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 |
|---|---|---|---|---|---|---|---|---|
julien-hadleyjack/genrss-py | src/genrss/tracklist.py | Python | bsd-2-clause | 1,857 | 0.003231 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from lxml import html
from tinydb import TinyDB, Query
import requests
from . import get_logger, CONFIG
class TracklistManager(object):
db = TinyDB(CONFIG["technical"]["tracklist-db"], indent=2, separators=(',', ': '))
ge... | tree = html.fromstring(page.text)
for track in tree.xpath('//div[@class="segment__track"]'):
try:
| artist_names = track.xpath('.//span[@property="byArtist"]//span[@class="artist"]/text()')
except ValueError:
artist_names = []
artist = ', '.join(artist_names)
try:
title, = track.xpath('.//p/span[@property="name"]/text()')
... |
fsalamero/pilas | pilas/actores/__init__.py | Python | lgpl-3.0 | 2,442 | 0.02297 | # -*- encoding: utf-8 -*-
# Pilas engine - A video game framework.
#
# Copyright 2010 - Hugo Ruscitti
# License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# Website - http://www.pilas-engine.com.ar
import math
import inspect
import pilas
from . import utils
from .actor import Actor
todos = []
__doc__ = ... | mport Misil
from .proyectil import Dinamita
from .proyectil import EstrellaNinja
from .torreta import Torreta
from .ovni import Ovni
from .manzana import Manzana
from .robot import | Robot
from .robot import Board
def listar_actores():
"""Devuelve una lista con todos los actores disponibles para crear en pilas
"""
return [k for k, v in vars(pilas.actores).items()
if inspect.isclass(v) and issubclass(v, Actor)]
|
xavfernandez/pip | src/pip/_internal/utils/wheel.py | Python | mit | 7,302 | 0 | """Support functions for working with wheel files.
"""
from __future__ import absolute_import
import logging
from email.parser import Parser
from zipfile import ZipFile
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.pkg_resources import DistInfoDistribution
from pip._vendor.six import PY2... | )
def pkg_resources_distribution_for_wheel(wheel_zip, name, loca | tion):
# type: (ZipFile, str, str) -> Distribution
"""Get a pkg_resources distribution given a wheel.
:raises UnsupportedWheel: on any errors
"""
info_dir, _ = parse_wheel(wheel_zip, name)
metadata_files = [
p for p in wheel_zip.namelist() if p.startswith("{}/".format(info_dir))
]
... |
cloudanswers/ccp-integrations | webhooks/helpscout.py | Python | agpl-3.0 | 265 | 0 | from | flask import Blueprint, request, jsonify
import time
app = Blueprint('helpscout_webhook', __name__)
@app.route("/webhooks/helpscout_app_callback", methods=['POST'])
def helpscout_ | webhook():
return jsonify({"html": "<b>test</b> test %s" % time.gmtime()})
|
tensorflow/examples | tensorflow_examples/lite/model_maker/core/data_util/object_detector_dataloader.py | Python | apache-2.0 | 15,144 | 0.00383 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | able shows mapping label integers ids to string label
names. 0 is the reserved key for `background` and doesn't need to be
included in label_map. Label names can't be duplica | ted. Supported
formats are:
1. Dict, map label integers ids to string label names, such as {1:
'person', 2: 'notperson'}. 2. List, a list of label names such as
['person', 'notperson'] which is
the same as setting label_map={1: 'person', 2: 'notperson'}.
3. Strin... |
mscuthbert/abjad | abjad/tools/selectiontools/test/test_selectiontools_Selection__all_are_components_in_same_logical_voice.py | Python | gpl-3.0 | 46,366 | 0.001229 | # -*- encoding: utf-8 -*-
import pytest
from abjad import *
Component = scoretools.Component
Selection = selectiontools.Selection
def test_selectiontools_Selection__all_are_components_in_same_logical_voice_01():
r'''Unincorporated | leaves do not share a logical voice.
Unicorporated leaves do not share a root component.
False if not allow orphans; True if allow orphans.
'''
notes = [Note("c'8"), Note("d'8"), Note("e'8"), Note("f'8")]
assert Selection._all_are_components_in_same_logical_voice(notes)
assert not Sele | ction._all_are_components_in_same_logical_voice(
notes, allow_orphans=False)
def test_selectiontools_Selection__all_are_components_in_same_logical_voice_02():
r'''Container and leaves all logical voice.
'''
container = Container("c'8 d'8 e'8 f'8")
r'''
{
c'8
d'8
e... |
Mellthas/quodlibet | quodlibet/library/file.py | Python | gpl-2.0 | 15,337 | 0.000326 | # 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 time
from pathlib import Path
from typing import Generator, Set,... | ns:
bool
"""
raise NotImplementedError
def scan(self, paths, exclude=[], cofuncid=None):
def need_yield(last_yield=[0]):
current = time.time()
if abs(current - last_yield[0]) > 0.015:
last_yield[0] = current
return True
... | current = time.time()
if abs(current - last_added[0]) > 1.0:
last_added[0] = current
return True
return False
# first scan each path for new files
paths_to_load = []
for scan_path in paths:
print_d(f"Scanning {s |
persandstrom/home-assistant | tests/components/image_processing/test_microsoft_face_detect.py | Python | apache-2.0 | 5,410 | 0 | """The tests for the microsoft face detect platform."""
from unittest.mock import patch, PropertyMock
from homeassistant.core import callback
from homeassistant.const import ATTR_ENTITY_PICTURE
from homeassistant.setup import setup_component
import homeassistant.components.image_processing as ip
import homeassistant.c... | def mock_face_event(event):
"""Mock event."""
face_events.append(event)
self.hass.bus.listen(' | image_processing.detect_face', mock_face_event)
aioclient_mock.get(url, content=b'image')
aioclient_mock.post(
self.endpoint_url.format("detect"),
text=load_fixture('microsoft_face_detect.json'),
params={'returnFaceAttributes': "age,gender"}
)
ip.sc... |
googleapis/python-appengine-admin | google/cloud/appengine_admin_v1/services/firewall/__init__.py | Python | apache-2.0 | 745 | 0 | # -*- coding: utf-8 -*-
# Copyright 2022 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, software
# distributed under the ... | e governing permissions and
# limitations under the License.
#
from .client import FirewallClient
from .async_client import FirewallAsyncClient
__all__ = (
"FirewallClient",
"FirewallAsyncClient",
)
|
rootio/rootio_web | alembic/versions/initial_added_tables.py | Python | agpl-3.0 | 13,787 | 0.015014 | """Added initial tables
Revision ID: initial
Revises: None
Create Date: 2013-10-25 16:52:12.150570
"""
# revision identifiers, used by Alembic.
revision = 'initial'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
... | llable=True),
sa.ForeignKeyConstraint(['network_id'], ['radio_network.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user_user.id'], ),
sa.PrimaryKeyConstraint()
)
op.create_table(u'radio_personlanguage',
sa.Column(u'language_id', sa.Integer(), nullable=True),
sa.Column(u'person_id', sa.Int... | traint(['person_id'], ['radio_person.id'], ),
sa.PrimaryKeyConstraint()
)
op.create_table('radio_episode',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('program_id', sa.Integer(), nullable=False),
sa.Column('recording_id', sa.Integer(), nullable=True),
sa.Column('created_time', s... |
tokyo-jesus/university | src/python/koans/python3/runner/writeln_decorator.py | Python | unlicense | 473 | 0.012685 | #!/usr/bin/env python
# | encoding: utf-8
import sys
import os
# Taken from legacy python unittest
class WritelnDecorator:
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __getattr__(self, attr):
return getattr(self.stream,attr)
def wr... | |
apache/incubator-systemml | src/main/python/tests/matrix/test_transpose.py | Python | apache-2.0 | 2,059 | 0.002428 | # -------------------------------------------------------------
#
# 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 unde... | )
def test_row(self):
trans = self.sds.from_numpy( mx).t().c | ompute()
self.assertTrue(np.allclose(trans, np.transpose(mx)))
def test_col(self):
trans = self.sds.from_numpy( my).t().compute()
self.assertTrue(np.allclose(trans, np.transpose(my)))
if __name__ == "__main__":
unittest.main(exit=False)
|
NekBox/nekpy | nekpy/dask/subgraph.py | Python | mit | 1,652 | 0.004843 | from copy import deepcopy
from .tasks import prepare, update_config, run, analyze, prepare_
from dask.base import tokenize
from dask.delayed import delayed
from math import ceil
from ..config import config as cfg
nekmpi_path = cfg.nekmpi
load_path = cfg.load
def series(base_in, tusr, job_step = 0, job_time = 0.):... | ex = 0
nres = max(3, base["torder"])
end_time = job_time
res = {}
data = deepcopy(base)
base["job_name"] = base["name"]
base["job_time"] = job_time
data = prepare(base, tusr)
for i in range(njob):
diff = {"restart": restart, "outind": out_index}
if i == 0:
res... | restart += nres
out_index += nio
if job_step > 0:
diff["num_steps"] = min(job_step, base["num_steps"] - i*job_step)
if job_time > 0:
diff["end_time"] = end_time
end_time += job_time
diff["job_name"] = "{}-{}".format(base["name"], i)
... |
pankajanand18/python-tests | linkedlists/reverserlist.py | Python | mit | 1,457 | 0.021277 |
from linkedlist import SinglyLinkedListNode
def reverseList(head):
tail=None
last=None
tempNode = head
while tempNode is not None:
currentNode, tempNode = tempNode, tempNode.next
currentNode.next = tail
tail = currentNode
return tail
def reverseListKNode(head,k):
... | tempTail.next = last
head.next = nextNode
else:
tempHead = last
head.next= nextNode
tempTail = head
head=nextNode
return tempHead
def printLinkedList(head):
while head is not None:
print | head.data,
head=head.next
print ''
def createList(list):
lastNode=None
head=None
for i in list:
node= SinglyLinkedListNode(i)
if lastNode == None:
lastNode = node
head = node
else:
lastNode.next = node
lastNode=node
... |
skylifewww/pangolin_new | content/templatetags/content_tags.py | Python | mit | 4,762 | 0.00441 | from django import template
# from django.contrib.ad | min.util import lookup_field
# from django.core.exceptions import ObjectDoesNotExist
# from django.core.urlresolvers import NoReverseMatch, reverse
# from django.db.models import ForeignKey
# from django.template.defaulttags import NowNode
# from django.utils.safestring import mark_safe
from django.shortcuts import ren... | tml')
def meta_title():
meta = get_object_or_404(Meta, published=1)
return {'title': meta.meta_title}
@register.inclusion_tag('meta/author.html')
def meta_author():
meta = get_object_or_404(Meta, published=1)
return {'author': meta.meta_author}
@register.inclusion_tag('meta/description.htm... |
vecnet/vnetsource | lib/views/error_views.py | Python | mpl-2.0 | 3,043 | 0.008544 | from django import http
from django.shortcuts import render, redirect
from django.template import (loader, TemplateDoesNotExist)
from django.views.decorators.csrf import requires_csrf_token
from django.core.urlresolvers import reverse
from lib.templatetags.base_extras import set_notification
import smtplib
from datetim... | loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseServerError('<h1>Server Error - Template Not Found</h1>')
context = {'STATIC_URL': '/static/'}
if template_name == "500.html":
status = 500
if template_name == "403.html":
status = 403
| if template_name == "404.html":
status = 404
return render(request, template_name, context, status = status)
@requires_csrf_token
def error_submit(request):
try:
sender_email = settings.SERVER_EMAIL
server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
if getattr... |
pawelkalinowski/project-python | Fibonacci n-th number (iterative).py | Python | mit | 1,745 | 0.005731 | """
The MIT License (MIT)
Copyright (c) 2013 Pawel Kalinowski
Permission is hereby granted, free of charge, to | any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including | without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies o... |
spectralDNS/spectralDNS | demo/Vortices2D.py | Python | lgpl-3.0 | 2,458 | 0.004475 | """
2D test case with three vortices
"""
from numpy import zeros, exp, pi, loadtxt, allclose, where
import matplotlib.pyplot as plt
from shenfun import Array
from spectralDNS import config, get_solver, solve
def initialize(U, X, U_hat, K_over_K2, T, **context):
w = exp(-((X[0]-pi)**2+(X[1]-pi+pi/4)**2)/(0.2)) \
... | t('vortices.txt')
U = context.U_hat.backward(context.U)
assert allclose(U[0], U_ref)
im = None
def update(context):
global im
params = config.params
solver = config.solver
# initialize plot
if params.tstep == 1:
| im = plt.imshow(zeros((params.N[0], params.N[1])))
plt.colorbar(im)
plt.draw()
if params.tstep % params.plot_result == 0 and params.plot_result > 0:
curl = solver.get_curl(**context)
im.set_data(curl[:, :])
im.autoscale()
plt.pause(1e-6)
if __name__ == '__main__':
... |
PearsonIOKI/compose-forum | askbot/models/signals.py | Python | gpl-3.0 | 3,977 | 0.004023 | """Custom django signals defined for the askbot forum application.
"""
import django.dispatch
from django.db.models.signals import pre_save, post_save, pre_delete, post_delete, post_syncdb
try:
from django.db.models.signals import m2m_changed
except ImportError:
pass
tags_updated = django.dispatch.Signal(
... | 'user', 'form_data']
)
post_updated = django.dispatch.Signal(
providing_args=[
'post',
| 'updated_by',
'newly_mentioned_users'
]
)
post_revision_published = django.dispatch.Signal(
providing_args = [
'revisi... |
toopy/django-toopy-website | src/toopy/admin/admin_.py | Python | mit | 638 | 0.001567 | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
def _date(obj):
return obj.date.strftime('%Y-%m-%d %H:%M:%S')
_date.short_description = _(u'Date')
class AdminContact(admin.ModelAdmin):
fields = (
'email',
'subject',
'message',
... |
'email',
'subject',
'website',
_date,
)
search_fields = (
'email',
'subject',
| 'message',
'website',
)
|
brahul90/cheapflights | cheapflights/main.py | Python | apache-2.0 | 1,721 | 0.024404 | ## Adding ./getresults to the Python path so that the modules in folder can be imported
import sys
sys.path.insert(0, './getresults')
import datetime
from flightsearch import flightsearch, flightresult
import os
import uuid
import time
from pprint import pprint
def main():
flyfrom = 'YYZ' #input("Enter departure ... | pprint(vars(item))
## This function aggegates the various results obtained from the modules in the ./getresults folder
def aggregatedflights(flightsearch):
getresultsdir = './getresults'
resultdict = {}
for filename in os.listdir(getresultsdir):
if filename.startswith("get") and filename... | __import__(modulename)
resultdict[modulename] = mod.getresult(flightsearch)
else:
continue
return sortbyprice(resultdict)
def sortbyprice(flightresult):
## Coming soon
return flightresult
if __name__ == '__main__':
main()
|
RulersOfAsgard/ALAMO-scheduler | alamo_scheduler/aioweb.py | Python | apache-2.0 | 3,647 | 0 | # -*- coding: utf-8 -*-
import asyncio
import logging
from alamo_scheduler.conf import settings
from pip import get_installed_distributions
from aiohttp.client import ClientSession
from aiohttp.web import Application, Response, json_response
logger = logging.getLogger(__name__)
__all__ = ['ClientSession', 'json_res... | contract()
self._handler = self.app.make_handler()
self._server = loop.create_server(
self._handler, settings.SERVER_HOST,
settings.SERVER_PORT, backlog=backlog
)
self._srv, self._startup_res = loop.run_until_complete(
asyncio.gather(self._server, sel... | started at http://{}:{}'.format(
settings.SERVER_HOST, settings.SERVER_PORT
))
def finish_connections(self):
loop = self.app.loop
self._srv.close()
loop.run_until_complete(self._srv.wait_closed())
loop.run_until_complete(self.app.shutdown())
loop.run_unt... |
jaety/image-river | indexer/logutil.py | Python | apache-2.0 | 584 | 0.006849 | imp | ort logging as log
import time
log.basicConfig(level=log.INFO)
warning = log.warning
info = log.info
def timed(show_args = True):
def timed_decorator(f):
def _timed(*args, **kw):
ts = time.time()
result = f(*args, **kw)
te = time.time()
if show_args:
... | log.info('func:%r took: %2.4f sec' % (f.__name__, te-ts))
return result
return _timed
return timed_decorator
|
ryota-sugimoto/hackerrank | dynamic_programming/grid_walking/tmp.py | Python | gpl-2.0 | 1,371 | 0.05981 | #!/usr/bin/env python
def n_ways(x, d, M):
memo = {}
def | loop(x,M):
if memo.has_key((x,M)):
return memo[(x,M)]
if M == 0:
return 1
| if x == d and x == 1:
return 0
if x == 1:
memo[(x,M)] = loop(x+1, M-1)
elif x == d:
memo[(x,M)] = loop(x-1, M-1)
else:
memo[(x,M)] = loop(x-1, M-1) + loop(x+1, M-1)
return memo[(x,M)]
return loop(x,M)
from math import factorial
def gen_ncr():
d = {}
def ncr(n,r):
... |
Guerillero/ArcExtractor | Extractor.py | Python | mit | 2,156 | 0.001855 | ##################################################################
# Extract a dbtable for every instance of a value in a geo-file #
# Written by Thomas Fish #
# Released under the MIT License #
# ... | fileName)):
filePath.append(outLocation + "\\" + fileName[y])
for z in range(len(fieldValues)):
# Extract out only the entries that are wanted
arcpy.AddMessage("Currently extracting " + fieldValues[z] + " in " + fieldName)
if lyr.name == "MyFile | ":
lyr.definitionQuery = fieldName + " =" + "'" + fieldValues[z] + "'"
arcpy.CopyRows_management(lyr, filePath[z])
fin.close()
if spreadsheetType == "csv":
FileTransformations.dbf2csv(outLocation, fieldValues, filePath)
elif spreadsheetType == "tsv":
FileTransformations.dbf2tsv(outLocation, fieldVa... |
ergonomica/ergonomica | ergonomica/lib/lib/ergo_del.py | Python | gpl-2.0 | 481 | 0.008316 | #!/ | usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
[lib/lib/ergo_del.py]
Defines the "del" command.
"""
from ergonomica import ErgonomicaError
def _del(argc):
"""del: Delete variables.
Usage:
del [<variable>VARS...]
"""
for var in argc.args['VARS']:
try:
... | del}
|
dkopecek/amplify | third-party/quex-0.65.2/quex/engine/generator/base.py | Python | gpl-2.0 | 9,154 | 0.010269 | # (C) Frank Rene Schaefer
import quex.engine.generator.state_machine_coder as state_machine_coder
import quex.engine.generator.state_router as state_router_generator
from quex.engine.generator.languages.variable_db import variable_db
from quex.engine.analyzer.door_id_address_label ... | ss_set()
# If there is only one address subject to state routing, then the
# state router needs to be implemented.
#if len(routed_address_set) == 0:
# return []
# Add the address of 'terminal_end_of_file()' if it is not there, already.
# (It should not be there, if we are working on a fixed ... | ng is webbed into analysis:: assert address_eof in routed_address_set)
if False:
address_eof = dial_db.get_address_by_door_id(DoorID.incidence(E_IncidenceIDs.END_OF_STREAM))
routed_address_set.add(address_eof)
dial_db.mark_label_as_gotoed(dial_db.get_label_by_address(address_eof))
... |
FabriceSalvaire/PyValentina | Patro/GeometryEngine/Rectangle.py | Python | gpl-3.0 | 3,505 | 0.002282 | ####################################################################################################
#
# Patro - A Python library to make patterns for fashion design
# Copyright (C) 2017 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gene... | Segment2D(p0, p1),
Segment2D(p1, p2),
Segment2D(p2, p3),
Segment2D(p3, p0),
| )
##############################################
@property
def diagonal(self):
return self._p1 - self._p0
##############################################
@property
def perimeter(self):
d = self.diagonal
return 2*(abs(d.x) + abs(d.y))
##########################... |
manhhomienbienthuy/scikit-learn | sklearn/datasets/tests/test_openml.py | Python | bsd-3-clause | 53,604 | 0.000597 | """Test the openml loader.
"""
import gzip
import warnings
import json
import os
import re
from importlib import resources
from io import BytesIO
import numpy as np
import scipy.sparse
import sklearn
import pytest
from sklearn import config_context
from sklearn.datasets import fetch_openml as fetch_openml_orig
from sk... | ories[col_name]
result = [
None if is_scalar_nan(idx) else cat[int(idx)]
| for idx in data_bunch.data[:, col_idx]
]
return np.array(result, dtype="O")
else:
# non-nominal attribute
return data_bunch.data[:, col_idx]
data_bunch = fetch_openml(
data_id=data_id, cache=False, target_column=None, as_frame=False
)
... |
jhseu/tensorflow | tensorflow/python/debug/lib/debug_events_monitors_test.py | Python | apache-2.0 | 18,786 | 0.005217 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | n(self, execution_index, execution):
if execution_index in self.executions:
raise ValueError("Duplicate execution index: %d" | % execution_index)
self.executions[execution_index] = execution
def on_graph_execution_trace(self, graph_execution_trace_index,
graph_execution_trace):
if graph_execution_trace_index in self.graph_execution_traces:
raise ValueError("Duplicate graph-execution-trace index: ... |
pinry/pinry | django_images/models.py | Python | bsd-2-clause | 4,263 | 0 | import hashlib
import os.path
from django.db import models
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.dispatch import receiver
from importlib import import_module
from django.urls import reverse
from . import utils
from .settings import IMAGE_SIZES, IMAGE_PATH, IMAGE_AUTO_DELETE
d... | ):
original = models.ForeignKey(Image, on_delete=models.CASCADE)
image = models.ImageField(upload_to=upload_to,
height_field='height', width_field='width',
max_length=255)
size = models.CharField(max_length=100)
height = models.PositiveIntegerF... | objects = ThumbnailManager()
class Meta:
unique_together = ('original', 'size')
def get_absolute_url(self):
return self.image.url
@receiver(models.signals.post_save)
def original_changed(sender, instance, created, **kwargs):
if isinstance(instance, Image):
instance.thumbnail_set.... |
greencoder/hopefullysunny-django | registrations/management/commands/registration_worker.py | Python | mit | 1,481 | 0.006752 | import zmq
import datetime
import pytz
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from registrations.models import Registration
from registrations import handlers
from registrations import tasks
class Command(BaseCommand):
def log(self, message):
f... | .TASK_LOG_PATH, 'a')
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
log_message = "%s\t%s\n" % (now, message)
self.stdout.write(log_message)
f.write(log_message)
f.close()
def handle(self, *args, **options):
context = zmq.Context()
pull_s... | self.log("Registration Worker ZMQ Socket Bound to 7002")
while True:
try:
data = pull_socket.recv_json()
task_name = data.pop('task')
task_kwargs = data.pop('kwargs')
self.log("Got task '%s' with kwargs: %s" % (task_n... |
chienlieu2017/it_management | odoo/addons/point_of_sale/wizard/pos_box.py | Python | gpl-3.0 | 1,816 | 0.002203 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, _
from odoo.exceptions import UserError
from odoo.addons.account.wizard.pos_box import CashBox
class PosBox(CashBox):
_register = False
@api.multi
def run(self):
active_model... | e(active_ids)[0].name
return valu | es
|
arielisidro/myprograms | python/6.00.1x Files/ps4/ps4a.py | Python | gpl-2.0 | 9,787 | 0.011239 | # 6.00x Problem Set 4A Template
#
# The 6.00 Word Game
# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
# Modified by: Sarina Canelake <sarina>
#
import random
import string
import os
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 13
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd... | ': 8, 'y': 4, 'z': 10
}
# ------------ | -----------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = os.path.dirname(__file__)+"/words.txt"
print WORDLIST_FILENAME
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list... |
lkorigin/laniakea | src/rubicon/rubicon/fileimport.py | Python | gpl-3.0 | 6,906 | 0.001593 | # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net>
#
# Licensed under the GNU Lesser General Public License Version 3
#
# This program 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, eith... | if spkg:
suite_target_name = '?'
if job.data:
suite_target_name = job.data.get('suite', '?')
event_data = {'pkgname': spkg.name,
'version': job.version,
'architecture': job.architecture... | ubmit_event_for_mod(LkModule.ARCHIVE, 'package-build-success', event_data)
else:
event_emitter.submit_event_for_mod(LkModule.ARCHIVE, 'package-build-failed', event_data)
else:
event_emitter.submit_event('upload-accepted', {'job_id': job_id, 'job_failed': not job_s... |
agrc/deq-enviro | scripts/nightly/databases/test.py | Python | mit | 187 | 0.02139 | import arcpy, os
db = os.path.join(os.path.dirname(os.path.abs | path(__file__)), r'eqedocsp.sde\AGRC.VW_DSHW_FACILITY')
if arcpy | .Exists(db):
print('pass')
else:
print('fail')
|
sinkap/trappy | trappy/wa/results.py | Python | apache-2.0 | 5,153 | 0.00097 | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | _min) / 10
if margin < 1:
margin = 1
update_axis = False
if data_min <= plot_y_min:
plot_y_min = data_min - margin
update_axis = True
if data_max >= plot_y_max:
plot_y_max = data_max + margin
update_axis = True
if up... |
A title is added to the plot if title is not supplied
"""
if title is None:
title = benchmark.replace('_', ' ')
title = title.title()
self[benchmark].plot(ax=self.ax, kind="bar", title=title)
plt.legend(bbox_to_anchor=(1.05, .5), loc=6)
def plot_re... |
saltstack/salt | tests/pytests/unit/modules/test_rpm_lowpkg.py | Python | apache-2.0 | 11,207 | 0.000803 | """
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import pytest
import salt.modules.cmdmod
import salt.modules.rpm_lowpkg as rpm
import salt.utils.path
from tests.support.mock import MagicMock, patch
# pylint: disable=unused-import
try:
import rpm as rpm_lib
HAS_RPM = True
except ImportError:
... | age"
mock = MagicMock(return_value=ret)
with patch.dict(rpm.__salt__, {"cmd.run_stdout": mock}):
assert rpm.owner("/usr/bin/salt-jenkins-build") == ""
assert not _c | alled_with_root(mock)
ret = {
"/usr/bin/vim": "vim-enhanced-7.4.160-1.e17.x86_64",
"/usr/bin/python": "python-2.7.5-16.e17.x86_64",
}
mock = MagicMock(
side_effect=[
"python-2.7.5-16.e17.x86_64",
"vim-enhanced-7.4.160-1.e17.x86_64",
]
)
with p... |
Wheelspawn/Python-Code-Fragments | IsGraphic.py | Python | gpl-3.0 | 1,082 | 0.019409 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 12:49:53 2018
A program that will tell if a given degree sequence is graphic.
Uses th | e Havel-Hakimi algorithm. Returns a boolean.
Steps are printed to console.
@author: nsage
"""
def is_graphic(l): # checks to se | e if a degree list is graphic
# if a vertex has an extra edge
# or the sum is odd (sum of the degrees of v must be 2|e|)
if l[0] > len(l)-1 or sum(l)%2==1:
return False
else:
if sum(l) == 0: # if vertex elimination is complete
return True
else: # delete the highest ... |
jean/sentry | src/sentry/api/endpoints/auth_index.py | Python | bsd-3-clause | 2,868 | 0.000697 | from __future__ import absolute_import
from django.contrib.auth import logout
from django.contrib.auth.models import AnonymousUser
from rest_framework.response import Response
from sentry.api.authentication import QuietBasicAuthentication
from sentry.models import Authenticator
from sentry.api.base import Endpoint
fr... | rnally in Sentry.
Common example::
curl -X ###METHOD### -u username:password ###URL###
"""
if not request.user.is_authenticated():
return Response(status=400)
# If 2fa login is enabled then we cannot sign in with username and
# password through this api... | esponse(
{
'2fa_required': True,
'message': 'Cannot sign-in with basic auth when 2fa is enabled.'
},
status=403
)
try:
# Must use the real request object that Django knows about
auth.logi... |
aginzberg/crowdsource-platform | crowdsourcing/migrations/0000_get_requester_ratings_fn.py | Python | mit | 3,733 | 0.004286 | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crowdsourcing', '0007_auto_20151208_1957'),
]
operations = [
migrations.RunSQL('''
CREATE OR REPLACE FUNCTION get_requester_ratings(IN worker_profile_id INTEGER)
... | wr_rating.weight,
avg_wr_rating
FROM crowdsourcing_requester r
| LEFT OUTER JOIN (
SELECT
wrr.target_id,
wrr.weight AS weight
FROM crowdsourcing_workerrequesterrating wrr
INNER JOIN (... |
CognitionGuidedSurgery/msml | src/msml/exporter/msml_namespace.py | Python | gpl-3.0 | 231 | 0.038961 | __author__ = 'suwelack'
|
from rdflib.namespace import ClosedNamespace
#MSMLRep= ClosedNamespace(
# uri=URIRef("http://www.msml.org/ontology/msmlRepresentation#"),
# terms=[ |
# 'isRepresentationOf', 'isDataNodeFor']
#) |
ankostis/ViTables | examples/scripts/MDobjects.py | Python | gpl-3.0 | 2,868 | 0.004881 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved
# Copyright (C) 2008-2017 Vicent Mas. All rights reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | exercise ViTables capability to zoom into
multidimensional cells.
It also works to check views of multidimensional attributes.
"""
import tables
import numpy
class Particle(tables.IsDescription):
"""Description of a table record."""
name = tables.StringCol(16, pos=1)
| lati = tables.IntCol(pos=2)
vector = tables.Int32Col(shape=(200,), pos=3)
matrix1 = tables.Int32Col(shape=(2, 200), pos=4)
matrix2 = tables.FloatCol(shape=(100, 2), pos=5)
matrix3 = tables.FloatCol(shape=(10, 100, 2), pos=5)
matrix4 = tables.FloatCol(shape=(2, 10, 100, 2), pos=5)
# Open a file in "... |
tuxite/pharmaship | pharmaship/inventory/migrations/0002_item_packing.py | Python | agpl-3.0 | 1,592 | 0.005653 | # Generated by Django 3.0.7 on 2020-12-07 08:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='packing_content',
... | me='packing_content',
field=models.PositiveIntegerField(default=1, verbose_name='Quantity per pack'),
),
migrations.AddField(
model_name='firstaidkititem',
name='packing_name',
field=models.PositiveIntegerField(choices=[(0, 'default'), (10, 'box'), | (11, 'set'), (20, 'pair'), (120, 'dozen'),], default=0),
),
migrations.AddField(
model_name='medicine',
name='packing_content',
field=models.PositiveIntegerField(default=1, verbose_name='Quantity per pack'),
),
migrations.AddField(
model_n... |
kezilu/pextant | pextant/sextant.py | Python | mit | 6,172 | 0.005347 | from flask_settings import GEOTIFF_FULL_PATH
import sys
import traceback
sys.path.append('../')
import numpy as np
import json
from datetime import timedelta
from functools import update_wrapper
from pextant.EnvironmentalModel import GDALMesh
from pextant.explorers import Astronaut
from pextant.analysis.loadWaypoints... | del.ROW_COL, *np.array(rawpoints).transpose()).to(LAT_LONG)
return_json['latlong'].append({'latitudes': list(lat), 'longitudes': list(lon)})
return json.dumps(return_json)
# OLD Stuff: delete
@app.route('/', methods=['GET', 'POST'])
@crossdomain(origin='*')
def get_waypoints():
... | )
#json_waypoints = JSONloader(xpjson)
waypoints = GeoPolygon(LAT_LONG, *data_np)
print waypoints.to(LAT_LONG)
environmental_model = gdal_mesh.loadSubSection(waypoints.geoEnvelope(), cached=True)
explorer = Astronaut(80)
solver = astarSolver(environmental_model, explorer... |
NarrativeScience/lsi | setup.py | Python | bsd-2-clause | 583 | 0 | import setuptools
import os
# This will add the __version__ to the globals
with open("src/lsi/__init__.py") as f:
exec(f.read())
setuptools.setup(
name='lsi',
version=__version__,
author="Narrative Science",
author_email="anelson@narrativescience.com",
url="https://github.com/NarrativeScience/... | ines(),
entry_points={
'console_scripts': ['lsi = lsi.lsi:main']
| }
)
|
annarev/tensorflow | tensorflow/python/feature_column/feature_column_lib.py | Python | apache-2.0 | 1,597 | 0.000626 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ========================
"""FeatureColumns: tools for ingesting and representing features."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long,wildcard-import,g-bad-import-order
from tensorflow.python.feature_col... | mn.feature_column_v2 import *
from tensorflow.python.feature_column.sequence_feature_column import *
from tensorflow.python.feature_column.serialization import *
# We import dense_features_v2 first so that the V1 DenseFeatures is the default
# if users directly import feature_column_lib.
from tensorflow.python.keras.fe... |
BearlyKoalafied/GGGGobbler | db/db.py | Python | mit | 9,293 | 0.003228 | import os.path
import sqlite3
from util import filepather
from db.data_structs import StaffPost
DB_FILE_NAME = "GGGGobbler.sqlite"
class DAO:
def __init__(self):
if os.path.isfile(filepather.relative_file_path(__file__, DB_FILE_NAME)):
self.open()
else:
self.open()
... | staffpost_date "
"FROM staffpost WHERE poethread_id = ?", (poe_thread_id,))
results = cur.fetchall()
if results is None:
return []
return [StaffPost(result[0], poe_thread_id, result[1], result[2], result[3])
for result in r... | """
gets the recorded page counter of given thread
"""
cur = self.db.cursor()
try:
cur.execute("SELECT poethread_page_count FROM poethread WHERE poethread_id = ?",
(poe_thread_id,))
row = cur.fetchone()
return None if row ... |
kekeller/german_endings | analyze_data/user_input.py | Python | mit | 1,854 | 0.055556 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from time import strftime
def append_new_end(word,user_end):
space_count = word.count('~') # count number of placeholders
if space_count > 0:
total_word = word[:-space_count] + user_end # supplied from raw input
else:
total_word = word
return t... | t
while word < len(text_new[sentence]):
user_end = raw_input(text_new[sentence][word].encode('utf-8') + ' ')
total_word = append_new_end(text_new[sentence][word],user_end)
total_word.encode('utf-8')
text_complete[sentence].append(total_word)
word += 1
sentence += 1
return text_complete
def p... | ences):
sentence = 0
while sentence < number_sentences:
contained = [x for x in text_complete[sentence] if x not in text_orig[sentence]]
print
print "Original Sentence: " ,
write_output(strftime("%Y-%m-%d %H:%M:%S"))
write_output('\n')
write_output("Original Sentence: ")
write_output('\n')
for each in... |
jupyter/jupyterlab | scripts/generate_changelog.py | Python | bsd-3-clause | 1,155 | 0.000866 | ''' Generate a changelog for JupyterLab from the GitHub releases '''
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import re
import requests
import dateutil.parser
# Get the list of releases.
r = requests.get('https://api.github.com/repos/jupyterlab/jupyterlab/r... | )
notes = re.sub(r'#([0-9]+)',
r'[#\1](https://github.com/jupyterlab/jupyterlab/issues/\1)',
notes)
title = f'{name} ({tag_name})' if name != tag_name else name
f.write(f'## [{title}]({tag_url})\n')
f.write(f'#### {ta... | f.write(notes)
f.write('\n\n')
|
peterbrittain/asciimatics | asciimatics/__init__.py | Python | apache-2.0 | 414 | 0.004831 | """
Asciimatics is a package to help people create full-screen text UIs (from interactive forms to
ASCII animations) on any platform. It is licensed under the Apache Software Foundation License 2.0.
"""
__author__ = 'Peter Brittain'
try:
from .version import version
except ImportError:
# Someone is running st... | m the GIT repo - dummy out the version
| version = "0.0.0"
__version__ = version
|
opesci/devito | devito/ir/equations/equation.py | Python | mit | 9,325 | 0.001287 | from cached_property import cached_property
import sympy
from devito.ir.equations.algorithms import dimension_sort, lower_exprs
from devito.finite_differences.differentiable import diff2sympy
from devito.ir.support import (IterationSpace, DataSpace, Interval, IntervalGroup,
Stencil, dete... | conditionals)
# Lower all Differentiable operations into SymPy operations
rhs = diff2sympy(expr.rhs)
# F | inally create the LoweredEq with all metadata attached
expr = super(LoweredEq, cls).__new__(cls, expr.lhs, rhs, evaluate=False)
expr._dspace = dspace
expr._ispace = ispace
expr._conditionals = conditionals
expr._reads, expr._writes = detect_io(expr)
expr._is_Increment =... |
alexryndin/ambari | ambari-server/src/main/resources/stacks/ADH/1.0/services/YARN/package/scripts/service_check.py | Python | apache-2.0 | 5,633 | 0.008699 | """
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 use this ... | } {yarn_distrubuted_shell_check_cmd}")
else:
smoke_cmd = yarn_distrubuted_shell_check_cmd
return_code, out = shell.checked_call(smoke_cmd,
path='/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin',
user=params.smokeuser,
... | )
application_name = self.get_app_name(out)
json_response_received = False
for rm_webapp_address in params.rm_webapp_addresses_list:
info_app_url = params.scheme + "://" + rm_webapp_address + "/ws/v1/cluster/apps/" + application_name
get_app_info_cmd = "curl --n... |
Storm7874/Utils | Messenger.py | Python | mit | 3,653 | 0.00438 | ## Messenger application. Basedd off PyMessenger by Tijndagamer
## Released under the MIT licence.
# You rock, man.
## Import stage.
try:
from Notify import Main
Notify = Main()
Notify.SetMode("C")
Notify.Success("Successfully imported Notify.")
except(ImportError):
print("[!] Failed to import Not... | break
try:
if self.__RecMessage == "--LEFT--":
Notify.Error("Client has left. Terminating Connection")
self.__conn.close()
break
except:
pass
def Main():
Local = MessengerClient()
Server =... | --------|
""")
while True:
menuchoice = int(input("[?]> "))
if menuchoice not in [1,2,3]:
Notify.Error("Please enter a valid selection.")
else:
break
if menuchoice == 1:
Notify.Info("Starting Server...")
|
tecdct2941/nxos_dashboard | repeated_timer.py | Python | apache-2.0 | 721 | 0.008322 | from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = inte | rval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _ru | n(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
s... |
OakNinja/svtplay-dl | lib/svtplay_dl/service/disney.py | Python | mit | 4,847 | 0.001444 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
from __future__ import absolute_import
import json
import re
import copy
import os
from svtplay_dl.service import Service, OpenGraphThumbMixin
from svtplay_dl.utils import get_http_data, check_redirect, filenamify
from svtplay_dl... | url = "http | ://cdnapi.kaltura.com/html5/html5lib/v1.9.7.6/mwEmbedFrame.php?&wid=%s&uiconf_id=%s&entry_id=%s&playerId=%s&forceMobileHTML5=true&urid=1.9.7.6&callback=mwi" % \
(partnerid, uiconfid, entryid, uniq)
error, data = get_http_data(url)
if error:
log.error("Cant get video i... |
ellonweb/merlin | Core/config.py | Python | gpl-2.0 | 1,487 | 0.004707 | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; ... | istribute 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 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
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fift... |
karllessard/tensorflow | tensorflow/python/keras/activations_test.py | Python | apache-2.0 | 8,461 | 0.004964 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tion([x], [activations.softmax(x)])
test_values = np.random.random((2, 5))
result = f([test_values])[0]
expected = _ref_softmax(test_values[0])
self.assertAllClose(result[0], expected, rtol=1e-05)
x = backend.placeholder(ndim=1)
with self.assertRaises(ValueError):
activations.softmax | (x)
def test_temporal_softmax(self):
x = backend.placeholder(shape=(2, 2, 3))
f = backend.function([x], [activations.softmax(x)])
test_values = np.random.random((2, 2, 3)) * 10
result = f([test_values])[0]
expected = _ref_softmax(test_values[0, 0])
self.assertAllClose(result[0, 0], expected, ... |
bytedance/fedlearner | web_console_v2/api/test/fedlearner_webconsole/mmgr/model_test.py | Python | apache-2.0 | 6,763 | 0 | # Copyright 2021 The FedLearner Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | .state, ModelState.PAUSED.value)
db.session.rollback()
def test_api(self):
resp = self.get_helper('/api/v2/models/1')
data = self.get_response_data(resp)
self.assertEqual(data.get('id'), 1)
| resp = self.get_helper('/api/v2/models')
model_list = self.get_response_data(resp)
self.assertEqual(len(model_list), 1)
model = Model.query.first()
model.state = ModelState.FAILED.value
db.session.add(model)
db.session.commit()
self.delete_helper('/api/v2/... |
abulovic/pgnd-meta | meta/data/tax.py | Python | mit | 12,071 | 0.009693 | import os, sys
from collections import defaultdict
import meta
NO_ENTRY_NAME = 'no_db_entry_name'
NO_ENTRY_RANK = 'no_db_entry_rank'
ranks = { 'superkingdom' : 0,
'kingdom' : 1,
'subkingdom' : 2,
'superphylum' : 3,
'phylum' : 4,... | for taxid in current_taxids:
# root node must not add itself to parent list
if taxid != self.root: parent_taxid = self.parent_nodes[taxid]
else: parent_taxid = None
# if parent exists, append him to parent list
... | parent_nodes.append(parent_taxid)
# Check for LCA
self.num_visited[taxid] += 1
if self.num_visited[taxid] == num_of_nodes:
self.lca_root = taxid
return taxid
# refresh current nodes
current_taxids = par... |
mahak/neutron | neutron/ipam/subnet_alloc.py | Python | apache-2.0 | 18,935 | 0 | # Copyright (c) 2015 Hewlett-Packard Co.
# 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 r... | hers will be
# rolled back and be caught in neutron.db.v2.base
with db_api.CONTEXT_WRITER.using(self._context):
query = (
self._context.session.query(models_v2.SubnetPool).filter_by(
id=self._subnetpool['id'], hash=current_hash))
count = query... | ']))
def _get_allocated_cidrs(self):
with db_api.CONTEXT_READER.using(self._context):
query = self._context.session.query(models_v2.Subnet.cidr)
subnets = query.filter_by(subnetpool_id=self._subnetpool['id'])
return (x.cidr for x in subnets)
def _get_available_prefi... |
ba1dr/tplgenerator | templates/django/__APPNAME__/apps/user_auth/admin.py | Python | mit | 110 | 0 | # -*- coding: utf-8 -*-
from django.contrib import | admin
from .models imp | ort User
admin.site.register(User)
|
peterhogan/python | oop_test.py | Python | mit | 2,018 | 0.026264 | import random
from urllib import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
"class %%% has-a __init__ hat takes self and *** parameter.",
"class %%%... | ):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range(0, snippet.count("@@@")):
param_count = random.randint(1,3)
param_names.append(', '.join(random.sample(WORDS, param_coun... | , word, 1)
# fake other names
for word in other_names:
result = result.replace("***", word, 1)
# fake parameter lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until they hit CTRL-D
try:
while True:
snippets = PHRASES.key... |
vertisfinance/docker-images | base/context/runutils.py | Python | mit | 8,413 | 0.000357 | # coding: utf-8
import os
import sys
import subprocess
import signal
import pwd
import shutil
import click
class Stopper(object):
def __init__(self):
self.stopped = False
def getvar(name, default=None, required=True):
"""
Returns the value of an environment variable.
If the variable is not... | Executes a one-off command. The message will be printed on terminal.
If input is given, it will be passed to the subprocess.
If user is given (as id or name) the process will run as the given user.
"""
if message:
| click.echo(message + ' ... ')
_setuser = setuser(user) if user else None
if input is None:
try:
output = subprocess.check_output(
args, stderr=subprocess.STDOUT, preexec_fn=_setuser)
except subprocess.CalledProcessError as e:
if message:
... |
guangtunbenzhu/BGT-Cosmology | DeepLearning/nnmath.py | Python | mit | 5,679 | 0.016024 | __license__ = "MIT"
__author__ = "Guangtun Ben Zhu (BGT) @ Johns Hopkins University"
__startdate__ = "2016.01.19"
__name__ = "nnmath"
__module__ = "Network"
__lastdate__ = "2016.01.19"
__version__ = "0.01"
__comments__ = "math utils for neural net work"
import numpy as np
from scipy.special import expit
# some small... | d = expit
sigmoid_deriv = lambda x: (0.5/np.cosh(0.5*x))**2
#### to add: softmax
def softmax(w, t=1.0):
assert w.ndim==2, "the input must be in format of [n_vector, ndim_vector]."
maxes = np.amax(w, axis=1).reshape(w.shape[0],1)
e = numpy.exp((w-maxes)/1.)
dist = e/numpy.sum(e, axis=1)
return dist
d... | mat of [n_vector, ndim_vector]."
tmp = np.eye((wsm.shape[1]).reshape(1, wsm.shape[1], wsm.shape[1]))
tmp_diag_indices = np.diag_indices(wsm.shape[1])
output = np.tile(tmp, np.r_[wsm.shape[0], np.ones(3)])
for i in np.arange(wsm.shape[0]):
output[i, tmp_diag_indices] = wsm[i, :]
output[i,... |
ajfazan/tools | scripts/compute_vector_difference.py | Python | gpl-2.0 | 2,566 | 0.045207 | #!/usr/bin/env osgeo_python
from osgeo import ogr, osr
import os, sys
def openDataSource( filename ):
driver = ogr.GetDriverByName( "ESRI Shapefile" )
ds = driver.Open( filename, 0 )
if ds is None:
print "Unable to open %s", filename
sys.exit( -1 )
return ds
def printGeometryInfo( g ):
print "... | = ds2.GetLayer()
sr1 = l1.GetSpatialRef()
sr2 = l2.GetSpatialRef()
wkt1 = sr1.ExportToWkt()
wkt2 = sr2.ExportToWkt()
if wkt1 != wkt2:
print "WARNING: Spatial reference systems differ... Unable to compute result"
return 0
geom1_type = l1.GetGeomType()
geom2_type = l2.GetGeomType()
| if ( geom1_type == ogr.wkbPolygon ) and ( geom2_type == ogr.wkbPolygon ):
out_driver = ogr.GetDriverByName( "ESRI Shapefile" )
# Remove the output shapefile if it already exists
if os.path.exists( argv[2] ):
try:
out_driver.DeleteDataSource( argv[2] )
except:
print sys.stderr, ... |
pozdnyakov/chromium-crosswalk | tools/telemetry/telemetry/core/platform/mac_platform_backend.py | Python | bsd-3-clause | 1,792 | 0.011161 | # Copyright (c) 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.
import os
try:
import resource # pylint: disable=F0401
except ImportError:
resource = None # Not available on all platforms
from telemetry.core.pl... | == 'Pages active':
pages_active = int(value.strip()[:-1]) # Strip trailing '.'
return p | ages_active * resource.getpagesize() / 1024
return 0
def GetMemoryStats(self, pid):
rss_vsz = self._GetPsOutput(['rss', 'vsz'], pid)
if rss_vsz:
rss, vsz = rss_vsz[0].split()
return {'VM': 1024 * int(vsz),
'WorkingSetSize': 1024 * int(rss)}
return {}
def GetOSName(self):
... |
liris-vision/starling | tools/getos.py | Python | gpl-3.0 | 1,475 | 0.007463 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# STARLING PROJECT
#
# LIRIS - Laboratoire d'InfoRmatique en Image et Systèmes d'information
#
# Copyright: 2012 - 2015 Eric Lombardi (eric.lombardi@liris.cnrs.fr), LIRIS (liris.cnrs.fr), CNRS (www.cnrs.fr)
#
#
# This program is free software: you can redistribute it... |
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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 along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further information, check the COPYING file distributed with this software.
#
#---------------... |
droundy/deft | papers/histogram/figs/yaml-comparison.py | Python | gpl-2.0 | 4,167 | 0.011039 | #!/usr/bin/env python
from __future__ import division
import sys, os
import numpy as np
import readnew
from glob import glob
#import re
import yaml
import os.path
import time # Need to wait some time if file is being written
# Example: /home/jordan/sad-monte-carlo/
filename_location = sys.argv[1]
# Example: data/sa... | l_data
data['bins']['histogram'] = np.array(data['bins']['histogram'])
data['bins']['lnw'] = np.array(data['bins']['lnw'])
data['movies']['energy']
minyaml = data['movies']['energy'].index(-Smax)
maxyaml = data['movies']['energy'].index(-Smin)
#print(data['bins']['lnw'])
moves = data['moves'... | ['movies']['entropy'] = np.array(data['movies']['entropy'])
lndos = data['movies']['entropy']
N_save_times = len(data['movies']['entropy'])
ref = reference
if ref[:len('data/')] != 'data/':
ref = 'data/' + ref
maxref = Smax #int(readnew.max_entropy_state(ref))
minref = Smin # int(re... |
andyaguiar/tornado | tornado/concurrent.py | Python | apache-2.0 | 18,212 | 0.000384 | #!/usr/bin/env python
#
# Copyright 2012 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 a... |
_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
sys.version_info >= (3, 4))
class ReturnValueIgnoredError(Exception):
pass
# This class and associated code in the future object is derived
# from the Trollius project, a backport of asyncio to Python 2.x - 3.x
c... | r(object):
"""Helper to log a traceback upon destruction if not cleared.
This solves a nasty problem with Futures and Tasks that have an
exception set: if nobody asks for the exception, the exception is
never logged. This violates the Zen of Python: 'Errors should
never pass silently. Unless expl... |
tensorflow/transform | tensorflow_transform/graph_tools.py | Python | apache-2.0 | 39,030 | 0.005867 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | e is
# resolved.
from tfx_bsl.types import tfx_namedtuple
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import composite_tensor
from tenso | rflow.python.framework import func_graph as tf_func_graph
from tensorflow.python.framework import function_def_to_graph
from tensorflow.python.util import object_identity
# pylint: enable=g-direct-tensorflow-import
_INITIALIZABLE_TABLE_OP_TYPES = [
'CuckooTable',
'CuckooTableV2',
'HashTable',
'HashTabl... |
meliora000/eb_django_app | django_eb/comment/migrations/0002_auto_20151231_1023.py | Python | mit | 930 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-31 01:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migr | ations.Mig | ration):
dependencies = [
('comment', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='comment',
field=models.CharField(max_length=120, null=True),
),
migrations.AlterField(
model_name='comm... |
dobestan/fastblog | fastblog/communications/models/sms.py | Python | mit | 442 | 0.004525 | from django.db import models
from .base import MessageAbstractModel
class SMS(MessageAbstractModel):
cmid = models.TextField()
class Meta:
verbose_name = 'SMS'
verbose_name_plural = verbose_name
def send_message(self, async=True):
from communications.tasks.sms import SendSMSTas... | if asyn | c:
return task.delay(self.id)
return task.run(self.id)
|
hirochachacha/apython | bpython/interpreter.py | Python | mit | 12,791 | 0.00172 | #!/usr/bin/env python
#coding: utf-8
# The MIT License
#
# Copyright (c) 2009-2011 the bpython authors.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | d
if func:
spec = self._get_argspec(func, arg_number)
else:
spec = None
if not spec:
if keyword.iskeyword(line):
spec = inspection.KeySpec([line])
elif self.is_commandline(line) and repl.is_only_word | :
spec = self.get_command_spec(l |
obi-two/Rebelion | data/scripts/templates/object/tangible/furniture/all/shared_frn_all_potted_plants_sml_s03.py | Python | mit | 476 | 0.046218 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PL | EASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/furniture/all/shared_frn_all_potted_plants_sml_s03.iff"
result.attribute_template_id = 6
res | ult.stfName("frn_n","frn_potted_plant_sml_s03")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
AlexMili/WhatInstalled | whatinstalled.py | Python | mit | 1,456 | 0.067995 | import os
import argparse
keywords = {\
"mac":[\
"brew install",\
"brew cask install",\
"port install"\
],\
"linux":[\
"apt-get install",\
"aptitude install",\
"yum install",\
"pacman install",\
"dpkg -i",\
"dnf install",\
"zypper in",\
"make install",\
"tar "\
],\
"lua":[\
"luarocks ins... | lobal keywords
history_file = os.p | ath.expanduser(args.bash_file)
f = open(history_file,"r")
if(args.profile != None and args.profile in keywords):
keywords = {args.profile:keywords[args.profile]}
elif(args.profile != None and args.profile not in keywords):
print("\n[ERROR]Profile doesn't exist\n")
exit(0)
for line in f:
for category in ke... |
bundgus/python-playground | matplotlib-playground/examples/user_interfaces/fourier_demo_wx.py | Python | mit | 8,955 | 0.00067 | #!/usr/bin/env python
import numpy as np
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
import wx
import matplotlib
matplotlib.interactive(False)
matplotli... | x.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5)
| self.SetSizer(sizer)
class FourierDemoWindow(wx.Window, Knob):
def __init__(self, *args, **kwargs):
wx.Window.__init__(self, *args, **kwargs)
self.lines = []
self.figure = Figure()
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
self.canvas.callbacks.connect('button_... |
stuarteberg/lazyflow | tests/testJsonConfig.py | Python | lgpl-3.0 | 7,865 | 0.012587 | ###############################################################################
# lazyflow: data flow based lazy parallel computation framework
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/o... | .int_setting == 42
assert configFields.auto_int_setting == 4 | 2
assert configFields.another_auto_int_setting == 43
assert configFields.bool_setting is True
assert configFields.formatted_setting.format( user_name="Stuart", user_home_town="Washington, DC" ) == "Greetings, Stuart from Washington, DC!"
assert configFields.roi_setting == ((1,2,3,4,5), (... |
owatte/thecaribfos | apps/thedirectory/migrations/0004_auto_20150529_1416.py | Python | gpl-3.0 | 616 | 0.008117 | # -*- coding: utf-8 -*-
from __ | future__ import unicode_literals
from django.db import models, migrations
#import tagging_autocomplete.models
import datetime
class Migration(migrations.Migration):
dependencies = [
('thedirectory', '000 | 3_auto_20150525_1515'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='tags',
#field=tagging_autocomplete.models.TagAutocompleteField(max_length=255, blank=True),
field=models.CharField(default=datetime.datetime(2015, 5, 25, 17, 23, 6, ... |
ColinIanKing/autotest | client/shared/xml_utils_unittest.py | Python | gpl-2.0 | 12,510 | 0.002878 | #!/usr/bin/python
import unittest, tempfile, os, glob, logging
try:
import autotest.common as common
except ImportError:
import common
from autotest.client.shared import xml_utils, ElementTree
class xml_test_data(unittest.TestCase):
def get_tmp_files(self, prefix, sufix):
path_string = os.path... | pology><secmodel><model>selinux</model><doi>0</doi>
</secmodel></host><guest><os_type>hvm</os_type><arch name='i686'>
<wordsize>32</wordsize><emulator>$TEST_XML_TEXT_REPLACE</emulator>
<machine>rhel6.2.0</machine><machine canonical='rhel6.2.0'>pc</machine>
<machine>rhel6.1.0</machine><ma... | 5.4.4</machine><machine>rhel5.4.0
</machine><domain type='qemu'></domain><domain type='kvm'><emulator>
/usr/libexec/qemu-kvm</emulator></domain></arch><features><cpuselection
/><deviceboot/><pae/><nonpae/><acpi default='on' toggle='yes'/><apic
default='on' toggle='no'/></features></guest... |
yukioSatoh/ysPyCommon | tests/test_ysPyCommon/__init__.py | Python | mit | 941 | 0.01169 | import unittest, tempfile, uuid, os, shutil, sys
class Test_CreateRemoveTempLocation(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs)
self._tmpTestFolder = None
def setUp(self):
self._tmpTestFolder = os | .path.join(tempfile.gettempdir(),
"unittest_%s_%s" % (self.__class__.__name__, str( uuid.uuid4() )[:8]))
os.mkdir(self._tmpTestFolder)
sys.path.append(self._tmpTestFolder)
def tearDown(self):
if not self._tmpTestFolder: return
... | %self._tmpTestFolder
shutil.rmtree(self._tmpTestFolder)
self._tmpTestFolder = None
if self._tmpTestFolder in sys.path:
sys.path.remove(self._tmpTestFolder)
|
sgiavasis/nipype | nipype/interfaces/vtkbase.py | Python | bsd-3-clause | 1,997 | 0 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
vtkbase provides some helpers to use VTK through the tvtk package (mayavi)
Code using tvtk should import it through this module
"""
import os
from .. import logging
iflogger = logging.getLogger('inte... | LKIT'] = old_ets
else:
del os.environ['ETS_TOOLKIT']
def vtk_version():
""" Get VTK version """
global _vtk_version
return _vtk_version
def no_vtk():
""" Checks if VTK is installed and the python wrapper is functional """
global _vtk_version
return _vtk_version is None
def no_t... | Checks if tvtk was found """
global _have_tvtk
return not _have_tvtk
def vtk_old():
""" Checks if VTK uses the old-style pipeline (VTK<6.0) """
global _vtk_version
if _vtk_version is None:
raise RuntimeException('VTK is not correctly installed.')
return _vtk_version[0] < 6
def confi... |
LaoZhongGu/kbengine | kbe/src/lib/python/Lib/webbrowser.py | Python | lgpl-3.0 | 21,961 | 0.001229 | #! /usr/bin/env python3
"""Interfaces for launching and remotely controlling Web browsers."""
# Maintained by Georg Brandl.
import io
import os
import shlex
import sys
import stat
import subprocess
import time
__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
class Error(Exception):
pass... | el | if command[0] is not None:
return command[0]()
raise Error("could not locate runnable browser")
# Please note: the following definition hides a builtin function.
# It is recommended one does "import webbrowser" and uses webbrowser.open(url)
# instead of "from webbrowser import *".
def open(url, ne... |
zero-point/hackattack | addField.py | Python | mit | 324 | 0.027778 | from osgeo import ogr
def addField(shapefile,field):
source = ogr.Open(shapefile, 1)
layer = source.GetLayer()
layer_defn = layer.GetLayerDefn()
new_field = ogr.FieldDefn(field, ogr.OFTInte | ger)
layer.CreateField(new_field)
source = None
# addField('A_Roads.shp','example') add the 'example' field to A_Roads sh | apefile
|
xavfernandez/pip | src/pip/__init__.py | Python | mit | 458 | 0 | from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_C | HECK_RUNNING:
from typing import List, Optional
__version__ = "20.0.dev0"
def main(args=None):
# type: (Optional[List[str]]) -> int
"""This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._... | per(args)
|
nortikin/sverchok | ui/nodeview_operators.py | Python | gpl-3.0 | 2,214 | 0.00271 | # This file is part of project Sverchok. It's copyrighted by the contributors
# recorded in the version control history of the file, available from
# its original location https://github.com/nortikin/sverchok/commit/master
#
# SPDX-License-Identifier: GPL3
# License-Filename: LICENSE
import bpy
from sverchok.utils.s... | ster_classes_facto | ry(classes)
|
henriquenogueira/aedes | aedes_server/core/checks.py | Python | mit | 1,051 | 0.001903 | from django.conf import settings
from django.core.checks import Error, register
@register
def check_threshold(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
if not hasattr(settings, 'THRESHOLD'):
errors.append(Error(
'settings must have th... | 0.0005 to your settings.py file',
obj=settings,
id='aedes.e_001'
))
return errors
@register
def check_aws_credentials(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
expected = ('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', ... | errors.append(Error(
'settings must contain AWS credentials',
hint='Add AWS credentials to your settings.py file',
obj=settings,
id='aedes.e_002'
))
return errors
|
back1992/mezzanine-api-docker | web/mykgb/spiders/quandl_data.py | Python | mit | 2,840 | 0.002817 | # -*- coding: utf-8 -*-
import scrapy
import numpy
import quandl
from mykgb import indicator
from myapp.models import Quandlset
from mykgb.items import MykgbItem
quandl.ApiConfig.api_key = "taJyZN8QXqj2Dj8SNr6Z"
quandl.ApiConfig.api_version = '2015-04-09'
class QuandlDataSpider(scrapy.Spider):
name = "quandl_dat... | = {
| 'ITEM_PIPELINES': {
# 'mykgb.pipelines.DestinyPipeline': 100
'mykgb.pipelines.MykgbPipeline': 100
},
'DEFAULT_REQUEST_HEADERS': {
'Referer': 'http://www.baidu.com'
}
}
def parse(self, response):
Quandlset.objects.update(actived=True)
... |
matthewfranglen/spark | examples/src/main/python/ml/anova_test_example.py | Python | mit | 1,926 | 0 | #
# 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 us... | Session\
.builder\
.appName("ANOVATestExample")\
.getOrCreate()
# $example on$
data = [(3.0, Vectors.dense([1.7, 4.4, 7.6, 5.8, 9.6, 2.3])),
(2.0, Vectors.dense([8.8, 7.3, 5.7, 7.3, 2.2, 4.1])),
(1.0, Vectors.dense([1.2, 9.5, 2.5, 3.1, 8.7, 2.5])),
(2... | f = spark.createDataFrame(data, ["label", "features"])
r = ANOVATest.test(df, "features", "label").head()
print("pValues: " + str(r.pValues))
print("degreesOfFreedom: " + str(r.degreesOfFreedom))
print("fValues: " + str(r.fValues))
# $example off$
spark.stop()
|
adhoc-dev/odoo-addons | project_issue_solutions_product/project_issue_solution.py | Python | agpl-3.0 | 403 | 0.024814 | #-*- coding: ut | f-8 -*-
from openerp.osv import fields, osv, orm
class project_isssue_solution(osv.osv):
""" Note """
_inherit = 'project.issue.solution'
_columns = {
'product_ids': fields.many2many('product.product', 'project_issue_solution_product_rel', 'solution_id','product_id', string='Products'),
}
... | :softtabstop=4:shiftwidth=4:
|
google/grr | grr/server/grr_response_server/flows/general/transfer_test.py | Python | apache-2.0 | 49,622 | 0.004816 | #!/usr/bin/env python
"""Test the file transfer mechanism."""
import hashlib
import io
import itertools
import os
import platform
import struct
import unittest
from unittest import mock
from absl import app
from grr_response_core.lib import constants
from grr_response_core.lib import utils
from grr_response_core.lib... | + chunk_size // 2
self._RunAndCheck(chunk_size, download_length)
class CompareFDsMixin(object):
def CompareFDs(self, fd1, fd2):
# Seek the files to the end to make sure they are the same size.
fd2.seek(0, 2)
fd1.seek(0, 2)
self.assertEqual(fd2.tell(), fd1.tell())
ranges = [
# Start... | (fd2.tell() - 100, 300),
# Zero length reads
(100, 0),
]
for offset, length in ranges:
fd1.seek(offset)
data1 = fd1.read(length)
fd2.seek(offset)
data2 = fd2.read(length)
self.assertEqual(data1, data2)
class GetFileFlowTest(CompareFDsMixin, flow_test_lib.FlowTe... |
jossthomas/Enigma-Machine | components/Default_Settings.py | Python | mit | 2,231 | 0.013459 | #Sequences of actual rotors used in WWII, format is name, sequences, turnover notch(es)
rotor_sequences = {
'I': ('EKMFLGDQVZNTOWYHXUSPAIBRCJ', ('Q')),
'II': ('AJDKSIRUXBLHWTMCQGZNPYFVOE', ('E')),
'III': ('BDFHJLCPRTXVZNYEIWGAKMUSQO', ('V')),
'IV': ('ESOVPZJAYQUIRHXLNFTGKDCMWB', ('J')),
'V... | VEUSRKX', ('Q')), #civilian
'IIIC': ('UQNTLSZFMREHDPXKIBVYGJCWOA', ('Q')), #civilian
'BETA': ('LEYJVCNIXWPBQMDRTAKZGFUHOS', None), #Position 4 Only
'GAMMA': ('FSOKANUERHMBTIYCWLQPZXVGJD', None) #Position 4 Only
}
#Simple letter substitutions before the | sequence is sent back through the rotors. Notably a letter cannot be encoded as itself here.
reflector_sequences = {
'A': 'EJMZALYXVBWFCRQUONTSPIKHGD',
'B': 'YRUHQSLDPXNGOKMIEBFZCWVJAT',
'C': 'FVPJIAOYEDRZXWGCTKUQSBNMHL',
'B Thin': 'ENKQAUYWJICOPBLMDXZVFTHRGS',
'C Thin': 'RDOBJNTKVEHMLFCWZAX... |
kennethjiang/donkey | donkeycar/parts/simulations.py | Python | mit | 2,106 | 0.015195 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 25 17:30:28 2017
@author: wroscoe
"""
import numpy as np
import random
class MovingSquareTelemetry:
"""
Generator of cordinates of a bouncing moving square for simulations.
"""
def __init__(self, max_velocity=29,
... | square box.
This can be used to test if a learning algorithm can learn.
"""
def __init__(self, resolution=(120,160), box_size=4, color=(255, 0, 0)):
self.resolution = resolution
self.box_size = box_size
self.color = color
def run(self, x,y, box_size=None, ... | ius = int((box_size or self.box_size)/2)
color = color or self.color
frame = np.zeros(shape=self.resolution + (3,))
frame[y - radius: y + radius,
x - radius: x + radius, :] = color
return frame
|
TalosThoren/python-demo | tests/context.py | Python | mit | 138 | 0.043478 | import os
import sys
sys.path.insert( 0, os.path.abspat | h( '.. ' ) )
from example import list_compare
from example import social_anal | ysis
|
ppericard/matamog | scripts/fasta_length_filter.py | Python | agpl-3.0 | 3,594 | 0.001391 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
fasta_length_filter
Description: Filter a fasta file based on sequence length
fasta_length_filter.py -i input.fa -o output.fa -m 300
fasta_length_filter.py -i input.fa -o output.fa -M 1000
-----------------------------------------------------------------------
... | ranty 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
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
def read_fasta_file_handle(fasta_file_handle... | ariables initialization
header = ''
seqlines = list()
sequence_nb = 0
# Reading input file
for line in fasta_file_handle:
if line[0] == '>':
# Yield the last read header and sequence
if sequence_nb:
yield (header, ''.join(seqlines))
del... |
Silhm/bcf-scribble-strips | OSC-Midi/pythonPgm/main.py | Python | mit | 612 | 0.011438 | """
make everything work together!
"""
import argparse
import subproces | s
from midi2osc import MidiToOSC
from osc2midi import OscToMidi
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", default="127.0.0.1",
help="The ip of the OSC server")
parser.add_argument("--port", type=int, default=8000,
help="The port the OSC serve... | IProc = #OscToMidi(args.ip, args.port)
|
onfire73/pypeskg | ui/pypesvds/lib/extras/pdflib/lzw.py | Python | apache-2.0 | 2,356 | 0.025467 | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:... | == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield ... | err, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debu... |
jaysonsantos/servo | components/script/dom/bindings/codegen/CodegenRust.py | Python | mpl-2.0 | 279,760 | 0.001659 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Common codegen classes.
from collections import defaultdict
from itertools import groupby
import operator
import os
... | duleFromObject,
getTypesFromCallback,
getTypesFromDescriptor,
getTypesFromDictionary,
iteratorNativeType
)
AUTOGENERATED_WARNING_COMMENT = \
"/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
FINALIZE_HOOK_NAME = '_finalize'
TRACE_HOOK_NAM | E = '_trace'
CONSTRUCT_HOOK_NAME = '_constructor'
HASINSTANCE_HOOK_NAME = '_hasInstance'
RUST_KEYWORDS = {"abstract", "alignof", "as", "become", "box", "break", "const", "continue",
"else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in",
"let", "loop", "macro", "m... |
dhuang/incubator-airflow | airflow/migrations/versions/852ae6c715af_add_rendered_task_instance_fields_table.py | Python | apache-2.0 | 2,123 | 0.000471 | #
# 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 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 dis... | ND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Add RenderedTaskInstanceFields table
Revision ID: 852ae6c715af
Revises: a4c2fd67d16b
Create Date: 2020-03-10 22:19:18.034961
"""
import sqlalchemy as sa
from alembic import op
#... |
jlant/playground | python/hello-cookiecutter/python-boilerplate/tests/test_python-boilerplate.py | Python | mit | 438 | 0.002283 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_python-boilerplate
---------- | ------------------------
Tests for `python-boilerplate` module.
"""
import unittest
from python-boilerplate import python-boilerplate
class TestPython-boilerplate(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass |
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.