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 |
|---|---|---|---|---|---|---|---|---|
Samuel789/MediPi | MedManagementWeb/env/lib/python3.5/site-packages/ruamel/yaml/scalarfloat.py | Python | apache-2.0 | 3,378 | 0.00148 | # coding: utf-8
from __future__ import print_function, absolute_import, division, unicode_literals
import sys
from .compat import no_limit_int # NOQA
if False: # MYPY
from typing import Text, Any, Dict, List # NOQA
__all__ = ["ScalarFloat", "ExponentialFloat", "ExponentialCapsFloat"]
class ScalarFloat(floa... | h, self._e_sign), file=out) # type: ignore
class ExponentialFloat(ScalarFloat):
def __new__(cls, value, width=None, underscore | =None):
# type: (Any, Any, Any) -> Any
return ScalarFloat.__new__(cls, value, width=width, underscore=underscore)
class ExponentialCapsFloat(ScalarFloat):
def __new__(cls, value, width=None, underscore=None):
# type: (Any, Any, Any) -> Any
return ScalarFloat.__new__(cls, value, wid... |
wandb/client | wandb/vendor/pygments/lexers/rdf.py | Python | mit | 9,398 | 0.00117 | # -*- coding: utf-8 -*-
"""
pygments.lexers.rdf
~~~~~~~~~~~~~~~~~~~
Lexers for semantic web and RDF query languages and markup.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups... | # PNAME_NS PN_LOCAL (with | simplified character range)
patterns['PrefixedName'] = r'%(PNAME_NS)s([a-z][\w-]*)' % patterns
tokens = {
'root': [
(r'\s+', Whitespace),
# Base / prefix
(r'(@base|BASE)(\s+)%(IRIREF)s(\s*)(\.?)' % patterns,
bygroups(Keyword, Whitespace, Name.Variable,... |
tudennis/LeetCode---kamyu104-11-24-2015 | Python/remove-duplicates-from-sorted-list-ii.py | Python | mit | 1,452 | 0.004132 | from __future__ import print_function
# Time: O(n)
# Space: O(1)
#
# Given a sorted linked list, delete all nodes that have duplicate numbers,
# leaving only distinct numbers from the original list.
#
# For example,
# Given 1->2->3->3->4->4->5, return 1->2->5.
# Given 1->1->1->2->3, return 2->3.
#
# Definition for s... | dummy = ListNode(0)
pre, cur = dummy, head
while cur:
if cur.next and cur.next.val == cur.val:
val = cur.val;
while cur and cur.val == val:
cur = cur.next
pre.next = cur
else:
pre.next = c... | = "__main__":
head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
print(Solution().deleteDuplicates(head))
|
v-legoff/pa-poc3 | src/service/default/wiki.py | Python | bsd-3-clause | 10,806 | 0.005552 | # Copyright (c) 2012 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and ... | deleted and its content (the second group) is copied into a
temporary field and paste in the original text, unchanged, at the end of the process.
"""
self.exceptions.append((start, end, options))
def add_markup(self, name, markup, html):
| """Add a new markup.
A wiki markup is by default close to a HTML markup. It should
begin with > (<), end with < (>). To close the markup
after the text to select, it use another > followed
by /, the markup and the < symbol.
These three symbol... |
Robpol86/libnl | libnl/nl80211/iw_scan.py | Python | lgpl-2.1 | 29,804 | 0.001711 | """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17.
Copyright (c) 2015 Robert Pooley
Copyright (c) 2007, 2008 Johannes Berg
Copyright (c) 2007 Andy Lutomirski
Copyright (c) 2007 Mike Kershaw
Copyright (c) 2008-2009 Luis R. Rodriguez
Permission to use, copy, modify, and/or distribute ... | on'
if data[0] & 0x04:
return 'Barker_Preamble_Mode'
return ''
def get_cipher(data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
| Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string).
"""
legend = {0: 'Use group cipher suite', 1: 'WEP-40', 2: 'TKIP', 4: 'CCMP', 5: 'WEP-104', }
key = data[3]
if ieee80211_oui == bytes(data[:3]):
legend.update({6: 'AE... |
IvarsKarpics/mxcube | gui/bricks/TaskToolBoxBrick.py | Python | lgpl-3.0 | 8,196 | 0.000488 | #
# Project: MXCuBE
# https://github.com/mxcube
#
# This file is part of MXCuBE software.
#
# MXCuBE is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your... |
self.ispyb_logged_in = logged_in
if HWR.beamline.session is not None:
HWR.beamline.session.set_user_group("")
self.setEnabled(logged_in)
self.task_tool_box_widget.ispyb_logged_in(logged_in)
def property | _changed(self, property_name, old_value, new_value):
if property_name == "useOscStartCbox":
self.task_tool_box_widget.use_osc_start_cbox(new_value)
elif property_name == "useCompression":
self.task_tool_box_widget.enable_compression(new_value)
elif property_name == "showC... |
hongquan/saleor | saleor/dashboard/customer/urls.py | Python | bsd-3-clause | 234 | 0 | from django.conf.ur | ls import patterns, url
from . import views
urlpatterns = patter | ns(
'',
url(r'^$', views.customer_list, name='customers'),
url(r'^(?P<pk>[0-9]+)/$', views.customer_details, name='customer-details')
)
|
ypzhang/jusha | book/scripts/d2d_kernel/cumemcpy_to_direct_offset1.py | Python | lgpl-3.0 | 5,058 | 0.028865 | #!/usr/bin/python
import numpy as np
#a = np.linspace(0.,10.,100)
#b = np.sqrt(a)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import csv
def import_text(filename, separator):
for line in csv.reader(open(filename), delimiter=separator,
skipinitialspace... | har_bw
#print float_bw
#print float
# start drawing
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title("cuMemcpy v.s. d2d_direct_kernel (address not aligned)");
ax.set_xlabel(table[0][0])
ax.set_ylabel('Bandwidth (GB/sec)')
#print len(size_st | ring)
#print len(char_bw)
fig.add_subplot(ax)
#ax.set_ylim([180,260])
print size_np
print size_string
#ax.set_xticklabels(size_np, range(len(size_np)))
ax.set_xticklabels(size_string)
#fig.xticks(size_np, size_string)
#ax.set_xticks(size_np, ('128K', '256K', '512K', '1M', '2M', '4M', '8M', '16M', '32M', '64M'))
#ax.... |
MHendricks/Motionbuilder-Remote | iphelper.py | Python | mit | 3,612 | 0.027409 | # A Gui interface allowing the binary illiterate to figure out the ip address the Arduino has been assigned.
import os
import re
from PySide.QtCore import QFile, QMetaObject, QSignalMapper, Slot, QRegExp
from PySide.QtGui import QDialog, QPushButton, QRegExpValidator
from PySide.QtUiTools import QUiLoader
class IPHel... | SecondTetTXT, self.uiThirdTetTXT, self.uiFourthTetTXT):
edit.setProperty('active', False)
if index == 12:
val = int(self.uiFourthTetTXT.text())
self.uiFourthTetTXT.setProperty('active', True)
elif index == 13:
val = int(self.uiThirdTetTXT.text())
self.uiThirdTetTXT.setProperty('active', True)
elif ... | elif index == 15:
val = int(self.uiFirstTetTXT.text())
self.uiFirstTetTXT.setProperty('active', True)
for i in range(8):
b = self.buttons[i]
b.blockSignals(True)
b.setChecked(2**i & val)
b.blockSignals(False)
# force a refresh of the styleSheet
self.setStyleSheet(self.styleSheet())
@Slot()
... |
Pakoach/Sick-Beard | sickbeard/databases/mainDB.py | Python | gpl-3.0 | 33,825 | 0.005026 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | self.connection.action("DELETE FROM tv_shows WHERE show_id = ?", [cur_dupe_id["show_id"]])
else:
logger.log(u"No duplicate show, check passed")
def fix_duplicate_episodes(self):
sqlResults = self.connection.select("SELECT showid, season, episode, COUNT(showid) as count FROM ... | , season, episode HAVING count > 1")
for cur_duplicate in sqlResults:
logger.log(u"Duplicate episode detected! showid: " + str(cur_duplicate["showid"]) + u" season: " + str(cur_duplicate["season"]) + u" episode: " + str(cur_duplicate["episode"]) + u" count: " + str(cur_duplicate["count"]), logger.... |
shashankrajput/seq2seq | seq2seq/test/attention_test.py | Python | apache-2.0 | 3,532 | 0.005663 | # Copyright 2017 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,... | ule.
"""
def setUp(self):
super(AttentionLayerTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_siz | e = 8
self.attention_dim = 128
self.input_dim = 16
self.seq_len = 10
self.state_dim = 32
def _create_layer(self):
"""Creates the attention layer. Should be implemented by child classes"""
raise NotImplementedError
def _test_layer(self):
"""Tests Attention layer with a given score type... |
mattgd/UnitConverter | units/__init__.py | Python | mit | 1,001 | 0 | # -*- coding: utf-8 -*-
from converters.circle import circle
from converters.currency import currency
from converters.electric import electric
from converters.force import force
from converters.pressure import pressure
from converters.speed import speed
from converters.temperature import temperature
class UnitsManage... | ter(self, converter):
"""
Met | hod that receives a new converter and adds it to
this manager.
Useful to add custom new methods without needing to edit
the core of this application.
"""
if converter is not None and callable(converter):
self._units.append(converter)
UNITS = UnitsManager()
|
hujiajie/chromium-crosswalk | tools/telemetry/telemetry/testing/simple_mock.py | Python | bsd-3-clause | 3,810 | 0.013386 | # Copyright 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.
"""A very very simple mock object harness."""
from types import ModuleType
DONT_CARE = ''
class MockFunctionCall(object):
def __init__(self, name):
se... | ll)
call.WithArgs(*args)
return call
def _install_hook(self, func_name):
def handler(*args, **_):
got_call = MockFunctionCall(
func_name).WithArgs(*args).WillReturn(DONT_CARE)
if self._trace.next_call_index >= len(self._trace.expected_calls):
raise Exception(
'Call t... | calls[
self._trace.next_call_index]
expected_call.VerifyEquals(got_call)
self._trace.next_call_index += 1
for h in expected_call.when_called_handlers:
h(*args)
return expected_call.return_value
handler.is_hook = True
setattr(self, func_name, handler)
class MockTimer(obj... |
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/nltk/corpus/reader/chunked.py | Python | gpl-2.0 | 8,206 | 0.000731 | # Natural Language Toolkit: Chunked Corpus Reader
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# Edward Loper <edloper@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A reader for corpora that contain chunked (and optionally tagged)
... | words and punctuation symbols, encoded as tuples
``(word,tag)``.
:rtype: list(tuple(str,str))
"""
return concat([ChunkedCo | rpusView(f, enc, 1, 0, 0, 0, *self._cv_args)
for (f, enc) in self.abspaths(fileids, True)])
def tagged_sents(self, fileids=None):
"""
:return: the given file(s) as a list of
sentences, each encoded as a list of ``(word,tag)`` tuples.
:rtype: list(list(tup... |
consbio/parserutils | parserutils/dates.py | Python | bsd-3-clause | 989 | 0 | import datetime
from dateutil import parser
from .numbers import is_number
from .strings import STRING_TYPES
DATE_TYPES = (datetime.date, datetime.datetime)
def parse_dates(d, default='today'):
""" Parses one or more dates from d """ |
if default == 'today':
default = datetime.datetime.today()
if d is None:
return default
elif isinstance(d, DATE_TYPES):
return d
elif is_number(d):
# Treat as milliseconds since 1970
d = d if isinstance(d, float) else float(d)
return datetime.datetime... | n default
elif len(d) == 0:
# Behaves like dateutil.parser < version 2.5
return default
else:
try:
return parser.parse(d)
except (AttributeError, ValueError):
return default
|
opendaylight/faas | demos/env_mininet/lsw1Demo.py | Python | epl-1.0 | 6,912 | 0.012297 | #!/usr/bin/python
import argparse
import requests,json
from requests.auth import HTTPBasicAuth
from subprocess import call
import time
import sys
import os
from vas_config_sw1 import *
DEFAULT_PORT='8181'
USERNAME='admin'
PASSWORD='admin'
OPER_OVSDB_TOPO='/restconf/operational/network-topology:network-topology/topo... | print r.text
r.raise_for_status()
def post(host, port, uri, data, debug=False):
'''Perform a POST rest operation, using the URL and data provided'''
url='http://'+host+":"+port+uri
headers = {'Content-type': 'application/yang.data+json',
'Accept': 'application/yang.data+json'}
... | ata), headers=headers, auth=HTTPBasicAuth(USERNAME, PASSWORD))
if debug == True:
print r.text
r.raise_for_status()
# Main definition - constants
# =======================
# MENUS FUNCTIONS
# =======================
# Main menu
# =======================
# MAIN PROGRAM
# ==============... |
mjwestcott/PyPokertools | tests/test_isomorph.py | Python | mit | 533 | 0.003752 | from examples.isomorph import (
get_all_canonicals,
get_canonical,
get_translation_dict,
)
from pokertools import cards_from_str as flop
def test_isomorph():
assert len(get_all_canonicals()) == 1755
assert get_canonical(flop('6s 8d | 7c')) == flop('6c 7d 8h')
assert get_translation_dict(flop('6s 8d 7c')) == {'c': 'd', 'd': 'h', 'h': 's', 's': 'c'}
assert get_canonica | l(flop('Qs Qd 4d')) == flop('4c Qc Qd')
assert get_translation_dict(flop('Qs Qd 4d')) == {'c': 'h', 'd': 'c', 'h': 's', 's': 'd'}
|
jistr/rejviz | rejviz/tests/test_utils.py | Python | apache-2.0 | 1,998 | 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 requ | ired | by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
import rejviz.tests.... |
jnewland/home-assistant | homeassistant/components/homematicip_cloud/weather.py | Python | apache-2.0 | 2,991 | 0 |
"""Support for HomematicIP Cloud weather devices."""
import logging
from homematicip.aio.device import (
AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries impor... | mematicIP Cloud weather sensor plus & basic."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the weather sensor."""
super().__init__(home, device)
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._device.label
@pro... | t:
"""Return the platform temperature."""
return self._device.actualTemperature
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def humidity(self) -> int:
"""Return the humidity."""
return ... |
SanketDG/coala-bears | tests/yml/RAMLLintBearTest.py | Python | agpl-3.0 | 602 | 0 | from bears.yml.RAMLLintBear import RAMLLintBear
from tests.LocalBearTestHelper import verify_local_bear
good_file = """
#%RAML 0.8
title: World Music API
baseUri: http://example.api.com/{version}
version: v1
"""
bad_file = """#%RAML 0.8
title: Failing RAML
version: 1
baseUri: http://example.com
/resource | :
description: hello
post:
"""
RAMLLintBearTest = verify_local_bear(RAMLLintBear,
valid_files=(good_file,),
| invalid_files=(bad_file,),
tempfile_kwargs={"suffix": ".raml"})
|
LuoZijun/uOffice | temp/ooxmlx/samples/01_basic/parse.py | Python | gpl-3.0 | 697 | 0.001435 | import sys
import six
import logging
import ooxml
from ooxml import parse, serialize, importer
logging.basicConfig(filename='ooxml.log', level=logging.INFO)
if len(sys.argv) > 1:
file_name = sys.argv[1]
dfile = ooxml.read_from_file(file_name)
six.print_("\n-[HTML]-----------------------------\n")
... | six.print_("\n-[USED STYLES]----------------------\n")
six.print_(dfile.document.used_styles)
six.print_("\n-[USED FONT SIZES]------------------\n")
si | x.print_(dfile.document.used_font_size)
|
Sybrand/digital-panda | panda-tray/download.py | Python | mit | 12,881 | 0.000854 | from bucket.local import LocalProvider
import config
import statestore
import logging
import os
import threading
import traceback
import messages
from send2trash import send2trash
from worker import BaseWorker
class Download(BaseWorker):
def __init__(self, objectStore, outputQueue):
BaseWorker.__init__(se... | Info.hash,
| localMD)
else:
# we don't have any history of this file - and the hash
# from local differs from remote! WHAT DO WE DO!
logging.error('TODO: HASH differs! Which is which????: %r'
... |
nccgroup/lapith | controller/viewer_controller.py | Python | agpl-3.0 | 22,502 | 0.004 | # Nessus results viewing tools
#
# Developed by Felix Ingram, f.ingram@gmail.com, @lllamaboy
# http://www.github.com/nccgroup/lapith
#
# Released under AGPL. See LICENSE for more information
import wx
import os
from model.Nessus import NessusFile, NessusTreeItem, MergedNessusReport, NessusReport, NessusItem
... | ue.initial_output.splitlines()[7:])|replace("Plugin Output:", "Plugin Output::\n") }}
{% endif %}
Recommendation
--------------
References
----------
{% if vuln.item.info_dict["cve"] %}
CVE:
{% for cve in vuln.item.info_dict["cve"] %}
{{ cve }}: `http://web.nvd.nist.gov/view/vuln/detail?vulnId={{ cve }}`
... | o_dict["bid"] %}
{{ bid }}: `http://www.securityfocus.com/bid/{{ bid }}`
{%- endfor %}
{%- endif %}
{% if vuln.item.info_dict["xref"] %}
Other References:
{% for xref in vuln.item.info_dict["xref"] %}
{{ xref }}
{%- endfor %}
{%- endif %}
{% if vuln.item.info_dict["see_also"] %}
See also:
{% for xref in vul... |
maralla/completor.vim | pythonx/completers/lsp/action.py | Python | mit | 3,344 | 0.000299 | # -*- coding: utf-8 -*-
import re
import logging
from completor.utils import check_subseq
from .utils import parse_uri
word_pat = re.compile(r'([\d\w]+)', re.U)
word_ends = re.compile(r'[\d\w]+$', re.U)
logger = logging.getLogger("completor")
# [
# [{
# u'range': {
# u'start': {u'line': 273, u'ch... | e': {
# u'start': {u'line': 9, u'character': 0},
# u'end': {u'line': 10, u'character': 0}
# }
# }, {
# u'newText': u'\tfmt.Println()\n',
# u'range': {
# u'start': {u'line': 10, u'character': 0},
# u'end': {u'line... | 0}
# }
# }, {
# u'newText': u'}\n',
# u'range': {
# u'start': {u'line': 10, u'character': 0},
# u'end': {u'line': 10, u'character': 0}
# }
# }
# ]
# ]
def format_text(data):
if not data:
return
for item ... |
vasily-v-ryabov/ui-automation-course | 1_Lyalyushkin/objc_constants.py | Python | bsd-3-clause | 588 | 0 | from ctypes import POINTER
from ctypes import c_long
from ctypes import c_uint32
from ctypes import c_void_p
CFIndex = c_long
CFStringEncoding = c_uint32
CFString = c_void_p
CFArray = c_void_p
CFDictionary = | c_void_p
CFError = c_void_p
CFType = c_void_p
CFAllocatorRef = c_void_p
CFStringRef = POINTER(CFString)
CFArrayRef = POINTER(CFArray)
CFDictionaryRef = POINTER(CFDictionary)
CFErrorRef = POINTER(CFError)
CFTypeRef = POINTER(CFType)
kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
kCGWindowListOptionAll = 0
| kCGWindowListOptionOnScreenOnly = (1 << 0)
kCGNullWindowID = 0
|
AzamYahya/shogun | examples/undocumented/python_modular/multiclass_chaidtree_modular.py | Python | gpl-3.0 | 1,100 | 0.033636 | #!/usr/bin/env python
from numpy import array, dtype, int32
traindat = '../data/fm_train_real.dat'
testdat = '../data/fm_test_real.dat'
label_traindat = '../data/label_train_multiclass.dat'
# set both input attributes as continuous i.e. 2
feattypes = array([2, 2],dtype=int32)
parameter_list = [[traindat,testdat,labe... | ImportError:
print("Could not import Shogun modules")
return
# wrap features and labels into Shogun objects
feats_train=RealFeatures(CSVFile(train))
feats_test=RealFeatures(CSVFile(test))
train_labels=MulticlassLabels(CSVFile(labels))
# CHAID Tree formation with nom | inal dependent variable
c=CHAIDTree(0,feattypes,10)
c.set_labels(train_labels)
c.train(feats_train)
# Classify test data
output=c.apply_multiclass(feats_test).get_labels()
return c,output
if __name__=='__main__':
print('CHAIDTree')
multiclass_chaidtree_modular(*parameter_list[0])
|
knuu/competitive-programming | atcoder/agc/agc026_b.py | Python | mit | 517 | 0 | for _ in range(in | t(input())):
A, B, C, D = map(int, input().split())
if A < B or C + D < B:
print("No")
continue
elif C >= B - 1:
print("Yes")
continue
ret = []
s_set = set()
now = A
while True:
now %= B
if now in s_set:
print("Yes", ret)
... | ak
|
edibledinos/pwnypack | tests/test_packing.py | Python | mit | 4,642 | 0.004093 | import pytest
import pwny
target_little_endian = pwny.Target(arch=pwny.Target.Arch.unknown, endian=pwny.Target.Endian.little)
target_big_endian = pwny.Target(arch=pwny.Target.Arch.unknown, endian=pwny.Target.Endian.big)
def test_pack():
assert pwny.pack('I', 0x41424344) == b'DCBA'
def test_pack_format_with_e... | 4901244, b'\xfc\xfd\xfe\xff', pwny.Target.Endian.little
yield | check_short_form_unpack_endian, 'U', 4294901244, b'\xff\xfe\xfd\xfc', pwny.Target.Endian.big
def check_short_form_pack(f, num, bytestr):
assert getattr(pwny, f)(num) == bytestr
def check_short_form_pack_endian(f, num, bytestr, endian):
assert getattr(pwny, f)(num, endian=endian) == bytestr
def check_shor... |
jgmize/kuma | kuma/wiki/urls.py | Python | mpl-2.0 | 5,894 | 0.00017 | from django.conf.urls import include, url
from django.views.generic import TemplateView
from kuma.attachments.feeds import AttachmentsFeed
from kuma.attachments.views import edit_attachment
from . import feeds, views
from .constants import DOCUMENT_PATH_RE
# These patterns inherit (?P<document_path>[^\$]+).
documen... | ocuments'),
url(r'^/load/$',
views.misc.load_documents,
name='wiki | .load_documents'),
# Special pages
url(r'^/templates$',
views.list.templates,
name='wiki.list_templates'),
url(r'^/tags$',
views.list.tags,
name='wiki.list_tags'),
url(r'^/tag/(?P<tag>.+)$',
views.list.documents,
name='wiki.tag'),
url(r'^/new$',
... |
knutfrode/opendrift | examples/example_grid_time.py | Python | gpl-2.0 | 1,294 | 0.001546 | #!/usr/bin/env python
from datetime import timedelta
import numpy as np
from opendrift.readers import reader_basemap_landmask
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.models.oceandrift import OceanDrift
o = OceanDrift(loglevel=0) # Set loglevel to 0 for debug information
reader_norkys... | urcrnrlon=5.5, urcrnrlat=61.2,
resolution='h', projection='merc')
o.add_reader([reader_basemap, reader_norkyst])
# Seeding some particles
lons = np.linspace(4.4, 4.6, 10)
lats = np.linspace(60.0, 60.1, 10)
lons, lats | = np.meshgrid(lons, lats)
lons = lons.ravel()
lats = lats.ravel()
# Seed oil elements on a grid at regular time interval
start_time = reader_norkyst.start_time
time_step = timedelta(hours=6)
num_steps = 10
for i in range(num_steps+1):
o.seed_elements(lons, lats, radius=0, number=100,
time=star... |
kmee/bank-statement-reconcile | __unported__/account_invoice_reference/__openerp__.py | Python | agpl-3.0 | 6,213 | 0.000161 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | ile the references (name,
origin, free reference) and above all, to understand which field will be
copied in the reference field of the move and move lines.
The approach here is to state simple rules with one concern: consistency.
The reference of the move lines must be the number of the document at their very
origin ... | rce document from a ledger).
The description of a line should always be... well, a description. Not a number
or a cryptic reference.
It particularly fits with other modules of the bank-statement-reconcile series
as account_advanced_reconcile_transaction_ref.
Fields
------
Enumerating the information we need in an in... |
keishi/chromium | ui/gl/generate_bindings.py | Python | bsd-3-clause | 57,794 | 0.014759 | #!/usr/bin/env python
# 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.
"""code generator for GL/GLES extension wrangler."""
import os
import collections
import re
import sys
GL_FUNCTIONS = [
{ 'return... | urn_type': 'void',
'names': ['glBindFragDataLocationIndexed'],
'arguments':
'GLuint program, GLuint colorNumber, GLuint index, const char* name', },
{ 'return_type': 'void',
'names': ['glBindFramebufferEXT', 'glBindFramebuffer'],
'arguments': 'GLenum target, GLuint framebuffer', },
{ 'return_type': 'void'... | renderbuffer', },
{ 'return_type': 'void',
'names': ['glBindTexture'],
'arguments': 'GLenum target, GLuint texture', },
{ 'return_type': 'void',
'names': ['glBlendColor'],
'arguments': 'GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha', },
{ 'return_type': 'void',
'names': ['glBlendEquation'],
'... |
DT9/programming-problems | 2017/microsoft17/1.py | Python | apache-2.0 | 262 | 0.007634 | import sys
import numpy as np
| def check_symmetric(a, tol=1e-8):
return np.allclose(a, a.T, atol=tol)
for line in sys.stdin:
a = np.matrix(line)
f = check_symmetric(a)
if not f:
print("Not s | ymmetric")
else:
print("Symmetric")
|
skirpichev/omg | diofant/tests/printing/test_conventions.py | Python | bsd-3-clause | 3,727 | 0.000537 | from diofant import (Derivative, Function, Integral, bell, besselj, cos, exp,
legendre, oo, symbols)
from diofant.printing.conventions import requires_partial, split_super_sub
__all__ = ()
def test_super_sub():
assert split_super_sub('beta_13_2') == ('beta', [], ['13', '2'])
assert spli... | it_super_sub('beta_13') == ('beta', [], ['13'])
assert split_super_sub('x_a_b') == (' | x', [], ['a', 'b'])
assert split_super_sub('x_1_2_3') == ('x', [], ['1', '2', '3'])
assert split_super_sub('x_a_b1') == ('x', [], ['a', 'b1'])
assert split_super_sub('x_a_1') == ('x', [], ['a', '1'])
assert split_super_sub('x_1_a') == ('x', [], ['1', 'a'])
assert split_super_sub('x_1^aa') == ('x', [... |
jucimarjr/IPC_2017-1 | lista06/lista06_lista04_questao14.py | Python | apache-2.0 | 1,317 | 0.006897 | #---------------------------------------------------------------------------
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
# Prof. Jucimar Jr
# Gabriel de Queiroz Sousa 1715310044
# Lucas Gabriel Silveira Duarte 1715310053
# Matheus de Olive... | admite muitas variações, como l33t ou 1337.
# O uso do leet reflete uma subcultura relacionada ao mundo dos jogos de computador e internet,
# sendo muito usada para confundir os iniciantes e | afirmar-se como parte de um grupo. Pesquise
# sobre as principais formas de traduzir as letras. Depois, faça um programa que peça uma texto
# e transforme-o para a grafia leet speak.
#---------------------------------------------------------------------------
leet = (('a', '4'), ('l', '1'), ('e', '3'), ('s', '5'... |
Patola/Cura | cura/Settings/CuraContainerStack.py | Python | lgpl-3.0 | 18,426 | 0.011397 | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Any, cast, List, Optional
from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject
from UM.Application import Application
from UM.Decorators import override
from UM.FlameProfiler import pyqtSlot
from U... | pyqtContainersChanged)
def material(self) -> InstanceContainer:
return cast(InstanceContainer, self._containers[_ContainerIndexes.Material])
## Set the variant container.
#
# \param new_variant The new variant container. It is expected to have a "type" metadata entry with the value "variant... | (self, new_variant: InstanceContainer) -> None:
self.replaceContainer(_ContainerIndexes.Variant, new_variant)
## Get the variant container.
#
# \return The variant container. Should always be a valid container, but can be equal to the empty InstanceContainer.
@pyqtProperty(InstanceContainer,... |
haylesr/angr | tests/test_path_groups.py | Python | bsd-2-clause | 4,184 | 0.00478 | import nose
import angr
import logging
l = logging.getLogger("angr_tests.path_groups")
import os
location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
addresses_fauxware = {
'armel': 0x8524,
'armhf': 0x104c9, # addr+1 to force thumb
#'i386': 0x8048524, # comm... | nose.tools.assert_equal(len( | pg5.active), 0)
nose.tools.assert_equal(len(pg5.backdoor), 1)
nose.tools.assert_equal(len(pg5.auth), 2)
# now unstash everything
pg6 = pg5.unstash_all(from_stash='backdoor').unstash_all(from_stash='auth')
nose.tools.assert_equal(len(pg6.active), 3)
nose.tools.assert_equal(len(pg6.backdoor), 0)
... |
munhyunsu/UsedMarketAnalysis | ruliweb_analyzer/db_5th_group.py | Python | gpl-3.0 | 1,617 | 0.009895 | #!/usr/bin/env python3
import os # makedirs
import sys # argv, exit
import csv # Dic | tReader
def cutoffdict(cdict):
rdict = dict()
for key in cdict.keys():
candi = cdict[key]
top = max(candi, key = candi.get)
if candi[top] > (sum(candi.values())*0.5):
rdict[key] = top
return rdict
def groupbyprefix(src_path):
des_path = src_path.split('/')[-... | = open('./dbdays/' + des_path, 'w')
des_csv = csv.DictWriter(des_file, fieldnames = [
'ipprefix', 'district', 'city'])
des_csv.writeheader()
cdict = dict()
for row in src_csv:
cprefix = row['ipprefix']
ccity = row['district'] +' ' + row['city']
cdict[cprefix] = {cci... |
joachimmetz/dfvfs | dfvfs/path/ewf_path_spec.py | Python | apache-2.0 | 777 | 0.005148 | # -*- coding: utf-8 -*-
"""The EWF image path specification implementation."""
from dfvfs.lib import defin | itions
from dfvfs.path import factory
from dfvfs.path import path_spec
class EWFPathSpec(path_spec.PathSpec):
"""EWF image path specification."""
TYPE_INDICATOR = definitions.TYPE_INDICATOR_EWF
def __init__(self, parent=None, **kwargs):
"""Initializ | es a path specification.
Note that the EWF file path specification must have a parent.
Args:
parent (Optional[PathSpec]): parent path specification.
Raises:
ValueError: when parent is not set.
"""
if not parent:
raise ValueError('Missing parent value.')
super(EWFPathSpec, s... |
CacaoMovil/guia-de-cacao-django | cacao_app/configuracion/forms.py | Python | bsd-3-clause | 762 | 0.001316 | # -*- coding: utf-8 -*-
from collections import OrderedDict
from django import forms
from django.utils.translation import ugettext_lazy as _
from envelope.forms import ContactForm
class ContactForm(ContactForm):
template_name = "envelope/contact_email.txt"
html_template_name = "envelope/contact_email.html"... | ='País', required=False)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['email'].required = False
ContactForm.base_fields = OrderedDict(
(k, ContactForm.base_fields[k])
for k in [
'sender', 'subject', 'ema | il', 'phone', 'country', 'message',
]
)
|
HMSBeagle1831/rapidscience | rlp/bookmarks/templatetags/bookmarks.py | Python | mit | 990 | 0.00202 | from django import template
register = template.Library()
@register.assignment_tag(takes_context=True)
def has_bookmark_permission(context, action):
"""Checks if the current user can bookmark the action item.
Returns a boolean.
Syntax::
{% has_bookmark_permis | sion action %}
"""
request = context['request']
if not request.user.is_authenticated():
return False
has_permission = True
if action.target.approval_required and not request.user.can_access_all_projects:
has_permission = False
if not has_permission:
return False
retur... | ting_bookmark(context, action):
request = context['request']
if not request.user.is_authenticated():
return None
existing_bookmark = request.user.bookmark_set.filter(
object_pk=action.action_object.pk, content_type=action.action_object_content_type
).first()
return existing_bookmark
|
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/nltk/cluster/util.py | Python | gpl-2.0 | 9,689 | 0.001858 | # Natural Language Toolkit: Clusterer Utilities
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Trevor Cohn <tacohn@cs.mu.oz.au>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_function, unicode_literals
import copy
from sys import stdout
from math import sqrt
try:... | f, n):
"""
Finds the n-groups of items (leaves) reachable from a cut at depth n.
:param n: number of groups
:type n: int
"""
if len(self._items) > 1:
root = _DendrogramNode(self._merge, *self._items)
else:
ro | ot = self._items[0]
return root.groups(n)
def show(self, leaf_labels=[]):
"""
Print the dendrogram in ASCII art to standard out.
:param leaf_labels: an optional list of strings to use for labeling the leaves
:type leaf_labels: list
"""
# ASCII rendering char... |
pmaupin/playtag | doc/make.py | Python | mit | 745 | 0.005369 | #!/usr/bin/env python
# REQUIRES both rst2pdf and wikir project from google code.
import sys
import subprocess
sys.path.insert(0, '../../rson/py2x')
from rson import loads
from simplejson import dumps
subprocess.call('../../rst2pdf/bin/rst2pdf manual.txt -e preprocess -e dotted_toc -o | manual.pdf'.split())
lines = iter(open('manual.txt', 'rb').read().splitlines())
badstuff = 'page:: space:: footer:: ##Page## contents::'.split()
result = []
for line in lines:
for check in badstuf | f:
if check in line:
break
else:
result.append(line)
result.append('')
result = '\n'.join(result)
from wikir import publish_string
result = publish_string(result)
f = open('manual.wiki', 'wb')
f.write(result)
f.close()
|
etutionbd/openfire-restapi | ofrestapi/system.py | Python | gpl-3.0 | 1,675 | 0.001194 | # -*- coding: utf-8 -*-
from requests import (get, post, delete)
from .base import Base
class System(Base):
def __init__(self, host, secret, endpoint='/plugins/restapi/v1/system/properties'):
"""
:param host: Scheme://Host/ for API requests
:param secret: Shared secret key for API request... | ncurrent_sessions(self):
"""
Retrieve concurrent sessions
"""
endpoint = '/'.join([self.endpoint.rpartition('/')[0], 'statistics', 's | essions'])
return self._submit_request(get, endpoint)
|
chayapan/django-sentry | tests/sentry/web/helpers/tests.py | Python | bsd-3-clause | 2,132 | 0.002345 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from django.contrib.auth.models import User
from sentry.constants import MEMBER_USER
from sentry.models import Project
from sentry.web.helpers import get_project_list
from tests.base import TestCase
class GetProjectListTEst(TestCase):
d... | blic=False)
@mock.patch('sentry.models.Team.objects.get_for_user', mock.Mock(return_value={}))
def test_includes_public_projects_without_access(self):
project_list = get_project_list(self.user)
self.assertEquals(len(project_list), 1)
self.assertIn(self.project.id, project_list)
@mo... | project_list = get_project_list(self.user, MEMBER_USER)
self.assertEquals(len(project_list), 0)
@mock.patch('sentry.models.Team.objects.get_for_user')
def test_does_include_private_projects_without_access(self, get_for_user):
get_for_user.return_value = {self.project2.team.id: self.project2.tea... |
schef/schef.github.io | source/11/mc-11-05-sk-mt.py | Python | mit | 3,429 | 0.022164 | #!/usr/bin/python
# Written by Stjepan Horvat
# ( zvanstefan@gmail.com )
# by the exercises from David Lucal Burge - Perfect Pitch Ear Traning Supercourse
# Thanks to Wojciech M. Zabolotny ( wzab@ise.pw.edu.pl ) for snd-virmidi example
# ( wzab@ise.pw.edu.pl )
import random
import time
import sys
import re
fname="/de... | ), nameNote(noteTwo).lower(), nameNote(noteThree).lower())
elif a.match(n):
| splitNote = n.split()
if splitNote[0] == nameNote(noteOne).lower() and splitNote[1] == nameNote(noteTwo).lower() and splitNote[2] == nameNote(noteThree).lower():
round += 1
print("Correct. Next round. " + str(round) + ".:")
done = True
match = True
... |
emmdim/guifiAnalyzer | plot/plotsServices.py | Python | gpl-3.0 | 4,467 | 0.004477 | #!/usr/bin/env python
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
#import matplotlib.dates as mdates
#import matplotlib.cbook as cbook
#from matplotlib import pyplot as plt
from matplotlib.dates import date2num
from statsmodels.distributions.empirical_distribution import ECDF
from colle... | s1, width, color='black')
ax1.set_xlim(-width, len(ind1) + width)
ax1.set_ylim(0, 0.7)
# ax.set_ylim(0,45)
# ax1.set_ylabel('Frequency')
#ax1.set_xlabel('Service Type')
ax1.set_title('Management Services Frequency')
xTickMarks1 = [str(i) for i in types1]
ax1.set_xticks(ind1 + width)
... | arks1)
plt.setp(xtickNames1, rotation=0, fontsize=13)
plt.show()
figfile = os.path.join(baseservicesdir, str(root) + "services_frequency")
fig.savefig(figfile, format='png', dpi=fig.dpi)
# Other categories
for s in g.services.values():
if s.type in mgmt:
s.type = "Management"
elif s.type != "Prox... |
arashzamani/lstm_nlg_ver1 | language_parser/SemanticVector.py | Python | gpl-3.0 | 679 | 0.002946 | # -*- coding: utf-8 -*-
import gensim, loggi | ng
class SemanticVector:
model = ''
def __init__(self, structure):
self.structure = structure
def model_word2vec(self, min_count=15, window=15, size=100):
print 'preparing sentences list'
sentences = self.structure.prepare_list_of_words_in_sentences()
print 'start modeli... | lf, name):
self.model.save(name)
def load_model(self, name):
self.model = gensim.models.Word2Vec.load(name)
|
jinzekid/codehub | 数据结构与算法/heap_sort/类定义操作定义堆结果以及排序.py | Python | gpl-3.0 | 2,192 | 0.008205 | # 类结构的堆排序
class DLinkHeap(object):
def __init__(self, list=None, N = 0):
self.dList = list
self.lengthSize = N
# 插入数据
def insert_heap(self, data):
self.dList.append(data)
self.lengthSize += 1
# 初始化堆结构
def init_heap(self):
n = self.lengthS... | self.swap(0, n-1)
n -= 1
self.sift_down(n)
# 打印堆数据
def print_heap(self, size):
for idx in range(size):
print(self.dList[idx], end=" ")
print()
if __name__ == "__main__":
k = 0
# 读取n个数
n = int(input())
# 输入列表
input_L = list(... | sort-----")
dLinkHeap.heap_sort()
dLinkHeap.print_heap(n)
|
avanzosc/odoo-addons | slide_channel_technology/models/__init__.py | Python | agpl-3.0 | 115 | 0 | from . import slide_chan | nel_technology_category
from . import slide_channel_technolog | y
from . import slide_channel
|
SoftFx/TTWebClient-Python | TTWebClientSample/public_currencies.py | Python | mit | 796 | 0.002513 | #!/usr/bin/python3
__author__ = 'ivan.shynkarenka'
import argparse
from TTWebClient.TickTraderWebClient import Tick | TraderWebClient
def main():
parser = argparse.ArgumentParser(description='TickTrader Web API sample')
parser.add_argument('web_api_address', help='TickTrader Web API address')
args = parser.parse_args()
# Create instance of the TickTrader Web API client
client = TickTraderWebClient(args.web_api_a... | public_currency(currencies[0]['Name'])
print("{0} currency precision: {1}".format(currency[0]['Name'], currency[0]['Precision']))
if __name__ == '__main__':
main() |
ramprasathdgl/TangoWithDjango | TangoWithDjango/rango/admin.py | Python | gpl-3.0 | 287 | 0.017422 | from django.c | ontrib import admin
# Register your models here.
from django.contrib import admin
from rango.models import Category, Page
class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'url')
admin.site.regis | ter(Category)
admin.site.register(Page,PageAdmin)
|
elivre/arfe | e2014/SCRIPTS/055-rede2014_rede_gephi_com_ipca_csv.py | Python | mit | 3,896 | 0.014117 | #!/usr/bin/env python
# coding: utf-8
# # rede_gephi_com_ipca_csv
# In[6]:
ano_eleicao = '2014'
rede =f'rede{ano_eleicao}'
csv_dir = f'/home/neilor/{rede}'
# In[7]:
dbschema = f'rede{ano_eleicao}'
table_edges = f"{dbschema}.gephi_edges_com_ipca_2018"
table_nodes = f"{dbschema}.gephi_nodes_com_ipca_2018"
table... | ute_query(edges_csv_query)
nodes_csv_query=f"""copy
(
select * from {table_nodes}
)
TO '{rede_dir_BR}/{rede}_Brasil_nodes. | csv' DELIMITER ';' CSV HEADER;
"""
mtse.execute_query(nodes_csv_query)
candidaturas_csv_query=f"""copy
(
select * from {table_candidaturas}
)
TO '{rede_dir_BR}/{rede}_Brasil_candidaturas.csv' DELIMITER ';' C... |
craigds/django-mpathy | tests/test_db_consistency.py | Python | bsd-3-clause | 2,474 | 0.000404 | import pytest
from django.db import connection, IntegrityError
from .models import MyTree
def flush_constraints():
# the default db setup is to have constraints DEFERRED.
# So IntegrityErrors only happen when the transaction commits.
# Django's testcase thing does eventually flush the constraints but to... | MyTree.objects.create(label='')
with pytest.raises(ValueError):
MyTree.objects.create(label=None)
with pytest.raises(ValueError):
MyTree.objects.create()
def test_root_node_already_exists(db):
MyTree.objects.create(label='root1')
with pytest.raises(IntegrityError):
MyTree.o... | e(label='root1')
def test_same_label_but_different_parent(db):
root1 = MyTree.objects.create(label='root1')
MyTree.objects.create(label='root1', parent=root1)
def test_same_label_as_sibling(db):
root1 = MyTree.objects.create(label='root1')
MyTree.objects.create(label='child', parent=root1)
with ... |
alogg/dolfin | test/unit/nls/python/PETScSNESSolver.py | Python | gpl-3.0 | 2,986 | 0.005023 | """Unit test for the SNES nonlinear solver"""
# Copyright (C) 2012 Patrick E. Farrell
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the ... | olfin import *
import unittest
try:
parameters["linear_algebra_backend"] = "PETSc"
except Run | timeError:
import sys; sys.exit(0)
parameters["form_compiler"]["quadrature_degree"] = 5
mesh = Mesh("doughnut.xml.gz")
V = FunctionSpace(mesh, "CG", 1)
bcs = [DirichletBC(V, 1.0, "on_boundary")]
u = Function(V)
v = TestFunction(V)
u.interpolate(Constant(-1000.0))
r = sqrt(triangle.x[0]**2 + triangle.x[1]**2)
rho ... |
quittle/bazel_toolbox | assert/scripts/assert_equal.py | Python | apache-2.0 | 4,276 | 0.005847 | # Copyright (c) 2016-2017 Dustin Doloff
# Licensed under Apache License v2.0
import argparse
import difflib
import hashlib
import os
import subprocess
import zipfile
# Resets color formatting
COLOR_END = '\33[0m'
# Modifies characters or color
COLOR_BOLD = '\33[1m'
COLOR_DISABLED = '\33[02m' # Mostly just means darke... | OW + bytes_to_str(sequence_mat | cher.a[a0:a1]) +
COLOR_DISABLED + bytes_to_str(sequence_matcher.b[b0:b1]) + COLOR_END)
diff = True
else:
raise RuntimeError('unexpected opcode ' + opcode)
return colorized_diff, diff
def hash_file(file):
"""
Computes the SHA-256 hash of the... |
depp/sggl | sggl.py | Python | bsd-2-clause | 232 | 0 | #!/usr/bin/env python3
# Copyright 2015 Dietrich Epp.
# This file is part of SGGL. SGGL is licensed under the terms | of the
# 2-clause BSD license. For more information, see LICENSE.tx | t.
import glgen.__main__
glgen.__main__.main()
|
wemanuel/smry | smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/instance_groups/managed/set_target_pools.py | Python | apache-2.0 | 3,208 | 0.004364 | # Copyright 2015 Google Inc. All Rights Reserved.
"""Command for setting target pools of instance group manager."""
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import utils
class SetT... | self.messages.InstanceGroupMan | agersSetTargetPoolsRequest(
targetPools=pools,
)
),
project=self.project,
zone=ref.zone,)
)
return [request]
SetTargetPools.detailed_help = {
'brief': 'Set instance template for instance group manager.',
'DESCRIPTION': """
... |
vivek8943/tracker_project | tracker_project/tracker/migrations/0001_initial.py | Python | mit | 1,059 | 0.002833 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Incident',
fields=[
... | )),
('closed', models.BooleanField(default=False)),
('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),
('created', models.DateTimeField(auto_now_add=True)),
], |
options={
},
bases=(models.Model,),
),
]
|
gltn/stdm | stdm/ui/wizard/profile_tenure_view.py | Python | gpl-2.0 | 67,557 | 0.000148 | """
/***************************************************************************
Name : ProfileTenureView
Description : A widget for rendering a profile's social tenure
relationship.
Date : 9/October/2016
copyright : John Kahiu
email ... | item = start_item
sel | f._end_item = end_item
self.base_width = base_width
if self.base_width is None:
self.base_width = 9.0
self._angle = tip_angle
if tip_angle is None:
self._angle = math.radians(50.0)
self.fill_arrow_head = fill_arrow_head
self.setPen(
... |
hackliff/domobot | kinect/pySVM/test/plotLinearSVC.py | Python | apache-2.0 | 1,628 | 0.0043 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
SVM-SVC (Support Vector Classification)
=========================================================
The classification application of the SVM is used below. The
`Iris <http://en.wikipedia.org/wiki/Iris_flower_data_set... | , yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
pl.figure(1, figsize=(4, 3))
pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired)
# Plot also the training points
pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
pl.xlabel('Sepal length')
pl.ylabel('Sepal width')
pl.xlim(xx.min(), | xx.max())
pl.ylim(yy.min(), yy.max())
pl.xticks(())
pl.yticks(())
pl.show()
|
ulif/pulp | server/test/unit/server/db/test_manage.py | Python | gpl-2.0 | 40,647 | 0.003174 | """
Test the pulp.server.db.manage module.
"""
from argparse import Namespace
from cStringIO import StringIO
import os
from mock import call, inPy3k, MagicMock, patch
from mongoengine.queryset import DoesNotExist
from ... import base
from pulp.common.compat import all, json
from pulp.server.db import manage
from pulp... | "defines an index for its unit key. This is "
"not allowed because the platform handlesit "
"for you.")
@patch.object(manage, 'ensure_database_indexes')
@patch('logging.config.fileConfig')
... | s', iter_entry_points)
@patch('pulp.server.db.manage.connection.initialize')
@patch('pulp.server.db.manage.factory')
@patch('pulp.server.db.manage.logging.getLogger')
@patch('pulp.server.db.manage.RoleManager.ensure_super_user_role')
@patch('pulp.server.db.manage.managers.UserManager.ensure_admin')
... |
jie/microgate | test_server.py | Python | mit | 1,151 | 0.001738 | from flask import Flask
from flask import request
from flask import jsonify
from flask import abort
import time
app = Flask(__name__)
@app.route('/api/1', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/api/1/<path:path>', methods=['GET', 'POST'])
def api1(path):
time.sleep(20)
return jsonify({
... | ds=['GET', 'POST'])
def api2(path):
return abort(400, 'you did a bad request')
@app.route('/api/3', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/api/3/<path:path>', methods=['GET', 'POST'])
def api3(path):
userId = request.args.get('userId')
return jsonify({
'userinfo': {
... | rinfo': {
'username': 'zhouyang'
}
})
if __name__ == '__main__':
app.run(port=1330, host='0.0.0.0')
|
liulion/mayavi | mayavi/tools/animator.py | Python | bsd-3-clause | 7,087 | 0.000564 | """
Simple utility code for animations.
"""
# Author: Prabhu Ramachandran <prabhu at aerodotiitbdotacdotin>
# Copyright (c) 2009, Enthought, Inc.
# License: BSD Style.
import types
from functools import wraps
try:
from decorator import decorator
HAS_DECORATOR = True
except ImportError:
HAS_DECORATOR = Fals... | = View(Group(Item('start'),
Item('stop'),
show_labels=False),
| Item('_'),
Item(name='delay'),
title='Animation Controller',
buttons=['OK'])
######################################################################
# Initialize object
def __init__(self, millisec, callable, *args, **kwargs):
... |
ilbay/PyMangaDownloader | Ui_NewMangaDialog.py | Python | gpl-2.0 | 2,334 | 0.003428 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'NewMangaDialog.ui'
#
# Created: Wed Jul 24 19:06:21 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except... | , disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, | text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_NewMangaDialog(object):
def setupUi(self, NewMangaDialog):
NewMangaDialog.setObjectName(_fromUtf8("NewMangaDialog"))
NewMangaDialog.resize(231, 78)
self.gridLayout = QtGui.QGridLayout(NewMangaDial... |
faarwa/EngSocP5 | zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Platform/darwin.py | Python | gpl-3.0 | 1,758 | 0.001706 | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008... | 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 Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright no... | 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 HOLDERS BE
# LIABLE FOR ANY... |
26fe/jsonstat.py | jsonstat/downloader.py | Python | lgpl-3.0 | 3,966 | 0.001261 | # -*- coding: utf-8 -*-
# This file is part of https://github.com/26fe/jsonstat.py
# Copyright (C) 2016-2021 gf <gf@26fe.com>
# See LICENSE file
# stdlib
import time
import os
import hashlib
# packages
import requests
# jsonstat
from jsonstat.exceptions import JsonStatException
class Downloader:
"""Helper clas... | .
Store the downloaded content into <cache_dir>/file.
If <cache_dir>/file exists, it returns content from disk
:param url: page to be downloaded
:param filename: filename where to store the content of url, None if we want not store
:param time_to_live: how many seconds to store... | 0 don't use cached version if any
:returns: the content of url (str type)
"""
pathname = self.__build_pathname(filename, url)
# note: html must be a str type not byte type
if time_to_live == 0 or not self.__is_cached(pathname):
response = self._... |
steelart/ask-navalny | django-backend/config/config.py | Python | mit | 148 | 0 | # Use default debug configuration or local configuration
try:
from .config_local impor | t *
except ImportErr | or:
from .config_default import *
|
zhanglongqi/pymodslave | ModSlaveSettingsRTU.py | Python | gpl-2.0 | 2,993 | 0.009021 | #-------------------------------------------------------------------------- | -----
# Name: ModSlaveSettingsRTU
# Purpose:
#
# Author: ElBar
#
# Created: 17/04/2012
# Copyright: (c) ElBar 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/us | r/bin/env python
from PyQt4 import QtGui,QtCore
from Ui_settingsModbusRTU import Ui_SettingsModbusRTU
import Utils
#add logging capability
import logging
#-------------------------------------------------------------------------------
class ModSlaveSettingsRTUWindow(QtGui.QDialog):
""" Class wrapper for RTU sett... |
sfloresk/NCA-Container-Builder | NCABase/app/sijax_handlers/single_access_handler.py | Python | apache-2.0 | 13,867 | 0.00786 | """
Helper for views.py
"""
from base_handler import base_handler
import traceback
import app.model
from flask import g, render_template
class single_access_handler(base_handler):
def __init__(self):
"""
Manages all the operations that are involved with a single port association with EPGs
... | tions()
self.exception = None
except Exception as e:
self.exception = e
print traceback.print_exc()
def get_create_single_access_networks(self, obj_response, form_values):
# Check if there has been connection errors
if self.exception is not None:
... | '" + str(self.exception).replace("'", "").
replace('"', '').replace("\n", "")[0:100] + "', 'danger', 0)")
return
# Load the sel_create_single_access_network select with the networks within the selected group
try:
network_ap = self.cobra_apic_o... |
boland1992/SeisSuite | seissuite/sort_later/find_holes.py | Python | gpl-3.0 | 17,030 | 0.021315 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 20 12:28:32 2015
@author: boland
"""
import sys
sys.path.append('/home/boland/Anaconda/lib/python2.7/site-packages')
import pickle
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans
import multiprocessing as mp
import pyproj
import os
... | s to be rotated and flipped
H = np.rot90(H)
H = np.flipud(H)
# Mask zeros
Hmasked = np.ma.masked_where(H | ==0,H) # Mask pixels with a value of zero
return Hmasked
#fig = plt.figure()
#plt.pcolormesh(xedges,yedges,Hmasked)
#plt.xlabel('longitude (degrees)')
#plt.ylabel('longitude (degrees)')
#cbar = plt.colorbar()
#cbar.ax.set_ylabel('Counts')
#fig.savefig(name)
def latitude... |
nkhare/rockstor-core | src/rockstor/storageadmin/views/network.py | Python | gpl-3.0 | 10,047 | 0.001294 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | ne)
nio.gateway = values.get('gateway', None)
nio.dns_servers = values.get('dns_servers', None)
nio.ctype = values.get('ctype', None)
nio.dtype = values.get('dtype', None)
nio.dspeed = values.get('dspeed', None)
nio.state = values.get('state', None)
return nio
... | /nginx/nginx.conf' % settings.ROOT_DIR
fo, npath = mkstemp()
with open(conf) as ifo, open(npath, 'w') as tfo:
for line in ifo.readlines():
if (re.search('listen.*80 default_server', line) is not None):
substr = 'listen 80'
if (ipaddr is... |
skimpax/python-rfxcom | tests/protocol/test_temperature.py | Python | bsd-3-clause | 3,484 | 0 | from unittest import TestCase
from rfxcom.protocol.temperature import Temperature
from rfxcom.exceptions import (InvalidPacketLength, UnknownPacketSubtype,
UnknownPacketType)
class TemperatureTestCase(TestCase):
def setUp(self):
self.data = bytearray(b'\x08\x50\x02\x11\x... | arser.load(self.data)
self.assertEquals(result, {
'packet_length': 8,
'packet_type': 80,
'packet_type_name': 'Temperature sensors',
| 'sequence_number': 17,
'packet_subtype': 2,
'packet_subtype_name':
'THC238/268,THN132,THWR288,THRN122,THN122,AW129/131',
'temperature': 16.7,
'id': '0x7002',
# 'channel': 2, TBC
'signal_level': 8,
'battery_level': 9
... |
ctongfei/nexus | torch/remove_classes.py | Python | mit | 259 | 0.003861 | #! /usr/bin/env python3
import sys
in_class = False
for l in sys.stdin:
if l.startswith("class"):
in_class = True
if in_class:
if l | .startswith("};"):
| in_class = False
continue
else:
print(l, end='')
|
shinexwang/Classy | Main/webParser.py | Python | apache-2.0 | 10,545 | 0.000379 | """
Copyright 2013 Shine Wang
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
distrib... | # this is mostly for Laurier courses
lec.building, lec.room = webData[index].split()
lec.instructor = webData[index+1].strip()
def endOfRow(self, data):
"""returns true if the current data-cell is the last cell
of this course; else - false"""
# the last cell is of ... | -##/## or
# "Information last updated
if re.search(r"\d+/\d+-\d+/\d+", data) or \
"Information last updated" in data:
return True
else:
return False
def postProcess(self, course):
"""this function will convert the class times to minutes-past-
... |
interhui/py_task | task/trigger/cron_trigger.py | Python | artistic-2.0 | 3,634 | 0.008255 | # coding=utf-8
'''
cron trigger
@author: Huiyugeng
'''
import datetime
import trigger
class CronTrigger(trigger.Trigger):
def __init__(self, cron):
trigger.Trigger.__init__(self, 0, 1);
self.cron = cron
def _is_match(self):
parser = CronParser(self.cron)
... |
if interval < 1:
interval = 1
if '*' in range_item:
temp_result.extend(self._add_to_set(min_val, max_val))
elif '-' in ran | ge_item:
item = range_item.split('-')
temp_result.extend(self._add_to_set(int(item[0]), int(item[1])))
else:
temp_result.append(int(range_item))
count = 0
for item in temp_result:
if count % interval... |
ioef/tlslite-ng | tlslite/recordlayer.py | Python | lgpl-2.1 | 29,445 | 0.001834 | # Copyright (c) 2014, Hubert Kario
#
# Efthimios Iosifidis - Speck Cipher Additions
# See the LICENSE file for legal information regarding use of this file.
"""Implementation of the TLS Record Layer protocol"""
import socket
import errno
import hashlib
from .constants import ContentType, CipherSuite
from .messages i... | self.seqnum += 1
return writer.bytes
class RecordLayer(object):
"""
Implementation of TLS record layer protocol
@ivar version: the TLS version to use (tuple encoded as on the wire)
@ivar sock: underlying socket
@ivar client: whether the conne | ction should use encryption
@ivar encryptThenMAC: use the encrypt-then-MAC mechanism for record
integrity
"""
def __init__(self, sock):
self.sock = sock
self._recordSocket = RecordSocket(sock)
self._version = (0, 0)
self.client = True
self._writeState = Connect... |
ddalex/p9 | sign/admin.py | Python | mit | 1,555 | 0.009646 | from django.contrib import admin
from django.contrib.admin.filters import RelatedFieldListFilter
from .models import ClientLog, Client, Feedback
def client_id(obj):
return obj.client.externid
class AliveClientsRelatedFieldListFilter(RelatedFieldListFilter):
def __init__(self, field, request, *args, **kwargs):... | ("status", "useragent", "failures", "complets")
ordering = ("status", "-updated", "-created", )
search_fi | elds = ("ip", "useragent", "externid", )
admin.site.register(Client, ClientAdmin)
class FeedbackAdmin(admin.ModelAdmin):
list_display = ("id", "useremail", "ip", "created")
ordering = ("-id",)
admin.site.register(Feedback, FeedbackAdmin)
|
AcerFeng/videoSpider | spider/models.py | Python | apache-2.0 | 2,458 | 0.003211 | from sqlalchemy import Column, String, BigInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
import time
BaseModel = declarative_base()
class Video(BaseModel):
__tablename__ = 'video'
id = Column(BigInteger, primary_key=True, autoincrement=True)
name = ... |
'link' : link.get('href')
}
# 视频类型:电视剧、电影、综艺
Video_large_type = Enum('Video_large_type', ('Series', 'Movies', 'Variety'))
# 电视剧类型:全部热播、内地、网剧、韩剧、美剧
Series_region = Enum('Series_region', ('All', 'Local', 'Net', 'SouthKorea', 'EuropeAndAmerica'))
# 电影类型:全部热播、院线、内地、香港、美国
Movie_region = Enum('M... | ty_type = Enum('Variety_type', ('Hot'))
"""
class RequestModel(object):
def __init__(self, source_url, platform, video_category, *, series_region=None, movie_region=None, veriety_region=None):
self.source_url = source_url
self.platform = platform
self.video_category = video_category
... |
icemoon1987/stock_monitor | model/turtle.py | Python | gpl-2.0 | 6,761 | 0.00419 | #!/usr/bin/env python
#coding=utf-8
import sys
sys.path.append("..")
import urllib
import myjson
from datetime import datetime, date, timedelta
import time
from define import *
from data_interface.stock_dataset import stock_dataset
class turtle(object):
"""
turtle model
"""
def get_mean(self, data, ... | date_str. If not exist, return.
data = dataset.get_data(date_str)
if data == None:
result["choise"] = -2
return result
data_index = dataset.get_data_index(date_str)
close_prices = [ item.close_price for item in data | set.data ]
result["close_price"] = close_prices[data_index]
result["10_mean"] = self.get_mean(close_prices, data_index, 10)
result["100_mean"] = self.get_mean(close_prices, data_index, 100)
result["50_max"] = self.get_max(close_prices, data_index, 50)
result["50_min"] = self.get_... |
benjyw/pants | src/python/pants/backend/python/lint/isort/skip_field.py | Python | apache-2.0 | 542 | 0 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.target_types import PythonLibrary, Pytho | nTests
from pants.engine.target import BoolField
class SkipIsortField(BoolField):
alias = "skip_isort"
default = False
help = "If true, don't run isort on this target's code."
def rules | ():
return [
PythonLibrary.register_plugin_field(SkipIsortField),
PythonTests.register_plugin_field(SkipIsortField),
]
|
tylerclair/canvas_admin_scripts | course_copy_csv.py | Python | mit | 684 | 0.00731 | import requests
import csv
from configparser import ConfigParser
config = ConfigParser()
config.read("config.cfg")
token = config.get("auth", "token")
domain = config.get("instance", "domain")
headers = {"Authorization" : "Bearer %s" % token}
source_course_id | = 311693
csv_file = ""
payload = {'migration_type': 'course_copy_importer', 'settings[source_course_id]': source_course_id}
with open(csv_file, 'rb') as courses:
coursesreader = csv.reader(courses)
for course in coursesreader:
u | ri = domain + "/api/v1/courses/sis_course_id:%s/content_migrations" % course
r = requests.post(uri, headers=headers,data=payload)
print r.status_code + " " + course |
Osmose/pontoon | pontoon/base/tests/test_placeables.py | Python | bsd-3-clause | 1,460 | 0.002055 | from django_nose.tools import assert_equal
from pontoon.base.tests import TestCase
from pontoon.base.utils import Newli | neEscapePlaceable, mark_placeables
class PlaceablesTests(TestCase):
def test_newline_escape_placeable(self):
"""Test detecting newline escape sequences"""
placeable = NewlineEscapePlaceable
assert_equal(placeable.parse(u'A string\\n')[1], placeable([u'\\n | ']))
assert_equal(placeable.parse(u'\\nA string')[0], placeable([u'\\n']))
assert_equal(placeable.parse(u'A\\nstring')[1], placeable([u'\\n']))
assert_equal(placeable.parse(u'A string'), None)
assert_equal(placeable.parse(u'A\nstring'), None)
def test_mark_newline_escape_placeables(... |
akretion/l10n-brazil | l10n_br_account/models/account_tax.py | Python | agpl-3.0 | 4,286 | 0 | # Copyright (C) 2009 - TODAY Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
class AccountTax(models.Model):
_inherit = 'account.tax'
fiscal_tax_ids = fields.Many2many(
comodel_name='l10n_br_fiscal.tax',
relation='l... | )
@api.multi
def compute_all(
self,
price_unit,
currency=None,
quantity=None,
product=None,
partner=None,
fiscal_taxes=None,
operation_line=False,
ncm=None,
nbm=None,
cest=None,
discount_value=None,
insuranc... | e,
fiscal_quantity=None,
uot=None,
icmssn_range=None
):
""" Returns all information required to apply taxes
(in self + their children in case of a tax goup).
We consider the sequence of the parent for group of taxes.
Eg. considering letters as ... |
jkthompson/block-chain-analytics | block.py | Python | mit | 10,671 | 0.023803 | import struct
import hashlib
magic_number = 0xD9B4BEF9
block_prefix_format = 'I32s32sIII'
def read_uint1(stream):
return ord(stream.read(1))
def read_uint2(stream):
return struct.unpack('H', stream.read(2))[0]
def read_uint4(stream):
return struct.unpack('I', stream.read(4))[0]
def read_uint8(stream):
... | super(Tx_Output, self).__init__()
pass
def parse(self, stream):
self.value = read_uint8(stream)
self.txout_script_len = read_varint(stream)
self.scriptPubKey = stream.read(self.txout_script_len)
def updateTxDict(self,txDict):
'''txDict holds arrays of Tx_O | utput values'''
txDict['txOut_value'] = txDict.get('txOut_value', [])
txDict['txOut_value'].append(self.value)
txDict['txOut_script_len'] = txDict.get('txOut_script_len', [])
txDict['txOut_script_len'].append(self.txout_script_len)
txDict['txOut_scriptPubKey'] = txDict.get('txOut_sc... |
synth3tk/the-blue-alliance | controllers/api/api_event_controller.py | Python | mit | 6,883 | 0.001017 | import json
import logging
import webapp2
from datetime import datetime
from google.appengine.ext import ndb
from controllers.api.api_base_controller import ApiBaseController
from database.event_query import EventListQuery
from helpers.award_helper import AwardHelper
from helpers.district_helper import DistrictHelp... | _key)
def _render(self, event_key):
self._set_event(event_key)
event_dict = ModelToDict.eventConverter(self.event)
return json.dumps(event_dict, ensure_ascii=True)
class ApiEventTeamsController(ApiEventController):
CACHE_KEY_FORMAT = "apiv2_event_teams_controller_{}" # (event_key)
... | al_cache_key = self.CACHE_KEY_FORMAT.format(self.event_key)
def _track_call(self, event_key):
self._track_call_defer('event/teams', event_key)
def _render(self, event_key):
self._set_event(event_key)
teams = filter(None, self.event.teams)
team_dicts = [ModelToDict.teamConverte... |
pympler/pympler | test/test_process.py | Python | apache-2.0 | 5,151 | 0.002136 | """
Check the measured process sizes. If we are on a platform which supports
multiple measuring facilities (e.g. Linux), check if the reported sizes match.
This should help to protect against scaling errors (e.g. Byte vs KiB) or using
the wrong value for a different measure (e.g. resident in physical memory vs
virtual... | faults, pi2.pagefaults)
if pi1.pagesize and pi2.pagesize:
self.assertEqual(pi1.pagesize, pi2.pagesize)
def test_ps_vs_proc_sizes(self):
'''Test process sizes match: ps util | vs /proc/self/stat
'''
psinfo = process._ProcessMemoryInfoPS()
procinfo = process._ProcessMemoryInfoProc()
self._match_sizes(psinfo, procinfo)
def test_ps_vs_getrusage(self):
'''Test process sizes match: ps util vs getrusage
'''
psinfo = process._ProcessMemo... |
fbradyirl/home-assistant | tests/components/homekit/common.py | Python | apache-2.0 | 317 | 0 | """Collection of fixtures and functions for the HomeKit t | ests."""
from unittest.mock import patch
def patch_debounce():
"""Return patch for debounce method."""
return patch(
"homeassistant.components.homekit.accessories.debounce",
lambda f: lambda | *args, **kwargs: f(*args, **kwargs),
)
|
userzimmermann/python-jinjatools | jinjatools/env.py | Python | gpl-3.0 | 1,555 | 0.001286 | # python-jinjatools
#
# Various tools for Jinja2,
# including new filters and tests based on python-moretools,
# a JinjaLoader class for Django,
# and a simple JinjaBuilder class for SCons.
#
# Copyright (C) 2011-2015 Stefan Zimmermann <zimmermann.code@gmail.com>
#
# python-jinjatools is free software: you can redistri... | = ['Environment']
from itertools import chain
import jinja2
class Environment(jinja2. | Environment):
def __init__(self, filters={}, tests={}, globals={}, **kwargs):
jinja2.Environment.__init__(self, **kwargs)
morefilters = __import__('jinjatools.filters').filters.filters
for name, func in chain(morefilters.items(), filters.items()):
self.filters[name] = func
... |
CenturylinkTechnology/ansible-modules-extras | clustering/consul_session.py | Python | gpl-3.0 | 9,707 | 0.001959 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, Steve Gargan <steve.gargan@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 th... | U General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
module: consul_session
short_description: "manipulate consul sessions"
description:
- allows the addition, modification and deletion of sessions in a consul
cluster. These sessions can then be used in co... | ng with
sessions can be found here http://www.consul.io/docs/internals/sessions.html
requirements:
- "python >= 2.6"
- python-consul
- requests
version_added: "2.0"
author: "Steve Gargan @sgargan"
options:
state:
description:
- whether the session should be present i.e. created if it does... |
haypo/trollius | tests/test_sslproto.py | Python | apache-2.0 | 2,350 | 0 | """Tests for asyncio/sslproto.py."""
try:
import ssl
except ImportError:
ssl = None
import trollius as asyncio
from trollius import ConnectionResetError
from trollius import sslproto
from trollius import test_utils
from trollius.test_utils import mock
from trollius.test_utils import unittest
@unittest.skipI... | (self):
self.loop = asyncio.new_event_loop()
self.set_event_loop(self.loop)
def ssl_protocol(self, waiter=None):
sslcontext = test_utils.dummy_ssl_context()
app_proto = asyncio.Protocol()
proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter)
self.add... |
def connection_made(self, ssl_proto, do_handshake=None):
transport = mock.Mock()
sslpipe = mock.Mock()
sslpipe.shutdown.return_value = b''
if do_handshake:
sslpipe.do_handshake.side_effect = do_handshake
else:
def mock_handshake(callback):
... |
LMescheder/AdversarialVariationalBayes | avb/iaf/models/full0.py | Python | mit | 698 | 0.004298 | import tensorflow as tf
| from tensorflow.contrib import slim as slim
from avb.ops import *
import math
def encoder(x, config, is_training=True):
df_dim = config['df_dim']
z_dim = config['z_dim']
a_dim = config['iaf_a_dim']
# Center x at 0
x = 2*x - 1
net = flatten_spatial(x)
net = slim.fully_connected(net, 300, a... | ftplus, scope="fc_0")
net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_1")
zmean = slim.fully_connected(net, z_dim, activation_fn=None)
log_zstd = slim.fully_connected(net, z_dim, activation_fn=None)
a = slim.fully_connected(net, a_dim, activation_fn=None)
return zmean,... |
gupon/ConnectorC4D | ConnectorC4D.py | Python | mit | 6,128 | 0.046671 | """
2015 gupon.jp
Connector for C4D Python Generator
"""
import c4d, math, itertools, random
from c4d.modules import mograph as mo
#userdata id
ID_SPLINE_TYPE = 2
ID_SPLINE_CLOSED = 4
ID_SPLINE_INTERPOLATION = 5
ID_ | SPLINE_SUB = 6
ID_SPLINE_ANGLE = 8
ID_SPLINE_MAXIMUMLENGTH = 9
ID_USE_SCREEN_DIST = 10
ID_USE_MAXSEG = 15
ID_MAXSEG_NUM = 13
ID_USE_CENTER = 19
ID_CENTER_OBJ = 18
class Point:
def __init__(self, p):
self.world = p
sel | f.screen = c4d.Vector(0)
def calc2D(self, bd):
self.screen = bd.WS(self.world)
self.screen.z = 0
class PointGroup:
def __init__(self):
self.points = []
def AddPoint(self, point):
self.points.append(Point(point))
def Make2DPoints(self):
bd = doc.GetRenderBaseDraw()
for point in self.points:
po... |
grlurton/hiv_retention_metrics | src/models/cohort_analysis_function.py | Python | mit | 4,874 | 0.008822 | import pandas as pd
import numpy as np
from dateutil.relativedelta import relativedelta
#### Utilities
def get_first_visit_date(data_patient):
''' Determines the first visit for a given patient'''
#IDEA Could be parallelized in Dask
data_patient['first_visit_date'] = min(data_patient.visit_date)
retur... | allelized in Dask
data_patient = get_first_visit_date(data_patient)
date_out = pd.NaT
date_last_appointment = pd.to_datetime(max(data_patient.next_visit_date))
late_time = reference_date - date_last_appointment
if late_time.days > | grace_period:
status = 'LTFU'
date_out = date_last_appointment
if late_time.days <= grace_period:
status = 'Followed'
if (data_patient.reasonDescEn.iloc[0] is not np.nan) & (pd.to_datetime(data_patient.discDate.iloc[0]) < reference_date):
status = data_patient.reasonDescEn.iloc[... |
MikeLing/shogun | examples/undocumented/python/graphical/classifier_perceptron_graphical.py | Python | gpl-3.0 | 2,302 | 0.032146 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import latex_plot_inits
parameter_list = [[20, 5, 1., 1000, 1, None, 5], [100, 5, 1., 1000, 1, None, 10]]
def classifier_perceptron_graphical(n=100, distance=5, learn_rate=1., max_iter=1000, num_threads=1, seed=None, nperceptrons=5):
from shog... | el(MSG_INFO)
np.random.seed(seed)
# Produce some (probably) linearly separable training data by hand
# Two Gaussians at a far enough distance
X = np.array(np.random.randn( | _DIM,n))+distance
Y = np.array(np.random.randn(_DIM,n))
label_train_twoclass = np.hstack((np.ones(n), -np.ones(n)))
fm_train_real = np.hstack((X,Y))
feats_train = RealFeatures(fm_train_real)
labels = BinaryLabels(label_train_twoclass)
perceptron = Perceptron(feats_train, labels)
perceptron.set_learn_rate(learn... |
spacy-io/spaCy | spacy/lang/ru/__init__.py | Python | mit | 905 | 0.001105 | from typing import Optional
from thinc.api import Model
from .stop_words import STOP_WORDS
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .lex_attrs import LEX_ATTRS
from .lemmatizer import RussianLemmatizer
from ...language import Language
class RussianDefaults(Language.Defaults):
tokenizer_excepti... | ENIZER_EXCEPTIONS
lex_attr_getters = LEX_ATTRS
stop_words = S | TOP_WORDS
class Russian(Language):
lang = "ru"
Defaults = RussianDefaults
@Russian.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={"model": None, "mode": "pymorphy2", "overwrite": False},
default_score_weights={"lemma_acc": 1.0},
)
def make_lemmatizer(
nlp: Language,
... |
WindowsPhoneForensics/find_my_texts_wp8 | find_my_texts_wp8/wp8_sms_integrated.py | Python | gpl-3.0 | 24,866 | 0.004987 | #! /usr/bin/env python
# Python script to parse SMStext messages from a Windows 8.0 phone's store.vol file
# Author: cheeky4n6monkey@gmail.com (Adrian Leong)
#
# Special Thanks to Detective Cindy Murphy (@cindymurph) and the Madison, WI Police Department (MPD)
# for the test data and encouragement.
# Thanks also to Jo... | TIME1][?][FILETIME2][?]["IPM.SMStext" string][1 byte][Sent Message][?][FILETIME3][?][FILETIME4]
? = unknown / varying number of bytes
All strings are Unicode UTF-16-LE and null terminated
FILETIMEs are 8 byte LE and record the number of 100 ns intervals since 1 JAN 1601 (ie MS FILETIME)
For MPD test data, there seems t... | 2 and "SMStext" for Sent SMS (0xB7 bytes between start of "IPM.SMStext" and start of
FILETIME2)
0xEA bytes between FILETIME2 and "SMStext" for Recvd SMS (subject to length of PHONE0)
For the supplied OHIO data, There seems to consistently be:
0xB4 bytes between FILETIME2 and "SMStext" for Sent SMS
0xDF bytes betwee... |
jawilson/home-assistant | homeassistant/components/utility_meter/__init__.py | Python | apache-2.0 | 7,390 | 0.000947 | """Support for tracking consumption over given periods of time."""
from datetime import timedelta
import logging
from croniter import croniter
import voluptuous as vol
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_NAME
from homeassistant.helpers import discov... | _METER_NET_CONSUMPTION,
CONF_METER_OFFSET,
CONF_METER_TYPE,
CONF_SOURCE_SENSOR,
CONF_TARIFF,
CONF_TARIFF_ENTITY,
CONF_TARIFFS,
DATA_TARIFF_SENSORS,
DATA_UTILITY,
DOMAIN,
METER_TYPES,
SERVICE_RESET,
SERVICE_SELECT_NEXT_TARIFF,
SERVICE_SELECT_TARIFF,
SIGNAL_RESET_ME... | "
DEFAULT_OFFSET = timedelta(hours=0)
def validate_cron_pattern(pattern):
"""Check that the pattern is well-formed."""
if croniter.is_valid(pattern):
return pattern
raise vol.Invalid("Invalid pattern")
def period_or_cron(config):
"""Check that if cron pattern is used, then meter type and of... |
EnigmaBridge/ebstall.py | ebstall/osutil.py | Python | mit | 18,396 | 0.002174 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import collections
import logging
import os
import platform
import re
import subprocess
import types
import util
import json
from ebstall.versions import Version
from ebstall.util import normalize_string
logger = logging.getLogger(__n... | ART_SYSTEMD = 'systemd'
# Pkg manager
PKG_YUM = 'yum'
PKG_APT = 'apt-get'
FAMILY_REDHAT = 'redhat'
FAMILY_DEBIAN = 'debian'
# redhat / debian
YUMS = ['redhat', 'fedora', 'ce | ntos', 'rhel', 'amzn', 'amazon']
DEBS = ['debian', 'ubuntu', 'kali']
class OSInfo(object):
"""OS information, name, version, like - similarity"""
def __init__(self, name=None, version=None, version_major=None, like=None, family=None,
packager=None, start_system=None, has_os_release=False, fal... |
wuga214/Django-Wuga | env/bin/viewer.py | Python | apache-2.0 | 1,056 | 0.000947 | #!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
| else:
import Tkinter as tkinter
from PIL import Image, ImageTk
#
# an image viewer
class UI(tkinter.Label):
def __init__(self, master, im):
if im.mode == "1":
# bitmap image
self.image = ImageTk.BitmapImage(im, foreground="wh | ite")
tkinter.Label.__init__(self, master, image=self.image, bd=0,
bg="black")
else:
# photo image
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bd=0)
#
# script interface
if __name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.