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 |
|---|---|---|---|---|---|---|---|---|
tendermint/tmsp | example/python3/app.py | Python | apache-2.0 | 2,169 | 0.001844 | import sys
from abci.wire import hex2bytes, decode_big_endian, encode_big_endian
from abci.server import ABCIServer
from abci.reader import BytesBuffer
class CounterApplication():
def __init__(self):
sys.exit("The python example is out of date. Upgrading the Python examples is currently left as an exer... | h.decode(), 0
def add_listener(self):
return 0
def rm_listener(self):
return | 0
def event(self):
return
if __name__ == '__main__':
l = len(sys.argv)
if l == 1:
port = 26658
elif l == 2:
port = int(sys.argv[1])
else:
print("too many arguments")
quit()
print('ABCI Demo APP (Python)')
app = CounterApplication()
server = AB... |
mohamed-mamdouh95/pedestrainTracker | darkflow/net/flow.py | Python | gpl-3.0 | 4,587 | 0.005668 | import os
import time
import numpy as np
import tensorflow as tf
import pickle
train_stats = (
'Training statistics: \n'
'\tLearning rate : {}\n'
'\tBatch size : {}\n'
| '\tEpoch number : {}\n'
'\tBackup every : {}'
)
def _save_ckpt(self, step, loss_profile):
file = '{}-{}{}'
model = self. | meta['name']
profile = file.format(model, step, '.profile')
profile = os.path.join(self.FLAGS.backup, profile)
with open(profile, 'wb') as profile_ckpt:
pickle.dump(loss_profile, profile_ckpt)
ckpt = file.format(model, step, '')
ckpt = os.path.join(self.FLAGS.backup, ckpt)
self.say('C... |
LuminosoInsight/luminoso-api-client-python | luminoso_api/v5_client.py | Python | mit | 20,872 | 0.000096 | """
Provides the LuminosoClient object, a wrapper for making
properly-authenticated requests to the Luminoso REST API.
"""
import json
import logging
import os
import requests
import time
from getpass import getpass
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from ur... | ept KeyError:
# Some code to help people transition from using URLs | with
# "analytics" to URLs with "daylight" by looking for a token
# with the old URL and using it if it exists
legacy_netloc = netloc.replace('daylight', 'analytics')
if legacy_netloc in token_dict:
logger.warning('Using token for lega... |
Luindil/Glassure | glassure/core/optimization.py | Python | mit | 19,018 | 0.005784 | # -*- coding: utf-8 -*-
from copy import deepcopy
import numpy as np
import lmfit
from . import Pattern
from .calc import calculate_fr, calculate_gr_raw, calculate_sq, calculate_sq_raw, calculate_normalization_factor_raw, \
fit_normalization_factor
from .utility import convert_density_to_atoms_per_cubic_angstrom... | ctionary with elements as keys and abundances as values
:param initial_density: start value for the density optimization in g/cm^3
:param background_min: minimum value for the background scaling
:param background_max: maximum value for the background scaling
:param density_min: min... | value for the density
:param density_max: maximum value for the density
:param iterations: number of iterations of S(Q) (see optimize_sq(...) prior to calculating chi2
:param r_cutoff: cutoff value below which there is no signal expected (below the first peak in g(r))
:param ... |
cberzan/django-anger | testdata/good_migration.py | Python | mit | 60,530 | 0.008161 | # -*- coding: utf-8 -*-
"""
A fairly complicated migration taken from the real world, mangled so as not to
disclose much about the meaning of the models / fields.
"""
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def ... | , {}),
'field026': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'field0 | 27': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '160'}),
'field028': ('django.db.models.fields.CharField', [], {'max_length': '160'})
},
'app_beta.model08': {
'Meta': {'object_name': 'Model08'},
'field029': ('django.db.models.fields.Boo... |
mathLab/RBniCS | rbnics/backends/basic/wrapping/function_copy.py | Python | lgpl-3.0 | 168 | 0 | # Copyright (C) | 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or | -later
def function_copy(function):
pass
|
dmaidaniuk/ozark | test/jsr223/src/main/webapp/WEB-INF/views/index.py | Python | apache-2.0 | 54 | 0.018519 | 'Hello ' + m | odels['mvc'].enc | oders.html(models['name']) |
alessandro-sena/slearning-stackoverflow | fix_probs.py | Python | bsd-2-clause | 965 | 0.004145 | impor | t competition_utilities as cu
import numpy as np
import features
from sklearn.ensemble import RandomFo | restClassifier
from sklearn.naive_bayes import *
import sys
from sklearn.neighbors import KNeighborsClassifier
probs_file = sys.argv[1]
submission_file = sys.argv[2]
train_file = "train-sample.csv"
full_train_file = "train.csv"
test_file = "public_leaderboard.csv"
def main():
f = open(probs_file, 'r')
lines =... |
cargocult/rowan-python | rowan/db.py | Python | mit | 1,715 | 0.001749 | import rowan.controllers.base as base
# ----------------------------------------------------------------------------
class MongoDBMiddleware(base.Wrapper):
"""
Wraps another controller, setting up the mongo database before
delegation. The database is housed in the .db.mongo property of the
request.
... | oller,
server="localhost", port=27017, db="test"):
super(MongoDBMiddleware, self).__init__(controller)
self.server = server
self.port = port
self.db = | db
self.connection = pymongo.Connection(self.server, self.port)
def __call__(self, request):
with request.set(db__mongo=self.connection[self.db]):
return self.controller(request)
# ----------------------------------------------------------------------------
class SQLAlchemyMiddleware... |
supercheetah/diceroller | pyinstaller/PyInstaller/hooks/hook-paste.exceptions.reporter.py | Python | artistic-2.0 | 169 | 0.005917 | # some modules use the old-style import: explicitly include
# the new module when the old | one is referenced
hiddenimports = ["email.mime.te | xt", "email.mime.multipart"]
|
kubernetes-client/python | kubernetes/client/models/v1_deployment.py | Python | apache-2.0 | 7,196 | 0 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | "For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1Deployment):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if... | elf.to_dict() != other.to_dict()
|
jromang/retina-old | imagepreview.py | Python | gpl-3.0 | 9,712 | 0.018946 | #
# This file is part of Retina.
#
# Retina 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.
#
# Retina is distribut... | age.height()-height/2,width/2,height/2)) #lower left
self.painter.drawImage(width/2,height/2,self.qimage.copy(self.qimage.width()-width/2,self.qimage.height()-height/2,width/2,height/2))#lower right
self.painter.setPen(QColor(255,160,47))
self.painter.dra... | ght()/2
self.painter.drawImage(width/4,height/4,self.qimage.copy(xcenter-width/4,ycenter-height/4,width/2,height/2))
self.painter.drawRect(width/4,height/4,width/2,height/2)
self.painter.end()
self.imageLabel.setPixmap(QPixmap.fromIm... |
dpnova/cyclone | cyclone/__init__.py | Python | apache-2.0 | 714 | 0 | # coding: utf-8
#
# Copyright 2010 Alexandre Fiori
# based on the original Tornado by Facebook
#
# 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
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either... | he
# License for the specific language governing permissions and limitations
# under the License.
__author__ = "Alexandre Fiori"
__version__ = version = "git-2013042301"
|
pantsbuild/pants | src/python/pants/backend/python/subsystems/ipython_test.py | Python | apache-2.0 | 3,096 | 0.002907 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
from pants.backend.python import target_types_rules
from pants.backend.python.goals.lockfile import GeneratePythonLockfile
... | ),
["==2.7.*", | "==3.5.*"],
)
assert_ics(
dedent(
"""\
python_sources(name='a', interpreter_constraints=['==2.7.*', '==3.5.*'])
python_sources(name='b', interpreter_constraints=['>=3.5'])
"""
),
["==2.7.*", "==3.5.*", ">=3.5"],
)
assert_ics(
... |
hlabathems/iccf | iccf/__init__.py | Python | bsd-3-clause | 517 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is an Astropy affiliated package.
"""
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from | ._astropy_init import *
# ----------------------------------------------------------------------------
# For egg_info test builds to pass, put package imports here.
if not _ASTROPY_SETUP_:
from .iccf i | mport *
|
slobberchops/rop | opc/text.py | Python | gpl-3.0 | 4,706 | 0 | typeface_bbc = {
"description": "Typeface from the Acorn BBC Computer",
"geometry": {"width": 8, "height": 8},
"bitmaps": [
0x00000000, 0x00000000, 0x18181818, 0x18001800, # (spc) !
0x6c6c6c00, 0x00000000, 0x36367f36, 0x7f363600, # " #
0x0c3f683e, 0x0b7e1800, 0x60660c18, 0x306606... | matrix | .drawPixel(x+bit, ybase + window, bg)
byte = byte >> 1
def drawChar(self, matrix, x, y, char, fg, bg):
char = ord(char) - 32 # printable ASCII starts at index 32
self.drawHalfChar(matrix, x, y, char, 0, fg, bg)
self.drawHalfChar(matrix, x, y, char, 1, fg, bg)
def draw... |
Sriee/epi | data_structures/heaps/frequency_stack.py | Python | gpl-3.0 | 2,003 | 0.001498 | import heapq
from collections import defaultdict, Counter
class FreqStackHeap(object):
"""
Leet code solution. Timing out. Execution result is correct but times out for
exceptionally high number of inputs.
"""
def __init__(self):
self._mem = { | }
self.heap = []
self._idx = 0
def push(self, x):
self._idx -= 1
if x in self._mem:
_temp = []
while self.heap[0][2] != x:
_temp.append(heapq.heappop(self.heap))
| found = heapq.heappop(self.heap)
self._mem[x][0] += 1
self._mem[x][1].append(found[1])
_temp.append((found[0] - 1, self._idx, found[2]))
while _temp:
heapq.heappush(self.heap, _temp.pop())
else:
self._mem[x] = [1, [self._id... |
tobias47n9e/social-core | social_core/backends/stackoverflow.py | Python | bsd-3-clause | 1,459 | 0 | """
Stackoverflow OAuth2 backend, docs at:
https://python-social-auth.readthedocs.io/en/latest/backends/stackoverflow.html
"""
from .oauth import BaseOAuth2
class StackoverflowOAuth2(BaseOAuth2):
"""Stackoverflow OAuth2 authentication backend"""
name = 'stackoverflow'
ID_KEY = 'user_id'
AUTHORIZAT... | ckoverflow account"""
fullname, first_name, last_name = self.get_user_names(
response.get('display_name')
)
return {'username': response.get('link').rsplit('/', 1)[-1],
'full_name': fullname,
'first_name': first_name,
'last_name': last_... | def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json(
'https://api.stackexchange.com/2.1/me',
params={
'site': 'stackoverflow',
'access_token': access_token,
'key': self.sett... |
ianj-als/pypeline | src/pypeline/core/types/tests/state_tests.py | Python | gpl-3.0 | 2,775 | 0.002883 | #
# Copyright Applied Language Solutions 2012
#
# This file is part of Pypeline.
#
# Pypeline 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 option) any l... | s: (value, s.append(value)))
target = (value, state.append(value))
|
result = State.runState(m, state)
self.assertEquals(target, result)
def test_many_mutable_state(self):
# Build this:
# state (\s -> (1, s ++ ["Initial value 1"]))
# >>= (\a -> state (\s -> (a * 2, s ++ ["Mult by 2"])))
# >>= (\a -> state (\s -> (a - 9, s ++ [... |
oblique-labs/pyVM | rpython/jit/metainterp/optimizeopt/test/test_intbound.py | Python | mit | 8,982 | 0.003674 | from rpython.jit.metainterp.optimizeopt.intutils import IntBound, IntUpperBound, \
IntLowerBound, IntUnbounded
from rpython.jit.metainterp.optimizeopt.intbounds import next_pow2_m1
from copy import copy
import sys
from rpython.rlib.rarithmetic import LONG_BIT
def bound(a,b):
if a is None and b is None:
... | and \
(upper is None or n <= upper):
if n == lower or n ==upper:
b | order.append(n)
else:
inside.append(n)
for n in nbr:
c = const(n)
if n in inside:
assert b.contains(n)
assert not b.known_lt(c)
assert not b.known_gt(c)
assert not b.k... |
ianadmu/bolton_bot | bot/common.py | Python | mit | 2,461 | 0.000406 | import random
import os.path
import re
DONT_DELETE = (
"i came back to life on|winnipeg is currently|loud messages|erased"
)
TEAM_MATES = "bolton|leon|ian|leontoast"
USER_TAG = re.compile("<@.*")
CHANNEL_TAG = re.compile("<!.*")
TESTING_CHANNEL = 'bolton-testing'
def is_bolton_mention(msg_text):
return r... | search('markov|bolton', msg_text.lower())
and not re.search(TEAM_MATES, msg_text.lower())
and not contains_tag(msg_text)
):
return True
return False
def should_add_loud(message):
msg_text = message['text']
if (
'user' in mess | age and
not contains_tag(msg_text) and
_is_loud(msg_text)
):
return True
return False
def contains_tag(msg_text):
tokens = msg_text.split()
for token in tokens:
if USER_TAG.match(token) or CHANNEL_TAG.match(token):
return True
return False
def get_targ... |
ammarkhann/FinalSeniorCode | lib/python2.7/site-packages/kombu/async/aws/ext.py | Python | mit | 863 | 0 | # -*- coding: utf-8 -*-
"""Amazon boto interface."""
from __future__ import absolute_import, un | icode_literals
try:
import boto
except ImportError: # pragma: no cover
boto = get_regions = ResultSet = RegionInfo = XmlHandler = None
class _void(object):
pass
AWSAut | hConnection = AWSQueryConnection = _void # noqa
class BotoError(Exception):
pass
exception = _void()
exception.SQSError = BotoError
exception.SQSDecodeError = BotoError
else:
from boto import exception
from boto.connection import AWSAuthConnection, AWSQueryConnection
from boto.hand... |
nibrahim/PlasTeX | plasTeX/Packages/ifpdf.py | Python | mit | 135 | 0.007407 | #!/usr/bin/env python
"""
| This package is intentionally empty | . The \ifpdf command is implemented
in the TeX/Primitives package.
"""
|
bountyfunding/bountyfunding | plugin/trac/bountyfunding/trac/bountyfunding.py | Python | agpl-3.0 | 27,871 | 0.007355 | # -*- coding: utf-8 -*-
from pprint import pprint
from genshi.filters import Transformer
from genshi.builder import tag
from trac.core import *
from trac.util.html import html
from trac.web import IRequestHandler, HTTPInternalError
from trac.web.chrome import INavigationContributor, ITemplateProvider, add_stylesheet... | , ticket_id)
subject = self.format_email_subject(t | icket)
link = self.env.abs_href.ticket(ticket_id)
email = GenericNotifyEmail(self.env, recipient, body, link)
email.notify('', subject)
def format_email_subject(self, ticket):
template = self.config.get('notification','ticket_subject_template')
template = NewTextTemplate(te... |
bxlab/hifive | hifive/fivec_binning.py | Python | mit | 71,263 | 0.003705 | #!/usr/bin/env python
"""
This is a module contains scripts for generating compact, upper-triangle and full matrices of 5C interaction data.
Concepts
--------
Data can either be arranged in compact, complete, or flattened (row-major) upper-triangle arrays. Compact arrays are N x M, where N is the number of forward p... | ay containing start and stop coordinates for a set of user-defined bins. Any fragment not falling in a bin is ignored.
:type binbounds: numpy array
:param start: The smallest coordinate to include in the array, measured from fragment midpoints. If 'binbounds' is given, this value is ignored. If both 'start' and... | ragment for 'region', adjusted to the first multiple of 'binsize' if not zero. Optional.
:type start: int.
:param stop: The largest coordinate to include in the array, measured from fragment midpoints. If 'binbounds' is given, this value is ignored. If both 'stop' and 'stopfrag' are given, 'stop' will override ... |
OCA/l10n-italy | l10n_it_fiscalcode/model/res_company.py | Python | agpl-3.0 | 266 | 0 | # L | icense AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
fiscalcode = fields.Char(
related="partner_id.fiscalcode", store=True, readon | ly=False
)
|
sdpython/pyquickhelper | src/pyquickhelper/pycode/utils_tests_helper.py | Python | mit | 20,810 | 0.001778 | """
@file
@brief This extension contains various functionalities to help unittesting.
"""
import os
import stat
import sys
import re
import warnings
import time
import importlib
from contextlib import redirect_stdout, redirec | t_stderr
from io import StringIO
| def _get_PyLinterRunV():
# Separate function to speed up import.
from pylint.lint import Run as PyLinterRun
from pylint import __version__ as pylint_version
if pylint_version >= '2.0.0':
PyLinterRunV = PyLinterRun
else:
PyLinterRunV = lambda *args, do_exit=False: PyLinterRun( # pyli... |
safchain/contrail-sandesh | library/python/pysandesh/test/test_utils.py | Python | apache-2.0 | 258 | 0.011628 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import socket
def ge | t_free_port():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 0))
po | rt = sock.getsockname()[1]
sock.close()
return port
|
TheAlgorithms/Python | digital_image_processing/histogram_equalization/histogram_stretch.py | Python | mit | 1,894 | 0.000528 | """
Created on Fri Sep 28 15:22:29 2018
@author: Binish125
"""
import copy
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
class contrastStretch:
def __init__(self):
self.img = ""
self.original_image = ""
self.last_list = []
self.rem = 0
self.... | lotHistogram(self):
plt.hist(self.img.ravel(), 256, [0, 256])
def showImage(self):
cv2.imshow("Output-Image", self.img)
cv2.imshow("Input-Image", self.original_image)
cv2.waitKey(5000)
c | v2.destroyAllWindows()
if __name__ == "__main__":
file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg")
stretcher = contrastStretch()
stretcher.stretch(file_path)
stretcher.plotHistogram()
stretcher.showImage()
|
andfoy/margffoy-tuay-server | env/lib/python2.7/site-packages/tornadoredis/backports.py | Python | gpl-2.0 | 6,201 | 0.000968 | from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter
class Counter(dict):
'''Dict subclass for counting hashable objects. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> Coun... | mpty counter:
# c += Counter()
def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
... | for elem in set(self) | set(other):
newcount = self[elem] + other[elem]
if newcount > 0:
result[elem] = newcount
return result
def __sub__(self, other):
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Count... |
codyparker/channels-obstruction | game/views/api_views.py | Python | mit | 2,229 | 0.000897 | from rest_framework.views import APIView
from rest_framework import viewsets
from game.serializers import *
from rest_framework.response import Response
from game.models import *
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from django.http import Http404
class ... | API endpoint for available/open games
"""
def list(self, request):
queryset = Game.get_available_games()
serializer = GameSerializer(queryset, many=True)
return Response(serializer.data)
class CurrentUserView(APIView):
def get(self, request):
serializer = UserSerializer(... | return Response(serializer.data)
class SingleGameViewSet(APIView):
"""
Get all data for a game: Game Details, Squares, & Log
"""
def get(self, request, **kwargs):
game = Game.get_by_id(kwargs['game_id'])
log = game.get_game_log()
squares = game.get_all_game_squares()
... |
Otend/backlog | work.py | Python | bsd-2-clause | 254 | 0.003937 | # -*- coding: utf-8 -*-
#import random
import time
class Work():
def __init__(self, name):
self.n | ame = name
self.addedTime = time.time()
self.wasViewed = False
def changeName(self, newName):
self.name = newNam | e
|
dand-oss/transit-python | tests/seattle_benchmark.py | Python | apache-2.0 | 1,590 | 0 | # Copyright 2014 Cognitect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | s and
# limitations under the License.
from transit.reader import JsonUnmarshaler
import json
import time
from StringIO import StringIO
def run_tests(data):
datas = StringIO(data)
t = time.time()
JsonUnmarshaler().load(datas)
et = time.time()
datas = StringIO(data)
tt = time.time()
json.l... | ett = time.time()
read_delta = (et - t) * 1000.0
print('Done: {} -- raw JSON in: {}'.format(
read_delta, (ett - tt) * 1000.0))
return read_delta
seattle_dir = '../transit-format/examples/0.8/'
means = {}
for jsonfile in ['{}example.json'.format(seattle_dir),
'{}example.verbo... |
jdereus/labman | labcontrol/gui/handlers/process_handlers/test/test_gdna_extraction_process.py | Python | bsd-3-clause | 2,304 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2017-, LabControl development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -------------------------------------------------... | [['21', False, 11, 6, 15, '157022406',
'new gdna plate', None]])}
response = self.post('/process/gdna_extraction', data)
self.assertEqual(response.code, 200)
self.assertCountEqual(json_decode(response.body), ['proc | esses'])
data = {'extraction_date': '01/20/2018', 'volume': 10,
'plates_info': json_encode(
[['21', True, None, None, None, None,
'externally extracted gdna plate',
'Extracted externally']])}
response = self.post('/process/... |
jptomo/rpython-lang-scheme | rpython/jit/codewriter/test/test_call.py | Python | mit | 11,707 | 0.002306 | import py
from rpython.flowspace.model import SpaceOperation, Constant, Variable
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.translator.unsimplify import varoftype
from rpython.rlib import jit
from rpython.jit.codewriter import support, call
from rpython.jit.codewriter.call import CallC... | side
def f():
return external(lltype.nullptr(T.TO))
rtyper = support.annotate(f, [])
jitdriver_sd = FakeJitDriverSD(rtyper.annotator.t | ranslator.graphs[0])
cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd])
res = cc.find_all_graphs(FakePolicy())
[f_graph] = [x for x in res if x.func is f]
[block, _] = list(f_graph.iterblocks())
[op] = block.operations
call_descr = cc.getcalldescr(op)
assert call_descr.extra... |
PeterHo/mysite | scoreboard/migrations/0002_auto_20160204_0121.py | Python | apache-2.0 | 892 | 0.002242 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('scoreboard', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='score',
name='lose... | field=models.CharField(default=b'H', max_length=50, verbose_name=b'\xe8\xb4\x9f\xe8\x80\x85', choices=[(b'\xe4\xbd\x95', b'\xe4\xb | d\x95'), (b'\xe4\xbd\x99', b'\xe4\xbd\x99'), (b'\xe5\xbc\xa0', b'\xe5\xbc\xa0')]),
),
migrations.AlterField(
model_name='score',
name='winner',
field=models.CharField(default=b'H', max_length=50, verbose_name=b'\xe8\x83\x9c\xe8\x80\x85', choices=[(b'\xe4\xbd\x95', b'\... |
jtoppins/beaker | Server/bkr/server/tests/data_setup.py | Python | gpl-2.0 | 38,889 | 0.005863 |
# 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.
import logging
import re
import os
import time
import datetime
import ... | zy_create | (osmajor=osmajor)
osversion = OSVersion.lazy_create(osmajor=osmajor, osminor=osminor)
if arches:
osversion.arches = [Arch.by_name(arch) for arch in arches]
if not name:
name = unique_name(u'%s.%s-%%s' % (osmajor, osminor))
distro = Distro.lazy_create(name=name, osversion=osversion)
i... |
ioiogoo/SmartUrl | manage.py | Python | mit | 806 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smarturl.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the... | ngo. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv) | |
free-free/pyblog | pyblog/locale/english/message.py | Python | mit | 313 | 0 | { |
"register": {
"email": "email address already exists",
"password": "password's length must longer than six characters",
"username": "{ username } already exists"
},
"login": {
"email": "email address not exists",
| "password": "password is not correct"
}
}
|
basvandenberg/puzzlepy | puzzlepy/cell.py | Python | mit | 1,875 | 0.001067 |
class Cell:
def __init__(self, coord):
self._coord = coord
self._neighbors = [None, None, None, None]
|
self._value = None
self._initial_value = False
self._valid_values = None
self._marks = set()
self._active = False
self._valid = True
self._partition_subsets = {}
@property
def coord(self):
return self._coord
@property
def neighbors(se... | return self._neighbors
@property
def initial_value(self):
return self._initial_value;
@initial_value.setter
def initial_value(self, value):
self._initial_value = True
self.value = value
@property
def value(self):
return self._value;
@value.setter
... |
Juniper/ceilometer | ceilometer/api/rbac.py | Python | apache-2.0 | 2,916 | 0 | #
# Copyright 2012 New Dream Network, LLC (DreamHost)
# Copyright 2014 Hewlett-Packard Company
#
# 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-... | ect the request should be limited to.
:param headers: HTTP headers dictionary
:return: A tuple of (user, project), set to None if there's no limit on
one of these.
"""
global _ENFORCER
if not _ENFORCER:
_ENFORCER = policy.Enforcer()
_ENFORCER.load_rules()
policy_dict = dic... | licy_dict['target.user_id'] = (headers.get('X-User-Id'))
policy_dict['target.project_id'] = (headers.get('X-Project-Id'))
if not _ENFORCER.enforce('segregation',
{},
policy_dict):
return headers.get('X-User-Id'), headers.get('X-Project-Id')
... |
idaholab/raven | tests/framework/hybridModel/logicalCode/control.py | Python | apache-2.0 | 959 | 0.005214 | # Copyright 2017 Battelle Energy Alliance, 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/LIC | ENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the Li... | uired by RAVEN to run this as an ControlFunction in LogicalModel.
@ In, self, object, object to store members on
@ Out, model, str, the name of external model that
will be executed by hybrid model
"""
model = None
if self.x > 0.5 and self.y > 1.5:
model = 'poly'
else:
model = 'exp'
retu... |
jameshensman/pythonGPLVM | GPPOD.py | Python | gpl-3.0 | 171 | 0.005848 | # -*- coding: utf-8 -*-
# C | opyright 2009 James Hensman
# Licensed under the | Gnu General Public license, see COPYING
#
# Gaussian Process Proper Orthogonal Decomposition.
|
rays/ipodderx-core | khashmir/unet.py | Python | mit | 2,756 | 0.006894 | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... | ass
self.r.listen_once(1)
if __name__ == "__main__":
n = Network(int(sys.argv[1]), int(sys.argv[2]))
n.simpleSetUp()
print ">>> network ready"
try:
n.r.listen_forever()
f | inally:
n.tearDown()
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.3/Lib/bsddb/db.py | Python | mit | 2,176 | 0.001838 | #----------------------------------------------------------------------
# Copyright (c) 1999-2001, Digital Creations, Fredericksburg, VA, USA
# and Andrew Kuchling. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
| # modification, are permitted provided that the following conditions are
# met:
#
# o Redistributions of source code must retain the above copyright
# notice, this list of conditi | ons, and the disclaimer that follows.
#
# o Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# o Neither the name of Digital Creations n... |
DashkevichBy/Advisors.stratiFi.frontend | tests/test_base_page.py | Python | apache-2.0 | 622 | 0 | from unittest import TestCase
from nose.tools import assert_raises, eq_
import tests
from webium.base_page import BasePage
from webium.driver import get_driver
from webium.errors import WebiumException
class PageWithoutUrl(BasePage):
pass
class TestWithStaticUrl(BasePage):
url = tests.get_url('simple_page... | l')
class TestNoUrlValidation(TestCase):
def test_no_url_validatio | n(self):
page = PageWithoutUrl()
assert_raises(WebiumException, page.open)
def test_static_url(self):
page = TestWithStaticUrl()
page.open()
eq_(get_driver().title, 'Hello Webium')
|
Ledoux/ShareYourSystem | Pythonlogy/build/lib/ShareYourSystem/Standards/Interfacers/Folderer/__init__.py | Python | mit | 6,649 | 0.055347 | # -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
The Folderer is a quick object helping for getting the FolderedDirKeyStrsList
at a specified directory or in the current one by default
"""
#<DefineAugmentation>
import ShareYourSystem as SYS... |
#Check for a module
if self['ModuleVariable']==None or self['ModuleStr']!=self['ModuleVariable'].__name__:
#Check
if self['ModuleStr']!="":
#Import the module if not already
if self['ModuleStr'] not in sys.modules:
importlib.import_module(self['ModuleStr'])
#set with sys
self['Module... |
#set
if self['ModuleVariable']!=None:
#set
self['InstallFolderPathStr']='/'.join(
self['ModuleVariable'].__file__.split('/')[:-1]
)+'/'
#set
self['LocalFolderPathStr']=SYS.PythonlogyLocalFolderPathStr+self['ModuleVariable'].__name__.replace(
'.','/')+'/'
#</DefineLocals>
#<DefineCla... |
ninjaotoko/dynaform | dynaform/forms/base.py | Python | bsd-3-clause | 24,221 | 0.007226 | # *-* coding=utf-8 *-*
import os, uuid, StringIO
import re
import json
import mimetypes
from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import force_escape, escape, safe
f... | ('dynaform_choices_related_queryset', kwargs = {
| 'field_pk': field.choices_related_field.pk,
'related_field_pk':field.pk,
'pk': 0
})
attrs.update({
'data-related-field': '',
... |
stripe/stripe-python | tests/api_resources/reporting/test_report_type.py | Python | mit | 760 | 0 | from __future__ import absolute_import, division, print_function
import stripe
TEST_RESOURCE_ID = "activity.summary.1"
class TestReportType(object):
def test_is_listable(self, request_mock):
resources = stripe.reporting.ReportType.list()
request_mock.assert_requested("get", "/v1/reporting/repor... | est_mock):
resource = stripe.reporting.ReportType.retrieve(TEST_RESOURCE_ID)
request_mock.assert_requested(
"get", "/v1/reporting/report_types/%s" % TEST_RESOURCE_ID
)
assert isinstance(resource, stripe.report | ing.ReportType)
|
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/eventhubs/custom.py | Python | mit | 20,353 | 0.005257 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | mespace_name)
def cli_namespace_update(cm | d, client, instance, tags=None, sku=None, capacity=None, is_auto_inflate_enabled=None,
maximum_throughput_units=None, is_kafka_enabled=None, default_action=None,
identity=None, key_source=None, key_name=None, key_vault_uri=None, key_version=None, trusted_service_access_... |
crocodilered/insideout | webapp/libs/models/schedule.py | Python | mit | 712 | 0.001404 | from sql | alchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy.types import String, Integer, Boolean, Text, Date
from webapp.libs.mediahelper import MediaHelper
Base = declarative_base()
|
class Schedule(Base):
__tablename__ = "schedule"
schedule_id = Column(Integer, primary_key=True)
date = Column("dt", Date, nullable=False)
content = Column(Text, nullable=False)
enabled = Column(Boolean)
def __init__(self, schedule_id=None, date=None, content=None, enabled=None):
... |
kinshuk4/MoocX | misc/deep_learning_notes/Proj_Centroid_Loss_LeNet/LeNet_plus/checkpoints/90_pc_trial_001/MNIST_train.py | Python | mit | 4,056 | 0.002959 | import os, sys, numpy as np, tensorflow as tf
from pathlib import Path
from termcolor import colored as c, cprint
sys.path.append(str(Path(__file__).resolve().parents[1]))
import LeNet_plus
__package__ = 'LeNet_plus'
from . import network
from tensorflow.examples.tutorials | .mnist | import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
BATCH_SIZE = 200
FILENAME = os.path.basename(__file__)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SUMMARIES_DIR = SCRIPT_DIR
SAVE_PATH = SCRIPT_DIR + "/network.ckpt"
### configure devices for this eval script.
USE_DEVICE = ... |
vakhet/rathena-utils | dev/ragna.py | Python | mit | 1,183 | 0.002536 | import re
def read_lua():
PATTERN = r'\s*\[(?P<id>\d+)\] = {\s*unidentifiedDisplayName = ' \
r'"(?P<unidentifiedDisplayName>[^"]+)",\s*unidentifie' \
r'dResourceName = "(?P<unidentifiedResourceName>[^"]+' | \
r')",\s*unidentifiedDescriptionName = {\s*"(?P<uniden' \
r'tifiedDescriptionName>[^=]+)"\s*},\s*identifiedDisp' \
r'layName = "(?P<identifiedDisplayName>[\S | ]+)",\s*id' \
r'entifiedResourceName = "(?P<identifiedResourceName>' \
r'[\S ]+)",\s*identifiedDescriptionName = {\s*"(?P<id' \
r'entifiedDescriptionName>[^=]+)"\s*},\s*slotCount = ' \
r'(?P<slotCount>\d{1}),\s*ClassNum = (?P<ClassNum>\d{' \
r'... |
emsrc/daeso-framework | lib/daeso/stats/corpus.py | Python | gpl-3.0 | 6,068 | 0.00824 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 ... |
read_subtable(pgc_tables[annot], pgc_tab_fn)
read_subtable(gb_tables[annot], gb_tab_fn)
pgc_tables[annot].summarize()
pgc_tab_fn = ".".join(("stats", seg, annot, "pgc"))
write_table(pgc | _tables[annot], pgc_tab_fn, verbose=verbose)
read_subtable(pgc_tables["all"], pgc_tab_fn, verbose=verbose)
gb_tables[annot].summarize()
gb_tab_fn = ".".join(("stats", seg, annot, "gb"))
write_table(gb_tables[annot], gb_tab_fn, verbose=verbose)
read_subtable(gb_tables["al... |
almarklein/bokeh | tests/glyphs/Patch.py | Python | bsd-3-clause | 987 | 0.001013 | import numpy as np
from bokeh.document import Document
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid
from bokeh.models.glyphs | import Patch
from bokeh.plotting import sho | w
N = 30
x1 = np.linspace(-2, 2, N)
x2 = x1[::-1]
y1 = x1**2
y2 = x2**2 + (x2+2.2)
x = np.hstack((x1, x2))
y = np.hstack((y1, y2))
source = ColumnDataSource(dict(x=x, y=y))
xdr = DataRange1d(sources=[source.columns("x")])
ydr = DataRange1d(sources=[source.columns("y")])
plot = Plot(
title=None, x_range=xdr, y_r... |
Patola/Cura | plugins/UM3NetworkPrinting/src/Cloud/Models/CloudClusterPrinterStatus.py | Python | lgpl-3.0 | 4,467 | 0.00582 | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Union, Dict, Optional, Any
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from .CloudClust... | _name: Human readable name of the printer. Can be used for identification purposes.
# \param ip_address: The IP address of the printer in the local network.
# \param machine_variant: The type of printer. Can be 'Ultimaker 3' or 'Ultimaker 3ext'.
# \param status: The status of the p | rinter.
# \param unique_name: The unique name of the printer in the network.
# \param uuid: The unique ID of the printer, also known as GUID.
# \param configuration: The active print core configurations of this printer.
# \param reserved_by: A printer can be claimed by a specific print job.
# \... |
openstack/sahara-dashboard | sahara_dashboard/test/integration_tests/pages/project/data_processing/jobs/jobtemplatespage.py | Python | apache-2.0 | 5,101 | 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... | _css_selector(
'input[type=text]')[-2:]
inputs[0].s | end_keys(key)
inputs[1].send_keys(value)
locator = (by.By.ID, 'params')
if form._is_element_visible(*locator):
params_block = form.src_elem.find_element(*locator)
add_btn = params_block.find_element_by_link_text('Add')
for key, value in parameters.ite... |
microy/PyMeshToolkit | MeshToolkit/File/Obj.py | Python | mit | 1,285 | 0.070039 | # -*- coding:utf-8 -*-
#
# Import OBJ files
#
# External dependencies
import os
import numpy as np
import MeshToolkit as mtk
# Import a mesh from a OBJ / SMF file
def ReadObj( filename ) :
# Initialisation
vertices = []
faces = []
normals = []
colors = []
texcoords = []
material = ""
# Read each line in the ... | v in values[1:4] ] ) ) )
# Normal
elif values[0] == 'vn' :
normals.append( list( map( float, values[1:4] ) ) )
# Color
elif values[0] == 'c' :
colors.append( list( map( float, values[1:4] ) ) )
# Texture
elif values[0] == 'vt' :
texcoords.appen | d( list( map( float, values[1:3] ) ) )
# Texture filename
elif values[0] == 'mtllib' :
material = values[1]
# Remap face indices
faces = np.array( faces ) - 1
# Return the final mesh
return mtk.Mesh( os.path.splitext(os.path.basename(filename))[0], vertices, faces, colors, material, texcoords, [], normals )
|
qsnake/numpy | numpy/testing/tests/test_utils.py | Python | bsd-3-clause | 15,034 | 0.00306 | import warnings
import sys
import numpy as np
from numpy.testing import *
import unittest
class _GenericTest(object):
def _test_equal(self, a, b):
self._assert_func(a, b)
def _test_not_equal(self, a, b):
try:
self._assert_func(a, b)
passed = True
except Asserti... | an, anan)
self.assertRaises(AssertionError,
lambda : self._assert_func(anan, aone))
self.assertRaises(AssertionError,
lambda : self._assert_func(anan, ainf))
self.assertRaises(AssertionError,
lambda : self._assert_func(ainf, anan))
class TestAlmos... | t_equal
def test_nan_item(self):
self._assert_func(np.nan, np.nan)
self.assertRaises(AssertionError,
lambda : self._assert_func(np.nan, 1))
self.assertRaises(AssertionError,
lambda : self._assert_func(np.nan, np.inf))
self.assertRaises(AssertionError,... |
teeple/pns_server | work/install/Python-2.7.4/Tools/pybench/Arithmetic.py | Python | gpl-2.0 | 13,590 | 0.000294 | from pybench import Test
class SimpleIntegerArithmetic(Test):
version = 2.0
operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
rounds = 120000
def test(self):
for i in xrange(self.rounds):
a = 2
b = 3
c = 3
c = a + b
c = b + c
c... | c = a - b
c = b - c
c = c - a
c = b - c
c = a / b
c = b / a
c = c / b
c = a * b
c = b * a
c = c * b
|
c = a / b
c = b / a
c = c / b
def calibrate(self):
for i in xrange(self.rounds):
pass
class SimpleLongArithmetic(Test):
version = 2.0
operations = 5 * (3 + 5 + 5 + 3 + 3 + 3) |
pombredanne/geopy | geopy/point.py | Python | mit | 10,317 | 0.000194 | import re
from itertools import islice
from geopy import util, units, format
class Point(object):
"""
A geodetic point with latitude, longitude, and altitude.
Latitude and longitude are floating point values in degrees.
Altitude is a floating point value in kilometers. The reference level
is never... | ude=None):
latitude = "%s" % self.latitude
longitude = "%s" % self.longitude
coordinates = [latitude, longitude]
if altitude is None:
altitude = bool(self.altitude)
if altitude:
if not isinstance(altitude, base | string):
altitude = 'km'
coordinates.append(self.format_altitude(altitude))
return ", ".join(coordinates)
def format_altitude(self, unit='km'):
return format.distance(self.altitude, unit)
def __str__(self):
return self.format()
def __unicode__(self):
... |
e-lin/LeetCode | 401-binary-watch/401-binary-watch.py | Python | apache-2.0 | 563 | 0.001776 | # solution reference:
# http://bookshadow.com/weblog/ | 2016/09/18/leetcode-binary-watch/
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
ans = []
for h in xrange(12):
for m in xrange(60):
if bin(h).count('1') + bin(m).count('1') == num:
... | ryWatch(n)
if __name__ == '__main__':
main() |
ketancmaheshwari/hello-goog | src/python/trie.py | Python | apache-2.0 | 179 | 0 | #!/bin/env python
# m | ainly for sys.argv[], sys.argv[0] is the name of the program
import sys
# mainly for arrays
import numpy as np
if __name__ == '_ | _main__':
print 'hello'
|
openstack/openstackdocstheme | openstackdocstheme/ext.py | Python | apache-2.0 | 18,703 | 0 | # Copyright 2015 Rackspace US, 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... | tackdocs_use_storyboard = app.config.use_storyboard
if app.config.bug_project is not None:
logger.info(
"[openstackdocsth | eme] "
"the 'bug_project' config option has been deprecated and "
"replaced by the 'openstackdocs_bug_project' option; support "
"for the former will be dropped in a future release")
app.config.openstackdocs_bug_project = app.config.bug_project
if app... |
uniphier/buildroot-unph | utils/checkpackagelib/lib_mk.py | Python | gpl-2.0 | 11,938 | 0.005193 | # See utils/checkpackagelib/readme.txt before editing this file.
# There are already dependency checks during the build, so below check
# functions don't need to check for things already checked by exploring the
# menu options using "make menuconfig" and by running "make" with appropriate
# packages enabled.
import re... | tional += 1
return
if self.END_CONDITIONAL.search(text):
self.conditional -= 1
| return
m = self.VARIABLE.search(text)
if m is None:
return
variable, assignment = m.group(1, 2)
if self.conditional == 0:
if variable in self.conditionally_set:
self.unconditionally_set.append(variable)
if assignment in self.OV... |
WojciechMula/toys | autovectorization-tests/scripts/compile_all.py | Python | bsd-2-clause | 1,263 | 0.003959 | #!/usr/bin/env python3
import sys
from pathlib import Path
from procedures import PROCEDURES
std_options = {
'avx2': '-O3 -mavx2 -S %(cpp_file)s -o %(asm_file)s',
'avx512': '-O3 -mavx512f -mavx512dq -mavx512bw -mavx512vbmi -mavx512vbmi2 -mavx512vl '
'-S %(cpp_file)s -o %(asm_file)s',
}
compile... | s how to invoke script (like 'gcc' or 'clang')")
print("target is avx2 or avx512")
return 1
arg_compiler = sys.argv[1]
arg_target = sys.argv[2]
options = None
for compiler in compiler_options:
if compiler in arg_compiler:
options = compiler_options[compiler][arg_tar... | print(f"{arg_compiler} not recognized")
return 1
for cpp_file in PROCEDURES:
asm_file = Path(cpp_file).stem + '_' + arg_target + '.s'
opts = options % {'cpp_file': cpp_file,
'asm_file': asm_file}
print(f"{arg_compiler} {opts}")
return 0
... |
timorieber/wagtail | wagtail/admin/tests/api/test_images.py | Python | bsd-3-clause | 8,040 | 0.002861 | import json
from django.urls import reverse
from wagtail.api.v2.tests.test_images import TestImageDetail, TestImageListing
from wagtail.images import get_image_model
from wagtail.images.tests.utils import get_test_image_file
from .utils import AdminAPITestCase
class TestAdminImageListing(AdminAPITestCase, TestImag... |
response = self.get_response()
content = json.loads(response.content.decode('UTF-8'))
for image in content['items']:
self.assertEqual(set(image.keys()), {'id | ', 'meta', 'title', 'width', 'height', 'thumbnail'})
self.assertEqual(set(image['meta'].keys()), {'type', 'detail_url', 'download_url', 'tags'})
def test_fields(self):
response = self.get_response(fields='width,height')
content = json.loads(response.content.decode('UTF-8'))
for... |
chevah/brink | brink/pavement_commons.py | Python | bsd-3-clause | 36,882 | 0.000054 | # Copyright (c) 2011 Ad | i Roiban.
# See LICENSE for details.
"""
Shared pavement methods used in Chevah project.
This file is copied into the root of each repo as pavement_lib.py
Brace yoursef for watching how wheels are reinvented.
Do not modify this file in | side the branch.
A `product` is a repository delived to customers or a library.
A `project` is a collection of products.
This scripts assume that you have dedicated folder for the project, and
inside the project folder, there is one folder for each products.
"""
from __future__ import (
absolute_import,
prin... |
jonparrott/google-cloud-python | logging/tests/unit/gapic/v2/test_config_service_v2_client_v2.py | Python | apache-2.0 | 18,769 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | .patch('google.api_core | .grpc_helpers.create_channel')
with patch as create_channel:
create_channel.return_value = channel
client = logging_v2.ConfigServiceV2Client()
# Setup Request
sink_name = client.sink_path('[PROJECT]', '[SINK]')
response = client.get_sink(sink_name)
asser... |
1905410/Misago | misago/users/tests/test_lists_views.py | Python | gpl-2.0 | 2,244 | 0.000446 | from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.utils.six.mov | es import range
from misago.acl.testutils import override_acl
from ..models import Rank
from ..testutils import AuthenticatedUserTestCase
class UsersListTestCase(AuthenticatedUserTestCase):
def setUp(self):
super(UsersListTestCase, self).setUp()
override_acl(self.user, {
'can_browse_... | permission"""
override_acl(self.user, {
'can_browse_users_list': 0,
})
response = self.client.get(reverse('misago:users'))
self.assertEqual(response.status_code, 403)
def test_lander_redirect(self):
"""lander returns redirect to valid page if user has permission... |
grandcat/robotics_g7 | object_recognition/src/object_recognition/msg/__init__.py | Python | gpl-2.0 | 35 | 0 | from ._Recognized_o | bje | cts import *
|
dials/dials | algorithms/scaling/scaling_options.py | Python | bsd-3-clause | 8,202 | 0.001585 | """
Phil scope of options for scaling.
"""
from __future__ import annotations
import iotbx.phil
phil_scope = iotbx.phil.parse(
"""
anomalous = False
.type = bool
.help = "Separate anomalous pairs in scaling and error model optimisation."
.expert_level=0
overwrite_existing_models = False
.type... | reflections to use"
"to determine the scaling model and error model."
.expert_level = 2
intensity_choice = profile sum *combine
.alias = intensity
.type = choice
.help = "Option to choose from profile fitted or summation intensities, or
an optimised combination o... | l = 1
combine.Imid = None
.type = floats
.help = "A list of values to try for the midpoint, for profile/sum combination
calculation: the value with the lowest Rmeas will be chosen.
0 and 1 are special values that can be supplied to include profile
and sum res... |
lavish205/olympia | src/olympia/addons/urls.py | Python | bsd-3-clause | 3,177 | 0.001574 | from django.conf.urls import include, url
from django.shortcuts import redirect
from olympia.stats.urls import stats_patterns
from . import views
ADDON_ID = r"""(?P<addon_id>[^/<>"']+)"""
# These will all start with /addon/<addon_id>/
detail_patterns = [
url('^$', views.addon_detail, name='addons.detail'),
... | .
url('^addon/%s/' % ADDON_ID, include(detail_patterns)),
# Remora EULA and Privacy policy URLS
url('^addons/policy/0/(?P<addon_id>\d+)/(?P<file_id>\d+)',
lambda r, addon_id, file_id: redirect(
'addons.eula', addon_id, file_id, permanent=True)),
url('^addons/policy/0/(?P<addon_id>\d... | .license_redirect),
url('^find-replacement/$', views.find_replacement_addon,
name='addons.find_replacement'),
]
|
Zabanya/warzone2100 | po/parseJson.py | Python | gpl-2.0 | 571 | 0.033275 | import json, sys, re
def printString(s, begin, end):
if not re.match(r'^(\*.*\*|CAM[0-9] .*|Z ?NULL.*)$', s):
sys.stdout.write('{}_({}){}'.format(begin, json.dumps(s, ensure_ascii=False), end))
def parse(obj):
if isinstance(obj, dict):
for k, v in obj.items():
parse(v)
if k == 'name' and isinstance(v, str... | k == 'text' and isinstance(v, list):
for s in v:
if isinstance(s, str):
printString(s, '', '\n')
elif isinstance(obj, list):
| for v in obj:
parse(v)
parse(json.load(open(sys.argv[1], 'r')))
|
apache/incubator-airflow | tests/providers/amazon/aws/sensors/test_dms_task.py | Python | apache-2.0 | 2,939 | 0.00034 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | s.hooks.dms import DmsHook
from airflow.providers.amazon.aws.sensors.dms_task import DmsTaskCompletedSensor
class TestDmsTaskCompletedSensor(unittest.TestCase):
def setUp(self):
self.sensor = DmsTaskCompletedSensor(
task_id='test_dms_sensor',
aws_conn_id='aws_default',
... | status):
assert self.sensor.poke(None)
@mock.patch.object(DmsHook, 'get_task_status', side_effect=("running",))
def test_poke_running(self, mock_get_task_status):
assert not self.sensor.poke(None)
@mock.patch.object(DmsHook, 'get_task_status', side_effect=("starting",))
def test_poke_s... |
andycasey/snob | sandbox_mixture_slf.py | Python | mit | 2,941 | 0.00374 | import numpy as np
from snob import mixture_slf as slf
n_samples, n_features, n_clusters, rank = 1000, 50, 6, 1
sigma = 0.5
true_homo_specific_variances = sigma**2 * np.ones((1, n_features))
rng = np.random.RandomSta | te(321)
U, _, _ = np.linalg.svd(rng.randn(n_features, n_features))
true_factor_loads = U[:, :rank].T
true_factor_scores = rng.randn(n_samples, rank)
X = np.dot(true_factor_scores, true_factor_loads)
# Assign objects to different clusters.
indices = rng.randint(0, n_clusters, size=n_samples)
true_weights = np.zeros(... | lusters)
true_means = rng.randn(n_clusters, n_features)
for index in range(n_clusters):
X[indices==index] += true_means[index]
true_weights[index] = (indices==index).sum()
true_weights = true_weights/n_samples
# Adding homoscedastic noise
bar = rng.randn(n_samples, n_features)
X_homo = X + sigma * bar
# Addi... |
LCAS/teaching | cmp3103m-code-fragments/scripts/odom_reader.py | Python | mit | 833 | 0.0012 | #!/usr/bin/env py | thon
import rospy
from pprint import pformat
from tf_conversions import transformations
from math import pi
from nav_msgs.msg import Odometry
class odom_reader:
def __init__(self):
self.image_sub = rospy.Subscriber("/odom",
Odometry, self.callback)
"""
| convert an orientation given in quaternions to an actual
angle in degrees for a 2D robot
"""
def odom_orientation(self, q):
y, p, r = transformations.euler_from_quaternion([q.w, q.x, q.y, q.z])
return y * 180 / pi
def callback(self, data):
print "odom pose: \n" + pformat(data... |
fstagni/DIRAC | AccountingSystem/Client/Types/Pilot.py | Python | gpl-3.0 | 801 | 0.002497 | __RCSID__ = "$Id$"
from DIRAC.AccountingSystem.Client.Types.BaseAccountingType import BaseAccountingType
class Pilot(BaseAccountingType):
def __init__(self):
BaseAccountingType.__init__(self)
self.definitionKeyFields = [('User', 'VARCHAR(64)'),
('UserGroup', 'VARCHAR(32)'),... | ('Site', 'VARCHAR(64)'),
('GridC | E', "VARCHAR(128)"),
('GridMiddleware', 'VARCHAR(32)'),
('GridResourceBroker', 'VARCHAR(128)'),
('GridStatus', 'VARCHAR(32)'),
]
self.definitionAccountingFields = [('Jobs', "INT UNSIGNED")... |
herove/dotfiles | sublime/Packages/HTML/html_completions.py | Python | mit | 10,848 | 0.001383 | import sublime, sublime_plugin
import re
def match(rex, str):
m = rex.match(str)
if m:
return m.group(0)
else:
return None
# This responds to on_query_completions, but conceptually it's expanding
# expressions, rather than completing words.
#
# It expands these simple expressions:
# tag.cl... | - 1
ch = view.substr(sublime.Region(pt, pt + 1))
if ch != '<':
return []
return ([
("a\tTag", "a href=\"$1\">$2</a>"),
("abbr\tTag", "abbr>$1</abbr>"),
("acronym\tTag", "acronym>$1</acronym>"),
("address\tTag", "address>$1</address>")... | ,
("b\tTag", "b>$1</b>"),
("base\tTag", "base>$1</base>"),
("big\tTag", "big>$1</big>"),
("blockquote\tTag", "blockquote>$1</blockquote>"),
("body\tTag", "body>$1</body>"),
("button\tTag", "button>$1</button>"),
("center\tTag", "center>... |
jayfk/cookiecutter-django-docker | {{cookiecutter.repo_name}}/config/settings/production.py | Python | bsd-3-clause | 4,238 | 0.003303 | # -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use mailgun to send emails
- Use redis
'''
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ---------------------------------------------------------... | conds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
| SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool("DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", def... |
bigchaindb/bigchaindb-examples | server/lib/models/assets.py | Python | apache-2.0 | 10,725 | 0.00317 | from time import sleep
from datetime import datetime
import rethinkdb as r
import cryptoconditions as cc
from decorator import contextmanager
import bigchaindb
import bigchaindb.util
import bigchaindb.crypto
@contextmanager
def take_at_least_seconds(amount_in_seconds):
t_issu | ed = datetime.now()
yield
t_expired = datetime.now() - t_issued
while t_expired.total_seconds() < amount_in_seconds:
sleep(1)
t_expired = datetime.now() - t_issued
def query_reql_response(response, query):
result = list(response)
if result and len(result):
content = re | sult[0]["transaction"]["data"]["payload"]["content"]
if query and content is not None:
if query in content:
return result
else:
return result
return None
def get_owned_assets(bigchain, vk, query=None, table='bigchain'):
assets = []
asset_ids = bigcha... |
plotly/python-api | packages/python/plotly/plotly/validators/volume/colorbar/tickformatstop/_value.py | Python | mit | 497 | 0 | import _plotly_uti | ls.basevalidators
class ValueValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="value",
parent_name="volume.colorbar.tickformatstop",
**kwargs
):
| super(ValueValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
parlar/calls2xls | external/CrossMap/usr/lib64/python2.7/site-packages/bx/align/tools/chop.py | Python | mit | 1,066 | 0.021576 | """
Support for chopping a list of alignment blocks to only the portion that
intersects a particular interval.
"""
def chop_list( blocks, src, start, end ):
"""
For each alignment block in the sequence `blocks`, chop out the portion
of the block that overlaps the interval [`start`,`end`) in the
compone... | _size - start, ref.end )
else:
slice_start = max( start, ref.start )
slice_end = min( end, ref.end )
sliced = block.slice_by_component( ref, slice_start, slice_end )
good = True
for c in sliced.components:
if c.size < 1:
good = False... | d )
return new_blocks |
tobiasraabe/otree_virtual_machine_manager | ovmm/commands/list_user.py | Python | mit | 484 | 0 | """This module contains the ``list_user`` command."""
import click
from ovmm.handlers.postgres import PostgreSQLDatabaseHandler
@click.command()
def list_user():
"""List users managed by ovmm."""
click.echo('\n{:-^60}'.format(' Process: List Users '))
postgres = PostgreSQLDatabaseHandler()
user_lis... | click.echo('List of user names:')
for i in user_list:
click.echo(i)
click.echo('{:-^60}\n'.format(' Process: End '))
| |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py | Python | apache-2.0 | 4,346 | 0.002761 | # Buffers allocated on the heap
from bgenOutput import *
from bgenType import OutputOnlyMixIn
from bgenBuffer import FixedInputOutputBufferType
class HeapInputOutputBufferType(FixedInputOutputBufferType):
"""Input-output buffer allocated on the heap -- passed as (inbuffer, outbuffer, size).
Inst... | utputBufferType):
"""same as base class, but passed as (i | nbuffer, outbuffer, &size)"""
def passOutput(self, name):
return "%s__in__, %s__out__, &%s__len__" % (name, name, name)
class HeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
"""same as base class, but passed as (inoutbuffer, size)"""
def passOutput(self, name):
... |
pimiento/captures | captures/wsgi.py | Python | gpl-2.0 | 1,132 | 0.000883 | """
WSGI config for ahaha project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | plication with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ahaha.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django... | ication = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Chasego/codirit | leetcode/133-Clone-Graph/bfs_001_iterative_jiuzhang.py | Python | mit | 1,381 | 0.005069 | """
Good Points:
1. getNodes
1.1 while q (instead of while len(q) > 0)
1.2 collections.deque (instead of q = [])
Bad Points:
1. another loop to fill mapping instead of doing it in the bfs
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = []):
self.val... | mapping = {}
for node in nodes:
mapping[node] = Node(node.val)
# copy neighbors(edges)
for node in nodes:
new_node = mapping[node]
for neighbor in node.neighbors:
new_neighb | or = mapping[neighbor]
new_node.neighbors.append(new_neighbor)
return mapping[root]
def getNodes(self, node):
q = collections.deque([node])
result = set([node])
while q:
head = q.popleft()
for neighbor in head.neighbors:
if ne... |
Vauxoo/account-payment | account_vat_on_payment/account_journal.py | Python | agpl-3.0 | 1,470 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011-2012 Domsense s.r.l. (<http://www.domsense.com>).
# Copyright (C) 2014 Agile Business Group sagl (<http://www.agilebg.com>)
#
# This progra... | an redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WA... | GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm... |
makkus/pigshare | setup.py | Python | gpl-3.0 | 1,523 | 0.003283 | 3#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import io
import re
init_py = io.open('pigshare/__init__.py').read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py))
metadata['doc'] | = re.findall('"""(.+)"""', init_py)[0]
requirements = [
"argparse",
"setuptools",
"restkit",
"bo | oby",
"simplejson",
"parinx",
"pyclist",
"argcomplete"
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='pigshare',
version=metadata['version'],
description=metadata['doc'],
author=metadata['author'],
author_email=metadata['email'],
url=metad... |
mlperf/training_results_v0.6 | Google/benchmarks/transformer/implementations/tpu-v3-512-transformer/transformer/data_generators/all_problems.py | Python | apache-2.0 | 1,542 | 0.01297 | """Imports for problem modules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import re
MODULES = [
"problem_hparams", # pylint: disable=line-too-long
"translate_ende", # pylint: disable=line-too-long
"translate_enfr", #... | ?" % | m for m in module.split(".")])
return re.match("^No module named (')?%s(')?$" % module_pattern, err_str)
def _handle_errors(errors):
"""Log out and possibly reraise errors during import."""
if not errors:
return
log_all = True # pylint: disable=unused-variable
err_msg = "Skipped importing {num_missing}... |
maldevel/PenTestKit | web/compare-post-data.py | Python | gpl-3.0 | 2,917 | 0.01337 | #!/usr/bin/python
# encoding: UTF-8
"""
This file is part of PenTestKit
Copyright (C) 2017-2018 @maldevel
https://github.com/maldevel/PenTestKit
PenTestKit - Useful tools for Penetration Testing.
This program is free software: you can redistribute it and/or modify
it under the term... | ss=RawTextHelpFormatter)
parser.add_argument("-i1", "--input1",
action="store",
metavar='POST_data',
dest='input1',
type=str,
default=None,
required=True,
... | help='POST data to compare')
parser.add_argument("-i2", "--input2",
action="store",
metavar='POST_data',
dest='input2',
type=str,
default=None,
required=True,
... |
brentbaum/cs3240-labdemo | hello.py | Python | mit | 55 | 0 | from helper import greet | ing
gree | ting("hello world...")
|
sibson/dynoup | settings.py | Python | mit | 470 | 0 | import os
from datetime import timedelta
ROLLBAR_ACCESS_TOKEN = os.environ.get('ROLLBAR_ACCESS_TOKEN')
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgres:///dynoup | ')
FERNET_SECRET = os.environ.get('FERNET_SECRET')
CELERY_BROKER_URL = os.environ.get('REDIS_URL', 'redis://')
CELERY_TASK_SERIALIZER = 'json'
CELERYBEAT_S | CHEDULE = {
'http-checks': {
'task': 'scaler.tasks.run_http_checks',
'schedule': timedelta(minutes=1),
}
}
|
hlieberman/ansible-modules-core | cloud/azure/azure_rm_publicipaddress.py | Python | gpl-3.0 | 10,272 | 0.002921 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <[email protected]>
# Chris Houseknecht, <[email protected]>
#
# 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 Soft... | e a Public IP with a network interface.
options:
resource_group:
description:
- Name of resource group with which the Public IP is associated.
required: true
allocation_method:
description:
- Control whether the assigned Public IP remains permanently assigned to ... | d anytime an associated virtual machine is power cycled.
choices:
- Dynamic
- Static
default: Dynamic
required: false
domain_name_label:
description:
- The customizable portion of the FQDN assigned to public IP address. This is an explicit setting.... |
opencivicdata/pupa | pupa/tests/importers/test_membership_importer.py | Python | bsd-3-clause | 8,414 | 0.00309 | import pytest
from pupa.scrape import Membership as ScrapeMembership
from pupa.scrape import Person as ScrapePerson
from pupa.importers import MembershipImporter, PersonImporter, OrganizationImporter
from pupa.exceptions import NoMembershipsError
from opencivicdata.core.models import Organization, Post, Person, Divisio... | embership']['insert'] == 0
assert import_log['membership']['update'] == 2
# confirm the membership res | olved based on start date and its end date was updated
assert hari.memberships.count() == 1
assert hari.memberships.get().end_date == '2022-03-10'
# confirm the membership resolved based on end date and its extras were updated
assert robot.memberships.count() == 1
assert robot.memberships.get().ext... |
kennethreitz/pipenv | pipenv/vendor/dparse/updater.py | Python | mit | 4,566 | 0.001533 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import re
import json
import tempfile
import toml
import os
class RequirementsTXTUpdater(object):
SUB_REGEX = r"^{}(?=\s*\r?\n?$)"
@classmethod
def update(cls, content, dependency, version, spec="==", hashes... |
for package_type in ['default', 'develop']:
if package_type in data:
if dependency.full_name in data[package_type]:
data[package_type][dependency.full_name] = {
'hashes': [
"{method}:{has... | ) for h in hashes
],
'version': "{spec}{version}".format(
spec=spec, version=version
)
}
return json.dumps(data, indent=4, separators=(',', ': ')) + "\n"... |
ResolveWang/algrithm_qa | arrandmatrix/q17.py | Python | mit | 1,207 | 0.00095 | """
问题描述:给定一个矩阵matrix,其中的值有正、负和0,返回子矩阵的最大累加和.
例如,矩阵matrix为
-90 48 78
64 -40 64
-81 -7 66
其中,最大累加和的子矩阵为:
48 78
-40 64
-7 66
所以返回累加和209.
例如,matrix为:
-1 -1 -1
-1 2 2
-1 -1 -1
其中,最大累加和的子矩阵为:
2 2
所以返回累加和为4.
"""
import sys
from arrandmatrix.q16 import MaxSum
class MaxMat | rixSum:
@classmethod
def get_max_sum(cls, matrix):
if not matrix:
return 0
max_value = -sys.maxsize
for i in range(len(matrix)):
j = i
pre_arr = [0 for _ in range(len(matrix[0]))]
while j < len(matrix):
arr = cls.arr_add(m... | alue])
j += 1
pre_arr = arr
return max_value
@classmethod
def arr_add(cls, arr1, arr2):
return [arr1[i]+arr2[i] for i in range(len(arr1))]
if __name__ == '__main__':
my_matrix = [
[-90, 48, 78],
[64, -40, 64],
[-81, -7, 66]
]
... |
alephobjects/Cura | Cura/util/resources.py | Python | agpl-3.0 | 9,176 | 0.029316 | #coding:utf8
"""
Helper module to get easy access to the path where resources are stored.
This is because the resource location is depended on the packaging method and OS
"""
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
import os
import sys
import glob
import platform
i... | phaAndExperimen | tal(item):
has_special = False
experimental_indicator = '*'
key = item.name
if key.startswith(experimental_indicator):
has_special = True
return has_special, key.lstrip(experimental_indicator).lower()
def getSimpleModeMaterials():
machine_type = profile.getMachineSetting('machine_type')
paths = []
paths.appe... |
andrewfu0325/gem5-aladdin | src/python/m5/main.py | Python | bsd-3-clause | 14,348 | 0.003694 | # Copyright (c) 2005 The Regents of The University of Michigan
# 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 ... | ault]")
# Debugging options
group("Debugging Options")
option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
help="Tick to create a brea | kpoint")
option("--debug-help", action='store_true',
help="Print help on debug flags")
option("--debug-flags", metavar="FLAG[,FLAG]", action='append', split=',',
help="Sets the flags for debug output (-FLAG disables a flag)")
option("--debug-start", metavar="TIME", type='int',
help="... |
jhogsett/linkit | python/mc_send.py | Python | mit | 1,096 | 0.000912 | #!/usr/bin/python
import socket
import struct
import sys
message = 'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settime... | derr, 'waiting to receive'
try:
data, server = sock.recvfrom(16)
except socket.timeout:
print >>sys.stderr, 'timed out, no more responses'
break
else:
print >>sys.stderr, 'received "%s" | from %s' % (data, server)
finally:
print >>sys.stderr, 'closing socket'
sock.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.