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 |
|---|---|---|---|---|---|---|---|---|
fraricci/pymatgen | pymatgen/analysis/phase_diagram.py | Python | mit | 84,602 | 0.000331 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines tools to generate and analyze phase diagrams.
"""
import re
import collections
import itertools
import math
import logging
from monty.json import MSONable, MontyDecoder
from functools ... | __repr__(self):
chempot_str = " ".join(["mu_%s = %.4f" % (el, mu)
for el, mu in self.c | hempots.items()])
return "GrandPotPDEntry with original composition " + \
"{}, energy = {:.4f}, {}".format(self.original_entry.composition,
self.original_entry.energy,
chempot_str)
def __str__(sel... |
EdDev/vdsm | vdsm/hooking.py | Python | gpl-2.0 | 2,647 | 0 | #
# | Copyright 2011-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat | er version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Li... |
phoebe-project/phoebe2-docs | 2.2/tutorials/detach.py | Python | gpl-3.0 | 2,387 | 0.008379 | #!/usr/bin/env python
# coding: utf-8
# Advanced: Detaching from Run Compute
# ============================
#
# Setup
# -----------------------------
# Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to ... | this parameter s | tores information on how to check the progress of the run_compute job and how to load the resulting model once it's complete
# In[5]:
b['mymodel']
# Re-attaching to a Job
# ------------------------------
#
# We can check on the job's status
# In[6]:
print(b['mymodel'].status)
# If we want, we can even save t... |
BStalewski/dontWasteTime | webapp/crawler_app/crawling/exceptions.py | Python | mit | 45 | 0 | class UnknownCrawler(RuntimeError):
pa | ss
| |
seblefevre/testerman | qtesterman/qtesterman.py | Python | gpl-2.0 | 872 | 0.002294 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# This file is part of Testerman, a test automation system.
# Copyright (c) 2009,2010 QTesterman contributors
#
# 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... | ater
# version.
# This program | is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
##
##
# Main QTesterman launcher.
# This is the script to run when you want to start QTester... |
gray-panda/grayrepo | 2020_flareon/04_report/soln.py | Python | gpl-2.0 | 2,149 | 0.007911 | def rigmarole(instr):
print("rigmarole %s" % instr)
i = 0
out = ""
while i < len(instr):
c1 = instr[i:i+2]
c2 = instr[i+2:i+4]
cc = int(c1,16) - int(c2, 16)
out += chr(cc)
# print("%s %s" % (c1, c2))
i += 4
return out
def ca... | ytes([tmp])
counter += 1
i += 4
return out
def main():
data = "9655B040B64667238524D15D6201.B95D4E01C55CC562C7557405A532D768C55FA12DD074DC697A06E172992CAF3F8A5C7306B7476B38.C555AC40A7469C234424.853FA85C470699477D3851249A4B9C4E.A855AF40B84695239D24895D2101D05CCA62BE... | 55B240B84692239624.CC55A940B44690238B24CA5D7501CF5C9C62B15561056032C468D15F9C2DE374DD696206B572752C8C3FB25C3806.A8558540924668236724B15D2101AA5CC362C2556A055232AE68B15F7C2DC17489695D06DB729A2C723F8E5C65069747AA389324AE4BB34E921F9421.CB55A240B5469B23.AC559340A94695238D24CD5D75018A5CB062BA557905A932D768D15F982D.D074B6696... |
live4thee/zstack-utility | zstacklib/zstacklib/iptables/iptables.py | Python | apache-2.0 | 10,071 | 0.00705 | '''
@author: frank
'''
from matches import *
from targets import *
from zstacklib.utils import log
from zstacklib.utils import shell
from zstacklib.utils import xmlobject
from zstacklib.utils import linux
import os
class IPTablesError(Exception):
'''iptables error'''
logger = log.get_logger(__name__)
clas... | elf.mat | ches.append(m)
self.match_classes[other_match_class.__name__] = m
action_objs = self.rule_xml_object.actions
for name, to in action_objs.get_children_nodes().items():
target_class = get_target(to.get_tag())
if not target_class:
raise IPTablesE... |
Pulgama/supriya | supriya/ugens/FBSineL.py | Python | mit | 887 | 0.001127 | import collections
from supriya import CalculationRate
from supriya.ugens.UGen import UGen
class FBSineL(UGen):
"""
A linear-interpolating feedback sine with chaotic phase indexing.
::
>>> fbsine_l = supriya.ugens.FBSineL.ar(
... a=1.1,
... c=0.5,
... fb=0.1,... | ... im=1,
... xi=0.1,
... yi=0.1,
... )
>>> fbsine_l
FBSineL.ar()
""" |
### CLASS VARIABLES ###
__documentation_section__ = "Chaos UGens"
_ordered_input_names = collections.OrderedDict(
[
("frequency", 22050),
("im", 1.0),
("fb", 0.1),
("a", 1.1),
("c", 0.5),
("xi", 0.1),
("yi", 0.1)... |
andresailer/DIRAC | WorkloadManagementSystem/Client/JobState/JobManifest.py | Python | gpl-3.0 | 8,502 | 0.010351 | """
"""
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.CFG import CFG
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
from DIRAC.Core.Utilities.JDL import loadJDLAsCFG, dumpCFGAsJDL
from DIRAC.WorkloadManagementSystem.Agent.SiteDirector import... | anifest=""):
self.__manifest = CFG()
self.__dirty = False
self.__ops = False
if manifest:
result = self.load(manifest)
if not result['OK']:
raise Exception(resul | t['Message'])
def isDirty(self):
return self.__dirty
def setDirty(self):
self.__dirty = True
def clearDirty(self):
self.__dirty = False
def load(self, dataString):
"""
Auto discover format type based on [ .. ] of JDL
"""
dataString = dataString.strip()
if dataString[0] == "["... |
kalrey/swift | swift/common/swob.py | Python | apache-2.0 | 50,266 | 0.00004 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 agree... | "%a, %d %b %Y %H:%M:%S GMT")
else:
self.headers[header] = value
return property(getter, setter,
doc=("Retrieve and set the %s header as a datetime, "
"set it with a datetime, int, or str | ") % header)
def _header_property(header):
"""
Set and retrieve the value of self.headers[header]
(Used by both request and response)
If a value of None is given, the header is deleted.
:param header: name of the header, e.g. "Transfer-Encoding"
"""
def getter(self):
return self.h... |
SlateScience/MozillaJS | js/src/testing/mozbase/mozfile/tests/test_tempfile.py | Python | mpl-2.0 | 2,461 | 0.001219 | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the M | ozilla 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/.
"""
tests for mozfile.NamedTemporaryFile
"""
import mozfile
import os
import unittest |
class TestNamedTemporaryFile(unittest.TestCase):
def test_iteration(self):
"""ensure the line iterator works"""
# make a file and write to it
tf = mozfile.NamedTemporaryFile()
notes = ['doe', 'rae', 'mi']
for note in notes:
tf.write('%s\n' % note)
tf.f... |
botswana-harvard/getresults-receive | getresults_receive/models/batch_item.py | Python | gpl-2.0 | 916 | 0.001092 | from django.db import models
from edc_base.model.models import BaseUuidModel
from getresults_patient.models import Patient
from .bat | ch import Batch
from .receive import ReceiveB | aseFieldsMixin
class BatchItem(ReceiveBaseFieldsMixin, BaseUuidModel):
batch = models.ForeignKey(Batch)
patient = models.ForeignKey(Patient)
collection_datetime = models.DateTimeField()
clinician_initials = models.CharField(
verbose_name='Clinician\'s initials',
max_length=3,
... |
SpreadBand/SpreadBand | apps/actors/migrations/0001_initial.py | Python | agpl-3.0 | 7,406 | 0.008372 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Actor'
db.create_table('actors_actor', (
('id', self.gf('django.db.models.fiel... | ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_leng | th': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_to... |
paulmadore/Eric-IDE | 6-6.0.9/eric/Debugger/DebuggerInterfacePython3.py | Python | gpl-3.0 | 43,276 | 0.003304 | # -*- coding: utf-8 -*-
# Copyright (c) 2009 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the Python3 debugger interface for the debug server.
"""
from __future__ import unicode_literals
import sys
import os
from PyQt5.QtCore import QObject, QTextCodec, QProcess, QProcessEnvironment... | bject):
"""
Class implementing the Python debugger interface for the debug server.
"""
def __init__(self, debugServer, passive):
"""
Constructor
@param debugServer reference to the debug server (DebugServer)
@param passive flag indicating passive connection mode | (boolean)
"""
super(DebuggerInterfacePython3, self).__init__()
self.__isNetworked = True
self.__autoContinue = False
self.debugServer = debugServer
self.passive = passive
self.process = None
self.qsock = None
self.queue =... |
stockminer/storm | base/monitor.py | Python | apache-2.0 | 923 | 0.019253 | #!encoding=utf-8
'''
Created on 2015年6月20日
@author: miaoyafei
'''
import jsonpickle as jspk
class Info(object):
'''
状态监控
| '''
def __init__(self):
self.id = 0 #监控id
self.group = 0 #所在组
self.up_time = '0000-00-00 00:00:00' #更新时间
self | .state_info = '' #状态信息
def get_value(self):
return "%d\t%d\t%s\t%s" %(self.id, self.group, self.up_time, self.state_info)
class Monitor(object):
def __init__(self):
self.infos = {}
def up_info(self, id, info):
self.infos[id] = info
def get_info(self, id):
return self.info... |
madgik/exareme | Exareme-Docker/src/mip-algorithms/PEARSON_CORRELATION/__init__.py | Python | mit | 52 | 0 | from .pearson import Pearson
__all__ = ["Pears | on"]
| |
SickGear/SickGear | sickbeard/processTV.py | Python | gpl-3.0 | 53,393 | 0.003409 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear 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,... | logger.log(u'Warning: unable to delete folder: %s: %s' % (folder, ex(e)), logger.WARNING)
return False
if ek.ek(os.path.isdir, folder):
logger.log(u'Warning: un | able to delete folder: %s' % folder, logger.WARNING)
return False
self._log_helper(u'Deleted folder ' + folder, logger.MESSAGE)
return True
def _delete_files(self, process_path, notwanted_files, force=False):
# type: (AnyStr, List[AnyStr], bool) -> Optional[bool]
"""
... |
eudoxos/woodem | lib/base/Colormap-local.py | Python | gpl-2.0 | 504 | 0.079365 | import numpy as np
import sys
from minieigen import *
pm=.1
sys.stdout.write('\t\tColormap{"red | -green-blue",{')
for a in np.linspace(0,1,255):
m=3*(a%(1/3.)) # relative within that third
i=int(a/(1/3.))
if i==3: i,m=2,1
c=[Vector3(.87,0,0),Vector3(0,.82,0),Vector3(.36,.58,1.)][i] # something isoluminant, by eye
c[i]-=( | 1-m)*pm
if a>0.: sys.stdout.write(',')
sys.stdout.write('%g,%g,%g'%(c[0],c[1],c[2]))
#print i,c[0],c[1],c[2]
sys.stdout.write('}}\n') # add comma if there are other colormaps
|
sanjuro/RCJK | vendor/django/contrib/formtools/wizard.py | Python | apache-2.0 | 10,209 | 0.001959 | """
FormWizard class -- implements a multi-page form, validating between each
step and storing the form's state as HTML hidden fields so that no state is
stored on the server side.
"""
import cPickle as pickle
from django import forms
from django.conf import settings
from django.http import Http404
from django.shortc... | t step, validate all of the forms one more
# time, as a sanity check, and call done().
num = self.num_steps | ()
if next_step == num:
final_form_list = [self.get_form(i, request.POST) for i in range(num)]
# Validate all the forms. If any of them fail validation, that
# must mean the validator relied on some other input, such as
# an external Web site.... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/papyon/gnet/proxy/SOCKS5.py | Python | gpl-3.0 | 60 | 0.016667 | ../../../../../../sha | re/pyshared/papyon/gnet | /proxy/SOCKS5.py |
choderalab/open-forcefield-group | qm/crank/nifty.py | Python | gpl-2.0 | 50,665 | 0.009908 | """@package forcebalance.nifty Nifty functions, intended to be imported by any module within ForceBalance.
Table of Contents:
- I/O formatting
- Math: Variable manipulation, linear algebra, least squares polynomial fitting
- Pickle: Expand Python's own pickle to accommodate writing XML etree objects
- Commands for sub... | def uncommadash(s):
# Takes a string like '27-31,88-91,100,136-139'
# and turns it into a list like [27, 28, 29, 30, 31, 88, 89, 90, 91, 100, 136, 137, 138, 139]
L = []
try:
for w in s.split(','):
| ws = w.split('-')
a = int(ws[0])-1
if len(ws) == 1:
b = int(ws[0])
elif len(ws) == 2:
b = int(ws[1])
else:
logger.warning("Dash-separated list cannot exceed length 2\n")
raise
if a < 0 ... |
adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/comment_tests/tests/feed_tests.py | Python | apache-2.0 | 1,316 | 0.00076 | import warnings
from django.test.utils import get_warnings_state, restore_warnings_state
from regressiontests.comment_tests.tests import CommentTestCase
class CommentFeedTests(CommentTestCase):
urls = 'regressiontests.comment_tests.urls'
feed_url = '/rss/comments/'
def test_feed(self):
response... | tom" version="2.0">')
self.assertContains(response, '<title>example.com comments</title>')
self.assertContains(response, '<link>http://example.com/</link>')
self.assertContains(response, '</rss>')
class LegacyCommentFeedTests(CommentFeedTests):
feed_url = '/rss/legacy/comments/'
def s... | t_warnings_state()
warnings.filterwarnings("ignore", category=DeprecationWarning,
module='django.contrib.syndication.views')
warnings.filterwarnings("ignore", category=DeprecationWarning,
module='django.contrib.syndication.feeds')
def ... |
bionikspoon/python_hangman | setup.py | Python | mit | 2,404 | 0.000832 | #!/usr/bin/env python
# coding=utf-8
"""
The full documentation is at https://python_hangman.readthedocs.org.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options... | .test_args = []
self.test_suite = True
def run_tests(self):
import pytest
i | mport sys
errno = pytest.main(self.test_args)
sys.exit(errno)
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['click', 'future']
test_requirements = ['pytest', 'mock']
setup( # :of... |
mgoubran/MeuralPaint | vgg.py | Python | gpl-3.0 | 1,993 | 0.003512 | # Copyright (c) 2015-2016 Anish Athalye. Released under GPLv3.
import tensorflow as tf
import numpy as np
import scipy.io
import pdb
MEAN_PIXEL = np.array([ 123.68 , 116.779, 103.939])
def net(data_path, input_image):
layers = (
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', '... | : weights are [width, height, in_channels, out_channels]
| # tensorflow: weights are [height, width, in_channels, out_channels]
kernels = np.transpose(kernels, (1, 0, 2, 3))
bias = bias.reshape(-1)
current = _conv_layer(current, kernels, bias)
elif kind == 'relu':
current = tf.nn.relu(current)
elif kind == 'poo... |
CompassionCH/compassion-modules | hr_attendance_management/models/hr_forced_due_hours.py | Python | agpl-3.0 | 1,647 | 0.001214 | # Copyright (C) 2018 Compassion CH
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api
class HrForcedDueHours(models.Model):
_name = "hr.forced.due.hours"
_description = "HR forced due hours"
_order = "date"
_sql_constraints = [
(
... | ds.Many2one(
"hr.employee", string="Employee", required=True, readonly=Fal | se
)
date = fields.Date("Date", required=True)
forced_due_hours = fields.Float("Forced due hours", required=True)
@api.model
def recompute_due_hours(self, employee_id, date):
return (
self.env["hr.attendance.day"]
.search([("employee_id", "=", employee_id), ("dat... |
young-geng/leet_code | problems/264_ugly-number-ii/main.py | Python | mit | 767 | 0.002608 | # https://leetcode.com/problems/ugly-number-ii/
import heapq |
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
def addToHeap(heap, dictionary, key):
if key in dictionary:
dictionary[key] += 1
else:
dictionary[ | key] = 1
heapq.heappush(heap, key)
if n == 1:
return 1
heap = [1]
seen = {1:1}
for i in xrange(1, n):
root = heapq.heappop(heap)
u2 = root*2
u3 = root*3
u5 = root*5
addToHeap(heap, seen, u2)
... |
daicang/Leetcode-solutions | 119-pascals-triangle-ii.py | Python | mit | 508 | 0.003937 | class Solution(object):
def getRow(self, rowIndex):
"""
| :type rowIndex: int
:rtype: List[int]
"""
rowIndex += 1
if rowIndex == 0:
return []
last_row = [1]
for i in range(1, rowIndex):
row = [1]
for j in range(1, i):
row.append(last_row[j-1]+last_row[j])
row.appe... | w
s = Solution()
print s.getRow(2)
print s.getRow(3)
|
yasir1brahim/OLiMS | models/search_ar.py | Python | agpl-3.0 | 7,325 | 0.017201 | # worksheet search on analysis basis.
from openerp import models, fields, api
from openerp.tools.translate import _
class SerachWroksheet(models.TransientModel):
_name = "olims.search_wroksheet"
_rec_name = "selection_type"
@api.multi
def _selection_services(self):
list_of_name = []
items_types_o... | manage_res:
ws_res_ids.append(item.id)
ids_list_ws = self.env['olims.worksheet'].search([('ManageResult', 'in', ws_res_ids)])
for ws_id in ids_list_ws:
ws_id_list.append(ws_id.id)
work_sheetids.append(ws_id_list)
else:
... | is_field)
,("LabService","=",int(analysis_field)), res_query_ar])
manage_analy_list = []
for ar_id in ids_list_ws_ar_res:
manage_analy_list.append(ar_id.id)
manage_analy_list
ids_list_ar_res = self.env["olims.ana... |
morskyjezek/BloggerSNATools | bloggerspider.py | Python | mit | 2,627 | 0.02322 | import requests
from urllib import urlopen
import urllib2
from bs4 import BeautifulSoup
root_url = raw_input('Enter the URL you want to search: ')
seed_post = root_url
def get_links_in_blogger_post():
response = requests.get(seed_post)
soup = BeautifulSoup(response.text)
return [a.attrs.get('href') for a in sou... | t_link()
if len(prevPost) > 1:
print 'This found more than one link to previous posts:',len(prevPost),'posts found.'
else:
print 'Link to previous post: '
for u in prevPost: print u
#count the posts found - not working
postCount = 0
#posts = page_soup.find_all('div.post-body')
#for post in posts:
# postCount +=... | ',numPosts,'posts.'
else:
print 'The post count is not working at this time.'
#get the links from a year's worth of posts based on the root_url, which should be specified as the blogger front page
archiveLinks = get_years_posts_from_blogger()
archiveLinkCount = 0
archiveLinkList = []
for link in archiveLinks:
prin... |
jmlopez-rod/assist | assist/__version__.py | Python | bsd-2-clause | 815 | 0.001227 | """assist version
version_info conforms to PEP 386
(major, minor, micro, alpha/beta/rc/final, #)
(1, 1, 2, 'alpha', 0) => "1.1.2.dev"
(1, 2, 0, 'beta', 2) => "1.2b2"
"""
VERSION_INFO = (0, 0, 1, 'beta', 5)
def get_version():
"""Return a PEP-386 compliant version number fr | om version_info."""
assert len(VERSION_INFO) == 5
assert VERSION_INFO[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if VERSION_INFO[2] == 0 else 3
main = '.'.join([str(part) for part in VERSION_INFO[:parts]])
sub = ''
if VERSION_INFO[3] == 'alpha' and VERSION_INFO[4] == 0:
sub = '.d... | RSION_INFO[4])
return str(main + sub)
VERSION = get_version()
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/operations/_vpn_gateways_operations.py | Python | mit | 32,694 | 0.004894 | # 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 may ... | ----------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_er | ror
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polli... |
AriZuu/micropython | tests/extmod/ubinascii_unhexlify.py | Python | mit | 546 | 0.003663 | try:
try:
import ubinascii as binascii
except ImportError:
| import binascii
except ImportError: |
print("SKIP")
raise SystemExit
print(binascii.unhexlify(b'0001020304050607'))
print(binascii.unhexlify(b'08090a0b0c0d0e0f'))
print(binascii.unhexlify(b'7f80ff'))
print(binascii.unhexlify(b'313233344142434461626364'))
try:
a = binascii.unhexlify(b'0') # odd buffer length
except ValueError:
print('Valu... |
dimfeld/gsutil | gslib/tests/test_signurl.py | Python | apache-2.0 | 10,904 | 0.004131 | # -*- coding: utf-8 -*-
# Copyright 2014 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 require... | b.tests.util import ObjectToURI as suri
from gslib.tests.util import unittest
# pylint: disable=protected-access
@unittest.skipUnless(HAVE_OPENSSL, 'signurl requires pyopenssl.')
@SkipForS3('Signed URLs are only supported for gs:// URLs.')
class TestSignUrl(testcase.GsUtilIntegrationTestCase):
"""Integration tests ... | and."""
def _GetJSONKsFile(self):
if not hasattr(self, 'json_ks_file'):
# Dummy json keystore constructed from test.p12.
contents = pkgutil.get_data('gslib', 'tests/test_data/test.json')
self.json_ks_file = self.CreateTempFile(contents=contents)
return self.json_ks_file
def _GetKsFile(se... |
luotao1/Paddle | python/paddle/fluid/incubate/fleet/base/role_maker.py | Python | apache-2.0 | 45,318 | 0.000574 | # Copyright (c) 2019 PaddlePaddle 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 app... | e NameError("generate_role() should be called first")
return True
def all_gather(self, input):
"""
all gather between trainers and pservers
Args:
input(int|float): input value
Returns:
| return a list of values
"""
if not self._role_is_generated:
self.generate_role()
retur |
shell909090/sshproxy | web/utils.py | Python | gpl-2.0 | 2,304 | 0.005208 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2014-07-02
@author: shell.xu
'''
import os, sys, json, logging
import bottle
from bottle import request, template, redirect
from db import *
logger = logging.getLogger('utils')
app = bottle.default_app()
sess = app.config.get('db.session')
LOGFMT = '%(asctime)s.%(m... | sions" % perm
return func(session, *p, **kw)
return _inner
return receiver
def jsonenc(func):
def _inner(*p, **kw):
try: r = func(*p, **kw)
exc | ept Exception, err:
r = {'errmsg': str(err)}
r = json.dumps(r)
logger.debug(r)
return r
return _inner
def log(logger, log):
session = request.environ.get('beaker.session')
logger.info(log)
sess.add(AuditLogs(username=session['username'], log=log))
def paged_template... |
cristilav/FLEQ | websocket-client.py | Python | agpl-3.0 | 15,128 | 0.012577 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management import setup_environ
import settings
setup_environ(settings)
import os
import sys
import time
import random
import datetime
from quizbowl.models import *
from quizbowl.views import notify_user
from django.contrib. | auth.model | s import User
from django.utils.html import escape
import httplib
import websocket
import threading
import time
import json
NUM_CORRECT = 10
QUESTIONS = 20
# NUM_CORRECT = 10
# QUESTIONS = 20
game_id = sys.argv[1]
# Extract quiz questions and fix the start time
game = Game.objects.get(pk=ga... |
dpazel/music_rep | tests/timemodel_tests/test_event_sequence.py | Python | mit | 5,287 | 0.006053 | import unittest
from timemodel.event_sequence import EventSequence
from timemodel.event import Event
from timemodel.position import Position
class TestEventSequence(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_successor(self):
es = EventSequence()... | es.print_maps()
assert es.successor(events[0]) == events[1]
assert es.successor(events[1]) == new_event
assert es.successor(new_event) == events[4]
assert es.successor(events[4]) is None
assert es.predecessor(events[4]) == new_event
assert es.prede... | (new_event) == events[1]
assert es.predecessor(events[1]) == events[0]
assert es.predecessor(events[0]) is None
assert es.first == events[0]
assert es.last == events[4]
es.move_event(new_event, Position(1, 8))
print('move (23, 3/4) to (23, 1/8)')
... |
nijel/weblate | weblate/utils/errors.py | Python | gpl-3.0 | 3,920 | 0.000766 | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | ised from requests.
if isinstance(error, JSONDecodeError) and not extra_log and hasattr(error, "doc"):
extra_log = repr(error.doc)
log("%s: %s: %s", cause, error.__class__.__name__, error)
if extra_log:
log("%s: %s: %s", cause, error.__class__.__name__, extra_log)
if print_tb:
L... | readcrumb only if settings are already loaded,
# we do not want to force loading settings early
if not settings.configured or not getattr(settings, "SENTRY_DSN", None):
return
sentry_sdk.add_breadcrumb(
category=category, message=message, level=level, data=data
)
def celery_base_data_h... |
rogalski/pylint | pylint/test/functional/assigning_non_slot.py | Python | gpl-2.0 | 3,455 | 0.004342 | """ Checks assigning attributes not found in class slots
will trigger assigning-non-slot warning.
"""
# pylint: disable=too-few-public-methods, no-init, missing-docstring, no-absolute-import, import-error
from collections import deque
from missing import Unknown
class Empty(object):
""" empty """
class Bad(objec... |
class UnicodeSlots(object):
"""Using unicode objects in __slots__ is okay.
On Python 3.3 onward, u'' is equivalent to '',
so this test should be safe for both versions.
"""
__slots__ = (u'first', u'second')
def __init__(self):
self.first = 42
| self.second = 24
class DataDescriptor(object):
def __init__(self, name, default=''):
self.__name = name
self.__default = default
def __get__(self, inst, cls):
return getattr(inst, self.__name, self.__default)
def __set__(self, inst, value):
setattr(inst, self.__name, ... |
talapus/Ophidian | Games/Hanoi/hanoi_prototype4.py | Python | bsd-3-clause | 486 | 0.002058 | def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper
hanoi(n - 1, source, target, hel | per)
# move disk from source peg to target peg
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
source = [9, 8, 7, 6, 5 | , 4, 3, 2, 1]
target = []
helper = []
hanoi(len(source), source, helper, target)
print source, helper, target
|
aperigault/ansible | test/integration/targets/sns_topic/files/sns_topic_lambda/sns_topic_lambda.py | Python | gpl-3.0 | 102 | 0 | from __future__ import p | rint_function
def handler(event, context):
print(event)
| return True
|
hunse/ctn_benchmarks | ctn_benchmark/benchmark.py | Python | gpl-2.0 | 5,043 | 0.001388 | from __future__ import absolute_import
import argparse
import importlib
import inspect
import logging
import os
import shelve
import time
import matplotlib.pyplot
import numpy as np
import nengo
class Benchmark(object):
def __init__(self):
self.parser = argparse.ArgumentParser(
... | me
def make_model(self, **kwargs):
p, fn = self.process_args(allow_cmdline=False, **kwargs)
np.random.seed(p.seed)
model = self.model(p)
return model
def record_speed(self, t):
now = time.time()
self.sim_speed = t / (now - self.start_time)
def run(self, **k... | fig(level=logging.ERROR)
print('running %s' % fn)
np.random.seed(p.seed)
model = self.model(p)
module = importlib.import_module(p.backend)
Simulator = module.Simulator
if p.backend == 'nengo_spinnaker':
import nengo_spinnaker
nengo_spinnaker.add_... |
TixLo/kademlia | lib/jsoncpp/devtools/fixeol.py | Python | gpl-3.0 | 1,974 | 0.019757 | from __future__ import print_function
import os.path
def fix_source_eol(path, is_dry_run = True, verbose = True, eol = '\n'):
"""Makes sure that all sources have the specified eol sequence (default: unix)."""
if not os.path.isfile(path):
raise ValueError('Path "%s" is not a file' % path)
try:
... | lly:
f.close()
fixed_lines = [line.rstrip('\r\n') + eol for line in raw_lines]
if raw_lines != fixed_lines:
print('%s =>' % path, end=' ')
if not is_dry_run:
f = open(path, "wb")
try:
f.writelines(fixed_lines)
finally:
f... | print(is_dry_run and ' NEED FIX' or ' FIXED')
return True
##
##
##
##def _do_fix(is_dry_run = True):
## from waftools import antglob
## python_sources = antglob.glob('.',
## includes = '**/*.py **/wscript **/wscript_build',
## excludes = antglob.default_excludes + './waf.py',
## ... |
rebearteta/social-ideation | connectors/migrations/0003_auto_20150423_1545.py | Python | mit | 393 | 0 | # -*- coding: utf-8 -*-
f | rom __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('connectors', '0002_parameter_description'),
]
operations = [
migrations.RenameField(
model_name='callback',
| old_name='type',
new_name='method',
),
]
|
netzulo/qacode | tests/002_benchmarks/__init__.py | Python | gpl-3.0 | 68 | 0 | # -*- coding: utf-8 -*- |
"""package qacode.tests | .002_benchmarks"""
|
lex128/mtasa-blue | vendor/curl/tests/python_dependencies/impacket/ntlm.py | Python | gpl-3.0 | 41,395 | 0.015098 | # Copyright (c) 2003-2016 CORE Security Technologies:
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
import base64
import struct
import calendar
import time
import hashlib
import random
import string
imp... | nature block on all messages. NTLMSSP_NEGOTIATE_ALWAYS_SIGN MUST be set in the
# NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. NTLMSSP_NEGOTIATE_ALWAYS_SI | GN is overridden
# by NTLMSSP_NEGOTIATE_SIGN and NTLMSSP_NEGOTIATE_SEAL, if they are supported. An alternate name for this field is
# NTLMSSP_NEGOTIATE_ALWAYS_SIGN.
NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000 # forces the other end to sign packets
NTLMSSP_RESERVED_6 = 0x0000400... |
peters/openalpr | src/bindings/python/openalpr/__init__.py | Python | agpl-3.0 | 26 | 0 | from openalpr import | Alpr
| |
shashankgroovy/cliwaka | setup.py | Python | gpl-3.0 | 1,168 | 0.001712 | from setuptools import setup, find_packages
from codecs import open
from os import path
current_dir = path.abspath(path.dirname(__file__))
with open(path.join(current_dir, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='cliwaka',
version='0.1.1',
description='Cliwaka is... | =[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
],
author='Shashank Srivastav',
author_email='shashankgrovy... | groovy/cliwaka',
download_url='https://github.com/shashankgroovy/cliwaka/archive/master.zip',
packages=find_packages(),
install_requires=[
'requests',
'argparse'
],
entry_points={
'console_scripts': [
'cliwaka=cliwaka.__main__:main',
],
},
)
|
snahelou/awx | awx/main/models/unified_jobs.py | Python | apache-2.0 | 42,104 | 0.00209 | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# Python
import codecs
import json
import logging
import re
import os
import os.path
from collections import OrderedDict
from StringIO import StringIO
# Django
from django.conf import settings
from dj | ango.db import models, connection
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django.utils.encoding import smart_text
from django.apps import apps |
from django.contrib.contenttypes.models import ContentType
# Django-Polymorphic
from polymorphic.models import PolymorphicModel
# Django-Celery
from djcelery.models import TaskMeta
# AWX
from awx.main.models.base import * # noqa
from awx.main.models.schedules import Schedule
from awx.main.models.mixins import Resou... |
DemokratieInBewegung/abstimmungstool | voty/initproc/globals.py | Python | agpl-3.0 | 4,009 | 0.002248 | from datetime import date
class NOTIFICATIONS:
"""
All internal notifications
"""
class INVITE:
SEND = "inivited"
ACCEPTED = "invite_accepted"
REJECTED = "invite_rejected"
class INITIATIVE:
EDITED = "init_edited"
SUBMITTED = "init_submitted"
PUBLISH... |
COMPARING_FIELDS = [
'title', 'subtitle', "summary", "problem", "forderung", "kosten",
"fin_vorschlag", "arbeitsweise", "init_argument",
"einordnung | ", "ebene", "bereich",
"motivation", "description", "budget"
]
ADMINISTRATIVE_LEVELS = [
'Bund',
'Baden-Württemberg',
'Bayern',
'Berlin',
'Brandenburg',
'Bremen',
'Hamburg',
'Hessen',
'Mecklenburg-Vorpommern',
'Niedersachsen',
'Nordrhein-Westfalen',
'Rheinland-Pfalz'... |
shanshanzhu/Data-Scrappers | USstock/stockcleanerOneFile.py | Python | mit | 1,444 | 0.029086 | # import urllib2
# fin = open('rawcsv/stockdata/stockdata.csv')
# fin.read()
#clean and merge data in one csv
from os import listdir
from os.path import isfile, join
mypath = './USstockHistory167Mb/'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and f[-3:] == 'csv' ]
print onlyfiles
ticker = '... | .write(line) # get the stock ticker and description
foutfinal.write('stockdata_84_06_eod' + '\n')
def secondheader(line):
csvlist = line.replace('# ', '').split(' ')
csvlist.inser | t(0, 'TICKER')
csvlist.insert(3, 'CLOSE')
csvline = ','.join(csvlist)
foutfinal.write(csvline)
foutmeta.write(csvline) # get column names
foutfinal.write('VARCHAR(10),DATE')
for i in xrange(len(csvlist) - 2):
foutfinal.write(',FLOAT4')
foutfinal.write('\n')
def findTicker(line):
global ticker
start = line.i... |
glyph/treq | treq/_utils.py | Python | mit | 940 | 0 | """
Strictly internal utilities.
"""
from __future__ import absolute_import, division, print_function
from twisted.web.client import HTTPConnectionPool
def default_reactor(reactor):
"""
Return the specified reactor or the default.
"""
if reactor is None:
from twisted.internet import reactor
... | bal_pool = [None]
def get_global_pool():
return _global_pool[0]
def set_global_pool(pool):
_global_pool[0] = pool
def default_pool(reactor, pool, persistent):
"""
Retu | rn the specified pool or a a pool with the specified reactor and
persistence.
"""
reactor = default_reactor(reactor)
if pool is not None:
return pool
if persistent is False:
return HTTPConnectionPool(reactor, persistent=persistent)
if get_global_pool() is None:
set_glo... |
openstack/os-collect-config | os_collect_config/tests/test_cfn.py | Python | apache-2.0 | 10,601 | 0 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | deployments': [
{
u'inputs': [
{
u'type': u'String',
u'name': u'input1',
u'value': u'value1'
}
],
u'group': 'Heat::Ungrouped',
u'name': 'dep-name1',
u'outputs':... | ,
u'config': {
u'config1': 'value1'
}
},
{
u'inputs': [
{
u'type': u'String',
u'name': u'input1',
u'value': u'value1'
}
],
u'group': 'os... |
alduxvm/pyMultiWii | demo/show-attitude.py | Python | gpl-3.0 | 1,095 | 0.008219 | #!/usr/bin/env python
"""show-attitude.py: Script to ask the MultiWii Board attitude and print it."""
__author__ = "Aldo Vargas"
__copyright__ = "Copyright 2017 Altax.net"
__license__ = "GPL"
__version__ = "1.1"
__maintainer__ = "Aldo Vargas"
__email__ = "alduxvm@gmail.com"
__status__ = "Development"
from pymultiwi... | name__ == "__main__":
#board = MultiWii("/dev/ttyUSB0")
board = MultiWii("/dev/tty.SLAB_USBtoUART")
try:
while True:
board.getData(MultiWii.ATTITUDE)
#print (board.attitude) #uncomment for regular printing
# Fancy printing (might not work on windows...) |
message = "angx = {:+.2f} \t angy = {:+.2f} \t heading = {:+.2f} \t elapsed = {:+.4f} \t".format(float(board.attitude['angx']),float(board.attitude['angy']),float(board.attitude['heading']),float(board.attitude['elapsed']))
stdout.write("\r%s" % message )
stdout.flush()
... |
jeremyarr/mooq | mooq/connect.py | Python | mit | 1,026 | 0.000975 | from .in_me | mory import InMemoryConnection
from .rabbit import RabbitMQConnection
async def connect(host="localhost", port=5672, broker="rabbit"):
'''
Create a connection object and then connect to a broker
:param host: the hostname of the broker you wish to connect to
:type host: str
:param port: the port o... | _memory" for an broker that resides in memory
(useful for unit testing)
:type broker: str
:return: :class:`InMemoryConnection` or :class:`RabbitMQConnection` object
.. todo:: raises BrokerConnectionError if cannot connect to the broker
'''
if broker == "in_memory":
conn = InMemory... |
adrn/StreamMorphology | scripts/freqmap/analyze.py | Python | mit | 5,960 | 0.010738 | # coding: utf-8
""" Analyze the output from frequency mapping """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os
# Third-party
import astropy.units as u
from astropy import log as logger
import matplotlib.pyplot as plt
import numpy as np
... | ))
if len(bounds) > 2:
bounds = (bounds[:2], bounds[2:])
else:
bounds = None
if args.vbounds is not None:
vbounds = map(float, args.vbound | s.split(","))
else:
vbounds = None
main(args.path, bounds=bounds, vbounds=vbounds)
|
AaltoML/kalman-jax | kalmanjax/archive/likelihoods.py | Python | apache-2.0 | 27,639 | 0.002437 | import jax.numpy as np
from jax.scipy.special import erf, erfc, gammaln
from jax.nn import softplus
from jax import jit, partial, jacrev, random
from jax.scipy.linalg import cholesky
from jax.scipy.stats import beta
from numpy.random import binomial
from numpy.polynomial.hermite import hermgauss
from utils import logph... | vₙ⁻¹] pᵃ(yₙ|xᵢ√(2vₙ) + mₙ)
d2Z = np.sum(
((sigma_points - m) ** 2 / v ** 2 - 1.0 / v)
* weighted_likelihood_eval
)
# d²logZₙ/dmₙ² = d[(dZₙ/dmₙ) / Zₙ]/dmₙ
# = (d²Zₙ/dmₙ² * Zₙ - (dZₙ/dmₙ)²) / Zₙ²
# = d²Zₙ/dmₙ² / Zₙ - (dlogZₙ/dmₙ)²
... | p75)
site_var = -power * (v + 1 / d2lZ) # approx. likelihood (site) variance
return lZ, site_mean, site_var
@partial(jit, static_argnums=0)
def moment_match(self, y, m, v, hyp=None, power=1.0):
"""
If no custom moment matching method is provided, we use Gauss-Hermite quadratur... |
David-Estevez/Parametric | Parametric/RecomputeParameters.py | Python | gpl-3.0 | 2,887 | 0.004509 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------#
# #
# This file is part of the Parametric Workbench #
# ... | #
#-----------------------------------------------------------------------#
__author__ = "David Estévez Fernández <david.estevez@bq.com>"
__license__ = "GNU General Public License v3 http://www.gnu.org/licenses/gpl.html"
import os
import FreeCAD, FreeCADGui
import Parameter
class Recom... | , 'icons', 'Force_Recompute.png')
return {'Pixmap' : icon_path, # the name of a svg file available in the resources
'MenuText': 'Recompute parameters',
'ToolTip' : 'Recompute all parameters in the document'}
def Activated(self):
for obj in Parameter.Parameter.getAva... |
grap/OCB | openerp/tests/test_mail.py | Python | agpl-3.0 | 20,377 | 0.006632 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This test can be run stand-alone with something like:
# > PYTHONPATH=. python2 openerp/tests/test_misc.py
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP... | POSE. See the
# GNU Affero General Public License for more details.
#
# You should have recei | ved a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import unittest2
from openerp.tools import html_sanitize, html_email_clean, append_content_to_html, plaintext2h... |
qyzxg/myblog | app/admin/__init__.py | Python | gpl-3.0 | 144 | 0.006944 | #!/usr/bin/python
# -*- coding:utf-8 -*-
from flask import Blueprint
admi | n = Blueprint('admin', __name__)
from . import views, forms
| |
ohtaman/pynm | pynm/feature/metric/itml.py | Python | mit | 2,733 | 0.000366 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from collections import defaultdict
from random import choice
import sys
import numpy
def sample_from_pairs(pairs):
num_pairs = len(pairs)
while True:
idx = numpy.random.randint(num_pairs)
yield pairs[idx]
def sample_from_labels(labels, balance=... | *alpha
beta = da/(1-da*p)
gsi_[i, j] *= slack/(slack + da*gsi)
lambda_[i, j] -= alpha
metric += beta * numpy.outer(m_d, m_d)
return metric
def sqrt_matrix(matrix):
u, s, v = numpy.linalg.svd(matrix)
return numpy.dot(u, numpy.dot(numpy.diag(numpy.sqrt(s)), v))
def convert_... | yield numpy.dot(sqrt_metric, a_data)
|
astra-toolbox/astra-toolbox | samples/python/s004_cpu_reconstruction.py | Python | gpl-3.0 | 2,550 | 0.002353 | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... | .figure(3)
pylab.imshow(rec)
pylab.show()
# Clean up.
astra.algorithm.delete(alg_id)
astra.data2d.delete(rec_id)
astra.data2d.delete(sinogram_id) |
astra.projector.delete(proj_id)
|
foreni-administrator/pyew | pefile.py | Python | gpl-2.0 | 187,331 | 0.012299 | # -*- coding: Latin-1 -*-
"""pefile, Portable Executable reader module
All the PE file basic structures are available with their default names
as attributes of the instance returned.
Processed elements such as the import table are made available with lowercase
names, to differentiate them from the upper case basic s... | to be retrieved from the f | ile.
# It's there to prevent loading massive amounts of data from memory mapped
# files. Strings longer than 1MB should be rather rare.
MAX_STRING_LENGTH = 0x100000 # 2^20
IMAGE_DOS_SIGNATURE = 0x5A4D
IMAGE_DOSZM_SIGNATURE = 0x4D5A
IMAGE_NE_SIGNATURE = 0x454E
IMAGE_LE_SIGNATURE ... |
sunu/oppia | extensions/rules/unicode_string.py | Python | apache-2.0 | 1,757 | 0 | # coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | f _evaluate(self, subject):
return subject.lower() == self.x.lower()
class CaseSensitiveEquals(base.UnicodeStringRule):
description = 'is equal to {{x|UnicodeString}}, taking case into account'
def _evaluate(self, subject):
return subject == self.x
class StartsWith(base.UnicodeStringRule):
... | f _evaluate(self, subject):
return subject.lower().startswith(self.x.lower())
class Contains(base.UnicodeStringRule):
description = 'contains {{x|UnicodeString}}'
def _evaluate(self, subject):
return subject.lower().find(self.x.lower()) != -1
class MatchesBase64EncodedFile(base.UnicodeStrin... |
laslabs/Python-Carepoint | carepoint/models/cph/fdb_pem_mogc.py | Python | mit | 643 | 0.001555 | # -*- coding: utf-8 -*-
# Copyright 2015-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from carepoint import Carepoint
from sqlalchemy import (Column,
Integer,
Boolean,
ForeignKey,
| )
class FdbPemMogc(Carepoint.BASE):
__tablename__ = 'fdrpemogc'
__dbname__ = 'cph'
gcn_seqno = Column(
Integer,
| primary_key=True,
autoincrement=False,
)
pemono = Column(
Integer,
ForeignKey('fdrpemmoe.pemono'),
primary_key=True,
)
update_yn = Column(Boolean)
|
dhermes/gcloud-python | logging/tests/unit/test__gapic.py | Python | apache-2.0 | 22,304 | 0.000986 | # Copyright 2016 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 in writing, s... | "textPayload": "text",
}
api.write_entries([entry])
# Check the request
assert len(channel.WriteLogEntries.requests) == 1
request = channel.WriteLogEntries.requests[0]
assert request.partial_success is False
assert len(request.entries) == 1
a... | y["resource"]["type"]
assert request.entries[0].text_payload == "text"
def test_logger_delete(self):
channel, api = self.make_logging_api()
channel.DeleteLog.response = empty_pb2.Empty()
api.logger_delete(PROJECT, self.LOG_NAME)
assert len(channel.DeleteLog.requests) == 1... |
postfix/sceadan | tools/extract_filename.py | Python | gpl-2.0 | 475 | 0.048421 |
import sys,os
from commands import getstatusoutput
Dir = sys.argv[1] # a foler that contains 52 individual files
fail,ls = getstatusoutput('ls %s' % Dir)
if not fail:
for filename in ls.split('\n'):
if filename[-6:] in ['042332','082917','003644','075130']: # files that not used
continue
else:
fp = open(Dir... | end = line.rfind('\"')
print line[:end+1 | ]
fp.close()
else:
print fail
|
vdemir/test_packages | other_packages/iptables/comar/firewall.py | Python | gpl-3.0 | 18,705 | 0.003597 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# i18n
MSG_CONNECTION_NAME = {
"en": "Internet Sharing",
"tr": "Internet Paylaşımı",
"sv": "Internetdelning",
"fr": "Partage de connexion Internet",
"es": "Compartir Internet",
"de": "Internet Freigabe",
"nl": "Internetverbinding delen",
}
MSG_ALL... | guration.",
"es": "Bloquea todas las conexiones entrantes a la computadora. Se puede especificar excepciones desde el dialogo de configuración.", |
"de": "Blockiert alle eingehenden Verbindungen. Im Konfigurations-Dialog können Ausnahmen angegeben werden.",
"nl": "Alle inkomende verbindingen naar deze computer blokkeren. Uitzonderingen kunnen in een configuratiedialoog ingesteld worden.",
}
TITLE_BLOCK_OUTGOING = {
"en": "Block Outgoing Connections",... |
takeontom/pyluxafor | docs/conf.py | Python | mit | 8,401 | 0.005357 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pyluxafor documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | s. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter t | itle for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Wind... |
CurtisHuebner/GPNN | mobyDick.py | Python | mit | 5,608 | 0.021755 | import itertools
import numpy as np
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils, optimizer
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
import variationalLSTM as M
import chainerUtil as V
import time
... | ],iterNum*batchSize)
loss.backward()
t2 = | time.clock()
msg = "iter: " + str(i + iterNum * j + 1) + "/" + str(iterNum * epoch)
msgLoss = "loss: " + str(loss.data/batchSize)
msgNorm = "grad: " + str(my_optimizer.compute_grads_norm())
msgTime = "time: " + str(t2 - t1) + " seconds"
print(msg... |
JackStouffer/Violent-Python | forensic/windows_registry.py | Python | mit | 2,693 | 0.002971 | #!./env/bin/python
""" Windows Registry Network Query
Lists the network name and MAC addresses of the networks that
this computer has connected to. If the location command is given
print the coordinates of the network if they are in the wigile
datebase
Don't be a moron, please don't use this for ... | rLon = re.findall(r'maplon=.*\&', resp)
if rLon:
mapLon = rLon[0].split
print '[-] Lat: ' + mapLat + ', Lon: ' + mapLon
def print_networks(username=None, password=None):
net = "SOFTWARE\Microsoft | \Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged"
key = OpenKey(HKEY_LOCAL_MACHINE, net)
print '\n[*] Networks You have Joined.'
for i in range(100):
try:
guid = EnumKey(key, i)
netKey = OpenKey(key, str(guid))
(n, addr, t) = EnumValue(netKey, 5)
... |
manhhomienbienthuy/scikit-learn | sklearn/linear_model/_stochastic_gradient.py | Python | bsd-3-clause | 85,464 | 0.000398 | # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> (main author)
# Mathieu Blondel (partial_fit support)
#
# License: BSD 3 clause
"""Classification, regression and One-Class SVM using Stochastic Gradient
Descent (SGD).
"""
import numpy as np
import warnings
from abc import ABCMeta, abstractmethod
... | TE_TYPES[learning_rate]
except KeyError as e:
raise ValueE | rror(
"learning rate %s is not supported. " % learning_rate
) from e
def _get_penalty_type(self, penalty):
penalty = str(penalty).lower()
try:
return PENALTY_TYPES[penalty]
except KeyError as e:
raise ValueError("Penalty %s is not supporte... |
FRCDiscord/Dozer | dozer/cogs/namegame.py | Python | gpl-3.0 | 37,558 | 0.002903 | """Namegame, where you try to remember a team number starting with the last number of the previous played team"""
import asyncio
import gzip
import pickle
import traceback
from collections import OrderedDict
from functools import wraps
import discord
import tbapi
from discord.ext.commands import has_permissions
from f... | isplay | _name for p in self.players.keys()]) or "n/a")
embed.add_field(name=v + "Player", value=self.current_player)
embed.add_field(name=v + "Number", value=self.number or "Wildcard")
embed.add_field(name="Time Left", value=self.time)
for name, value in extra_fields:
embed.add_fiel... |
gnarula/eden_deployment | modules/s3/__init__.py | Python | mit | 3,463 | 0.000866 | # -*- coding: utf-8 -*-
""" S3 Framework Extensions for web2py
This package is loaded in models/000_1st_run.py as "s3base",
this namespace can be used to access all S3 classes, e.g.::
s3base.S3Resource()
@see: U{B{I{S3 Developer Guidelines}} <http://eden.sahanafoundation.org/wiki/DeveloperGuidel... | R ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
# Import all names from the S3 modules that shall be accessible
# under the s3base namespace:
# Utilities,... | ets ===========================================
#
# These names are also imported into the global namespace in
# 00_db.py in order to access them without the s3base prefix:
from s3validators import *
from s3utils import *
from s3widgets import *
from s3data import *
# Basic Toolkits ===================================... |
s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/common/extensions/docs/server2/host_file_system_iterator_test.py | Python | gpl-3.0 | 8,159 | 0.001838 | #!/usr/bin/env python
# Copyright 2013 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.
from copy import deepcopy
import unittest
from host_file_system_provider import HostFileSystemProvider
from host_file_system_iterator ... | fo(20),
self._GetStableChannelInf | o(21),
self._GetStableChannelInfo(22),
self._GetStableChannelInfo(23),
self._GetStableChannelInfo(24),
self._GetStableChannelInfo(25),
self._GetStableChannelInfo(26),
self._GetStableChanne... |
dsarkozi/care4care-sdp-grp4 | Care4Care/C4CApplication/views/MemberDetailsRedirectView.py | Python | agpl-3.0 | 1,019 | 0.008832 | from dja | ngo.views.decorators.cache import never_cache
from django.views.generic.base import RedirectView
from C4CApplication.views.utils import create_user
class MemberDetailsRedirectView(RedirectView):
url = ""
connected_member = None
def dispatch(self, request, *args, **kwargs):
... | mber = create_user(self.request.session['email'])
return super(MemberDetailsRedirectView, self).dispatch(request, *args, **kwargs)
@never_cache
def get(self, request, *args, **kwargs):
member_to_ad_as_a_friend_mail = kwargs['pk']
self.url = "/memberdetails/"+str(member... |
theislab/anndata | anndata/tests/test_views.py | Python | bsd-3-clause | 18,418 | 0.000489 | from copy import deepcopy
from operator import mul
import joblib
import numpy as np
from scipy import sparse
import pandas as pd
import pytest
import anndata as ad
from anndata._core.index import _normalize_index
from anndata._core.views import ArrayView, SparseCSRView, SparseCSCView
from anndata.utils import asarray... | nit_hash == joblib.hash(adata)
def test_set_varm_key(adata):
init_hash = joblib.hash(adata)
orig_varm_val = adata.varm["o"].copy()
subset_varm = adata[:, :50]
assert subset_varm.is_view
sub | set_varm.varm["o"] = np.ones((50, 20))
assert not subset_varm.is_view
assert np.all(adata.varm["o"] == orig_varm_val)
assert init_hash == joblib.hash(adata)
def test_set_obs(adata, subset_func):
init_hash = joblib.hash(adata)
subset = adata[subset_func(adata.obs_names), :]
new_obs = pd.Data... |
mephizzle/wagtail | wagtail/wagtailusers/models.py | Python | bsd-3-clause | 1,196 | 0.000836 | from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_u | nicode_compatible
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
submitted_notifications = models.BooleanField(
verbose_name=_('Submitted notifications'),
default=True,
help_text=_("Receive notification when a page is submitted for moderation")
... | help_text=_("Receive notification when your page edit is approved")
)
rejected_notifications = models.BooleanField(
verbose_name=_('Rejected notifications'),
default=True,
help_text=_("Receive notification when your page edit is rejected")
)
@classmethod
def get_for_user(... |
amaniak/meson | depfixer.py | Python | apache-2.0 | 10,688 | 0.004117 | #!/usr/bin/env python3
# Copyright 2013-2014 The Meson development team
# 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... | = 8
else:
self.Addr = p+'I'
self.AddrSize = 4
self.Off = p+'I'
self.OffSize = 4
class DynamicEntry(DataSizes):
def __init__(self, ifile, ptrsize, is_le):
super().__init__(ptrsize, is_le)
self.ptrsize = ptrsize
if ptrsize == 64:
... | ];
self.val = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0];
else:
self.d_tag = struct.unpack(self.Sword, ifile.read(self.SwordSize))[0]
self.val = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
def write(self, ofile):
if self.ptrsize == 64:
... |
QISKit/qiskit-sdk-py | qiskit/visualization/pulse/matplotlib.py | Python | apache-2.0 | 22,579 | 0.001019 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | f is_empty(self):
"""Return if pulse is empty.
Returns:
bool: if the channel has nothing to plot
"""
if any(self.waveform) or self.framechanges or self.conditionals or self.snapshots:
return False
return True
def to_table(self, name):
"""Get... | rgs:
name (str): name of channel
Returns:
dict: dictionary of events in the channel
"""
time_event = []
framechanges = self.framechanges
conditionals = self.conditionals
snapshots = self.snapshots
for key, val in framechanges.items():
... |
openspending/babbage | babbage/model/binding.py | Python | mit | 262 | 0 | class Binding(object):
def __init__ | (self, table, ref):
self.table = table
self.ref = ref |
def __unicode__(self):
return u"<Binding(%r, %r)>" % (self.table.name, self.ref)
def __repr__(self):
return self.__unicode__()
|
MarlboroCollegeComputerScience/flask_sql_planet_express | src/utilities.py | Python | mit | 503 | 0.007952 | """
utilities.py
"""
from flask import url_for
def _get_project_path():
""" Return absolute path to planet_express, without trailing slash"""
# Assumes that the project folder is one up from here, at ./..
import sys, os
my_folder | = os.path.dirname(os.path.realpath(__file__))
parent_folder = os.path.abspath(my_folder + '/..')
retur | n parent_folder
project_path = _get_project_path()
# TODO: generate this randomly.
secret_key = "Shhhh! It's the development secret key..."
|
opesci/devito | tests/test_dimension.py | Python | mit | 47,982 | 0.002001 | from itertools import product
import numpy as np
from sympy import And
import pytest
from conftest import skipif, opts_tiling
from devito import (ConditionalDimension, Grid, Function, TimeFunction, SparseFunction, # noqa
Eq, Operator, Constant, Dimension, SubDimension, switchconfig,
... | grid.dimensions
t = grid.stepping_dim
thickness = 4
u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1)
xleft = SubDimension.left(name='xleft', parent=x, thickness=thickness)
xi = SubDimension.middle(name='xi', parent=x,
... | rent=y,
thickness_left=thickness, thickness_right=thickness)
t_in_centre = Eq(u[t+1, xi, yi], 1)
leftbc = Eq(u[t+1, xleft, yi], u[t+1, xleft+1, yi] + 1)
rightbc = Eq(u[t+1, xright, yi], u[t+1, xright-1, yi] + 1)
op = Operator([t_in_centre, leftbc, right... |
Agicia/lpod-python | image.py | Python | apache-2.0 | 2,333 | 0.003859 | # -*- coding: UTF-8 -*-
#
# Copyright (c) 2009-2010 Ars Aperta, Itaapy, Pierlis, Talend.
#
# Authors: Hervé Cauwelier <herve@itaapy.com>
#
# This file is part of Lpod (see: http://lpod-project.org).
# Lpod is free software; you can redistribute it and/or modify it under
# the terms of either:
#
# a) the GNU General Pub... | return sel | f.get_attribute('xlink:type')
def set_type(self, type):
return self.set_attribute('xlink:type', type)
def get_show(self):
return self.get_attribute('xlink:show')
def set_show(self, show):
return self.set_attribute('xlink:show', show)
def get_actuate(self):
return ... |
Anislav/Stream-Framework | stream_framework/tests/feeds/redis.py | Python | bsd-3-clause | 1,712 | 0.000584 | from stream_framework.tests.feeds.base import TestBaseFeed, implementation
from stream_framework.feeds.redis import RedisFeed
from stream_framework.activity import Activity
from stream_framework.utils import datetime_to_epoch
class CustomActivity(Activity):
@property
def serialization_id(self):
'''
... | elf.time:
raise TypeError('Cant serialize activities without a time')
milliseconds = str(int(datetime_to_epoch(self.time) * 1000))
# shorter than the default version
serialization_id_str = '%s%0.2d%0.2d' % (
milliseconds, self.object_id % 100, self.verb.id)
seria... | disFeed):
activity_class = CustomActivity
class TestRedisFeed(TestBaseFeed):
feed_cls = RedisFeed
class TestCustomRedisFeed(TestBaseFeed):
'''
Test if the option to customize the activity class works without troubles
'''
feed_cls = RedisCustom
activity_class = CustomActivity
@imple... |
y-a-r-g/idea-color-themes | paypal/standard/pdt/models.py | Python | mit | 3,544 | 0.00254 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.http import QueryDict
from django.utils.http import urlencode
from six.moves.urllib.request import urlopen
from six.moves.urllib.parse import unquote_plus
from paypal.standard.models import PayPalSta... | ACK_ENDPOINT, SANDBOX_POSTBACK_ENDPOINT
from paypal.standard.pdt.signals import pdt_successful, pdt_failed
# ### Todo: Move this logic to conf.py:
# if paypal.standard.pdt is in installed apps
# ... then check for this setting in conf.py
class PayPalSettingsError(Exception):
"""Raised when settings are incorrect."... | .PAYPAL_IDENTITY_TOKEN
except:
raise PayPalSettingsError(
"You must set PAYPAL_IDENTITY_TOKEN in settings.py. Get this token by enabling PDT in your PayPal account.")
class PayPalPDT(PayPalStandardBase):
format = u"<PDT: %s %s>"
amt = models.DecimalField(max_digits=64, decimal_places=2, default=0... |
stanfordnlp/coqa-baselines | rc/utils/data_utils.py | Python | mit | 10,586 | 0.002267 | # -*- coding: utf-8 -*-
"""
Module to handle getting data loading classes and helper functions.
"""
import json
import io
import torch
import numpy as np
from collections import Counter, defaultdict
from torch.utils.data import Dataset
from . import constants as Constants
from .timer import Timer
##################... | l_answers' in qas:
answers = answers + qas['additional_answers']
sample = {'id': (paragraph['id'], qas['turn_id']),
'question': question,
'answers': answers,
'evidence': paragraph['annotated_context'],
| 'targets': qas['answer_span']}
if self.config['predict_raw_text']:
sample['raw_evidence'] = paragraph['context']
return sample
################################################################################
# Read & Write Helper Functions #
###################################... |
ares/robottelo | robottelo/manifests.py | Python | gpl-3.0 | 7,792 | 0 | """Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entit... | # for API interface
manifest = manifests.clone()
upload_manife | st_locked(org_id, manifest, interface=INTERFACE_API)
# for CLI interface
manifest = manifests.clone()
upload_manifest_locked(org_id, manifest, interface=INTERFACE_CLI)
# or in one line with default interface
result = upload_manifest_locked(org_id, manifests.clone())
sub... |
TsinghuaX/edx-platform | lms/djangoapps/django_comment_client/base/views.py | Python | agpl-3.0 | 20,227 | 0.001434 | import time
import random
import os
import os.path
import logging
import urlparse
import functools
import lms.lib.comment_client as cc
import django_comment_client.utils as utils
import django_comment_client.settings as cc_settings
from django.core import exceptions
from django.contrib.auth.decorators import login_r... | to a single get_group_for_user_and_commentable function
# that can do different things depending on the commentable_id
if cached_has_permission(request.user, "see_all_cohorts", course_id):
# admins can optionally choose what group to post as
group_id = post.get('group_id', user_g... |
else:
# regular users always post with their own id.
group_id = user_group_id
if group_id:
thread.update_attributes(group_id=group_id)
thread.save()
#patch for backward compatibility to comments service
if not 'pinned' in thread.attributes:
thr... |
jwacalex/MULTEX-EAST-PoS-Tagger | csvtools/mkFullTable.py | Python | lgpl-3.0 | 3,084 | 0.007787 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""This Script generates LaTeX Table with all Information from the Results-File.
"""
from __future__ import print_function
import csv
from config import tagsets, mapping, RESULTS_CSV
__author__ = "Alexander Böhm [jwacalex], Thomas Stieglmaier, Thomas Ziegler"
__credits__ = [... | mn{1}{c|}{\\textbf{Tagging}} & \multicolumn{4}{c}{(second line: standard deviation)} \\\\
"""
print(header)
def footer(lang_code, tagset):
footer = """
\end{tabular}}
\scriptsize
\caption{Results of the different Part of Speech-Taggers on the Language %s for the %s T | agset}
\label{table:lang%s%s}
\end{table}\clearpage""" % (mapping[lang_code], tagsets[tagset.upper()], lang_code.upper(), tagset)
print(footer)
def mkLine(metric, std, row):
print("""\\hline
{} & {} & {:3.1f} & {:2.2f} & {:0.4f} & {:0.4f} & {:0.4f} & {:0.4f} \\\\""".format(
row... |
flag0010/pop_gen_cnn | introgression/old/plot.input.image.py | Python | gpl-3.0 | 2,054 | 0.015579 | import numpy as np
from matplotlib import pyplot as plt
from random import *
def transpose_shape(x):
n = []
for i in x: n.append(i.T)
return np.array(n)
def flip_bits(x):
n = []
for idx, i in enumerate(x):
m = []
for j in i:
ch = choice([0,1])
if ch and j.s... | x):
n = []
s = set(range(x.shape[1]))
for kdx, i in enumerate(x):
out = set([idx for idx, j in enumerate(i) if not j.sum()])
shuffleable = list(s-out)
#print sorted(out)
#print i.shape
shuffle(shuffleable)
shuffleable.extend(sorted(out))
n.append(i[shu... | ']
plt.subplot(1,2,1)
plt.imshow(x[443], aspect=.10, cmap='gray')
plt.subplot(1,2,2)
plt.imshow(shuffle_rows(x)[443], aspect=.10, cmap='gray')
plt.show()
plt.subplot(1,2,1)
plt.imshow(x[143], aspect=.10, cmap='gray')
plt.title('Originial')
plt.subplot(1,2,2)
plt.title("SNP order shuffled")
plt.imshow(flip_bits(x... |
ActiveState/code | recipes/Python/541082_Unicode_repr/recipe-541082.py | Python | mit | 528 | 0.007576 | def urepr(x):
import re, unicoded | ata
def toname(m):
try:
return r"\N{%s}" % unicodedata.name(unichr(int(m.group(1), 16)))
except | ValueError:
return m.group(0)
return re.sub(
r"\\[xu]((?<=x)[0-9a-f]{2}|(?<=u)[0-9a-f]{4})",
toname,
repr(x)
)
def displayhook(x):
if x is not None:
print urepr(x)
def install():
import sys
sys.displayhook = displayhook
def uninstall():
import sys... |
apahim/avocado-misc-tests | perf/perftool.py | Python | gpl-2.0 | 3,154 | 0.000317 | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | rftool(Test):
"""
perftool-testsuite
"""
def setUp(self):
'''
Install the basic packages to support perf
'''
# Check for basic utilities
smm = SoftwareManager()
detec | ted_distro = distro.detect()
kernel_ver = platform.uname()[2]
deps = ['gcc', 'make']
if 'Ubuntu' in detected_distro.name:
deps.extend(['linux-tools-common', 'linux-tools-%s' % kernel_ver])
# FIXME: "redhat" as the distro name for RHEL is deprecated
# on Avocado versio... |
sahabi/keyman | keyman/interface/keychain.py | Python | mit | 798 | 0.002506 | class KeyChain(object):
def __init__(self, key_list=None):
if key_list i | s None:
self.key_list = []
else:
self.key_list = key_list
# self.label = label
def isSelected(self):
for key in self.key_list:
if key.isSelected():
return True
return False
def which(self):
for i, key in enumerate(self.... | , key):
self.key_list.append(key)
def get_selected_level(self):
for key in self.key_list:
if key.isSelected():
return key.level
def get_selected_key(self):
return self.key_list[self.which()]
# def derive_pubkey(self):
|
Mirantis/tempest | tempest/api/orchestration/stacks/test_neutron_resources.py | Python | apache-2.0 | 7,913 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | test_created_server(self):
"""Verifies created sever."""
server_id = self.test_resources.get('Server')['physical_resource_id']
resp, server = self.servers_client.get_server(server_id)
self.assertEqual('200', resp['status'])
self.assertEqual(self.keypair_name, server[' | key_name'])
self.assertEqual('ACTIVE', server['status'])
network = server['addresses']['NewNetwork'][0]
self.assertEqual(4, network['version'])
self.assertIn(netaddr.IPAddress(network['addr']), self.subnet_cidr)
|
ksmaheshkumar/grr | lib/checks/triggers_test.py | Python | apache-2.0 | 3,871 | 0.003875 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for triggers."""
from grr.lib import flags
from grr.lib import test_lib
from grr.lib.checks import checks
from grr.lib.checks import triggers
target_1 = checks.Target({})
target_2 = checks.Target(os=["TermOS"],
cpe=["cpe:/o:cyberdyne:term... | o:cyberdyne:term | os", "t800")
def testConditionIsHashable(self):
c1 = triggers.Condition(*termos)
c2 = triggers.Condition(*t800)
results = set([c1, c2, c1, c1, c1, c2])
self.assertEqual(2, len(results))
self.assertItemsEqual(set([c1, c2]), results)
def testConditionMatch(self):
# More general terms include... |
sanSS/programming-contests | project-euler/problem020.py | Python | gpl-3.0 | 1,260 | 0.001587 | #!/usr/bin/env python3
########################################################################
# Solves problem 20 from projectEuler.net.
# Finds the sum of the digits | of 100!.
# Copyright (C) 2010 Santiago Alessandri
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Thi... | rogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# alon... |
jingriver/stocktracker | pytoolkit/rssReader/twistedRssReader.py | Python | mit | 11,646 | 0.009531 | from twisted.internet import reactor, protocol, defer
from twisted.web import client
from twisted.web.client import HTTPPageGetter, HTTPClientFactory
from twisted.python import failure
from twisted.web import error
import feedparser, time, sys
import md5, os
# You can get this file from http://xoomer.virgilio... | et('version','Unknown')
#
# Uncomment the following if you want to print the feeds
#
chan = parsed_feed.get('channel', None)
if chan:
print chan.get('title', '')
print chan.get('link', '')
#print chan.get('tagline', '')
... | one)
if items:
for item in items:
print '\tTitle: ', item.get('title','')
print '\tDate: ', item.get('date', '')
print '\tLink: ', item.get('link', '')
print '\tDescription: ', item.get('description', '')
print '\... |
yongwen/makahiki | makahiki/apps/widgets/my_commitments/__init__.py | Python | mit | 74 | 0 | """Implements a widget that displays the player' | s curren | t commitments."""
|
tkarna/cofs | test_adjoint/test_swe_adjoint.py | Python | mit | 3,627 | 0.001103 | """
Tests whether we can compute a consistent gradient of some functional
based on the forward model with respect to the bottom friction
via firedrake_adjoint.
Stephan Kramer 25-05-16
"""
import pytest
from thetis import *
from firedrake_adjoint import *
op2.init(log_level=INFO)
velocity_u = 2.0
def basic_setup():
... | ()
solver_obj.assign_initial_conditions(uv=as_vector((velocity_u, 0.0)), elev=Constant(0.0))
solver_obj.iterate()
J0 = assemble(solver_obj.fields.solution_2d[0]*dx)
drag_func = Control(solver_obj.options.quadratic_drag_coefficient)
Jhat = ReducedFunctional(J0, drag_func)
| c = Function(solver_obj.options.quadratic_drag_coefficient)
dc = Function(c)
from numpy.random import rand
c.vector()[:] = rand(*c.dat.shape)
dc.vector()[:] = rand(*dc.dat.shape)
minconv = taylor_test(Jhat, c, dc)
assert minconv > 1.90
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.