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 |
|---|---|---|---|---|---|---|---|---|
AndrewPashkin/python-tempo | src/tempo/django/forms.py | Python | bsd-3-clause | 859 | 0 | """Provides Django-Admin form field."""
# coding=utf-8
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field, ValidationError
from tempo.django.widgets import RecurrentEventSetWidget
from tempo.recurrenteventset import RecurrentEventSet
class RecurrentEven | tSetField(Field):
"""Form field, for usage in admin forms.
Represents RecurrentEventSet."""
# pylint: disable=no-init
widget = RecurrentEventSetWidget
def clean(self, value):
"""Cleans and validates RecurrentEventSet expression."""
# pylint: disable=no-self-use
if value is N... | invalid')
return RecurrentEventSet.from_json(value)
|
projectatomic/atomic-reactor | tests/conftest.py | Python | bsd-3-clause | 2,306 | 0.000867 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This | software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals, absolute_import
import json
import pytest
import requests
import requests.exceptions
from tests.constants import LOCALHOST_REGISTRY_HTTP, DOCKER0... | Name
from atomic_reactor.core import ContainerTasker
from atomic_reactor.constants import CONTAINER_DOCKERPY_BUILD_METHOD
from atomic_reactor.inner import DockerBuildWorkflow
from tests.constants import MOCK_SOURCE
if MOCK:
from tests.docker_mock import mock_docker
@pytest.fixture()
def temp_image_name():
re... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/geometry/tests/test_geometry.py | Python | agpl-3.0 | 24,875 | 0.006151 | from sympy import (Abs, C, Dummy, Max, Min, Rational, Float, S, Symbol, cos, oo,
pi, simplify, sqrt, symbols)
from sympy.geometry import (Circle, Curve, Ellipse, GeometryError, Line, Point,
Polygon, Ray, RegularPolygon, Segment, Triangle,
are_si... | ar(p3)
assert Point.is_collinear(p3, p4)
assert Point.is_collinear(p3, p4, p1_1, p1_2)
assert Point.is_collinear(p3, p4, p1_1, p1_3) == False
x_pos = Symbol('x', real=True, positive=True)
p2_1 = Point(x_pos, 0)
p2_2 = Point(0, x_pos | )
p2_3 = Point(-x_pos, 0)
p2_4 = Point(0, -x_pos)
p2_5 = Point(x_pos, 5)
assert Point.is_concyclic(p2_1)
assert Point.is_concyclic(p2_1, p2_2)
assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_5) == False
def test_line():
p1 = Point(0, 0)
... |
CoderBotOrg/coderbotsrv | server/lib/cryptography/hazmat/backends/openssl/backend.py | Python | gpl-3.0 | 38,174 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import collections
import itertools
import warnings
from contextlib impor... | penSSLSerializationBackend, X509Backend
)
from cryptography.hazmat.backends.openssl.ciphers import (
_AESCTRCipherContext, _CipherContext
)
from cryptography.hazmat.backends.openssl.cmac import _CMACContext
from cryptography.hazmat.backends.openssl.dsa import (
_DSAParameters, _DSAPrivateKey, _DSAPublicKey
)
fr... | backends.openssl.hashes import _HashContext
from cryptography.hazmat.backends.openssl.hmac import _HMACContext
from cryptography.hazmat.backends.openssl.rsa import (
_RSAPrivateKey, _RSAPublicKey
)
from cryptography.hazmat.backends.openssl.x509 import _Certificate
from cryptography.hazmat.bindings.openssl.binding i... |
pipian/libcueify | tests/swig/check_full_toc.py | Python | mit | 8,463 | 0.002363 | # check_full_toc.py - Unit tests for SWIG-based libcueify full TOC APIs
#
# Copyright (c) 2011 Ian Jacobi <pipian@pipian.com>
#
# 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
# rest... | 0, 13, 0, 0))
serialized_mock_full_toc.extend(
TRACK_DESCRIPTOR(2, 1, 6, 0xA2, 0, 0, 0, 57, 35, 13))
serialized_mock_full_toc.extend(
TRACK_DESCRIPTOR(2, 1, 6, 13, 1, 2, 3, 54, 16, 26))
class TestFullTOCFunctions(unittest.TestCase):
def test_serialization(self):
# Test both deserialization and seri... | full_toc = cueify.FullTOC()
self.assertTrue(
full_toc.deserialize(
struct.pack(
"B" * len(serialized_mock_full_toc),
*serialized_mock_full_toc)))
s = full_toc.serialize()
self.assertEqual(full_toc.errorCode, cueify.OK)
... |
rsalmaso/wagtail | wagtail/core/migrations/0017_change_edit_page_permission_description.py | Python | bsd-3-clause | 771 | 0 | # -*- coding: utf-8 - | *-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0016_change_page_url_path_to_text_field"),
]
operations = [
migrations.AlterField(
model_name="grouppagepe | rmission",
name="permission_type",
field=models.CharField(
choices=[
("add", "Add/edit pages you own"),
("edit", "Edit any page"),
("publish", "Publish any page"),
("lock", "Lock/unlock any page"),
... |
chris-schmitz/circuit-python-acrylic-nightlight | code/code.py | Python | mit | 1,177 | 0.002549 | from digitalio import DigitalInOut, Direction, Pull
import board
import time
import neopixel
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT
pixelPin = board.D2
pixelNumber = 8
strip = neopixel.NeoPixel(pixelPin, pixelNumber, brightness=1, auto_write=False)
switch = DigitalInOut(board.D1)
switch.dire... | t(255 - pos * 3), 0, int(pos * 3))
else:
pos -= 170
return (0, int(pos * 3), int(255 - pos * 3))
def rainbow_cycle(wait):
for outer in range(255):
for inner in range(len(strip)):
index = int((inner * 256 / len(strip)) + outer)
strip[inner] = wheel(index & 255)
... | te()
time.sleep(wait)
while True:
if switch.value:
led.value = False
strip.fill((0, 0, 0))
strip.write()
else:
led.value = True
# strip.fill((255, 0, 0))
rainbow_cycle(0.001)
# time.sleep(0.01) |
ToonTownInfiniteRepo/ToontownInfinite | toontown/minigame/TargetGameGlobals.py | Python | mit | 7,031 | 0.001991 | from pandac.PandaModules import *
from toontown.toonbase import TTLocalizer
from toontown.toonbase import ToontownGlobals
ENDLESS_GAME = config.GetBool('endless-ring-game', 0)
NUM_RING_GROUPS = 16
MAX_TOONXZ = 15.0
MAX_LAT = 5
MAX_FIELD_SPAN = 135
CollisionRadius = 1.5
CollideMask = ToontownGlobals.CatchGameBitmask
TAR... | 1],
8,
2],
ToontownGlobals.MinniesMelodyland: [[6,
4,
2,
0],
[12,
... | [28,
12,
6,
3.0],
[colorGreen,
colorBlue,
colorYellow,
... |
SkyZH/CloudOJWatcher | ojrunnerlinux.py | Python | gpl-3.0 | 1,643 | 0.009738 | import lorun
import os
import codecs
import random
import subprocess
import config
import sys
RESULT_MAP = [
2, 10, 5, 4, 3, 6, 11, 7, 12
]
class Runner:
def __init__(self):
return
def compile(self, judger, srcPath, outPath):
cmd = config.langCompile[judger.lang] % {'root': sys.path[0], '... | rst['result'] == 0:
fans = open(ansFile, 'rU')
fout = open(fout_path, 'rU')
crst = lorun.check(fans.fileno(), fout.fileno())
fout.close()
fans.close()
return | (RESULT_MAP[crst], int(rst['memoryused']), int(rst['timeused']))
return (RESULT_MAP[rst['result']], 0, 0)
|
masroore/pynewscred | pynewscred/req_parser.py | Python | bsd-3-clause | 7,407 | 0.00027 | __author__ = 'Dr. Masroor Ehsan'
__email__ = 'masroore@gmail.com'
__copyright__ = 'Copyright 2013, Dr. Masroor Ehsan'
__license__ = 'BSD'
__version__ = '0.1.1'
from datetime import datetime
try:
from lxml import etree
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree... | ('owner', srcNode, source_dict)
_find_and_set('guid', srcNode, source_dict)
_find_and_set('is_blog', srcNode, source_dict, bool)
_find_and_set('thumbnail', srcNode, source_dict)
| _find_and_set('description', srcNode, source_dict)
mediaNode = srcNode.find('media_type')
media_dict = {}
_find_and_set('name', mediaNode, media_dict)
_find_and_set('dashed_name', mediaNode, media_dict)
if len(media_dict) > 0:
source_dict['media_type'] = media_dict
if len(source_dic... |
nelhage/taktician | python/tak/ptn/ptn.py | Python | mit | 2,895 | 0.018307 | import tak
from . import tps
import attr
import re
@attr.s
class PTN(object):
tags = attr.ib()
moves = attr.ib()
@classmethod
def parse(cls, text):
head, tail = text.split("\n\n", 1)
tags_ = re.findall(r'^\[(\w+) "([^"]+)"\]$', head, re.M)
tags = dict(tags_)
tail = re.sub(r'{[^}]+}', ' ', ... | not m:
raise BadMove(move, "malformed move")
stone, pickup, file, rank, d | ir, drops = m.groups()
x = ord(file) - ord('a')
y = ord(rank) - ord('1')
if pickup and not dir:
raise BadMove(move, "pick up but no direction")
typ = None
if dir:
typ = slide_map[dir]
else:
typ = place_map[stone]
slides = None
if drops:
slides = tuple(ord(c) - ord('0') for c in drops... |
rob-metalinkage/django-gazetteer | gazetteer/fixtures/mapstory_tm_world_config.py | Python | cc0-1.0 | 2,139 | 0.02618 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# do this when > 1.6!!!
# from django.db import migrations, models
from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldConfig
from skosxl.models import Concept, Scheme, MapRelation
from gazetteer.settings imp... | ion':"Populated place"} , scheme = sch)
except:
pass
# now set up cross references from NGA feature types namespace
# now set up harvest config
def | load_ft_mappings() :
pass
def load_config() :
try:
GazSourceConfig.objects.filter(name="TM_WorldBoundaries").delete()
except:
pass
config=GazSourceConfig.objects.create(lat_field="lat", name="TM_WorldBoundaries", long_field="lon")
NameFieldConfig.objects.create(config=config,langua... |
asedunov/intellij-community | python/testData/breadcrumbs/dictKey.py | Python | apache-2.0 | 25 | 0.04 | a = {"abc": "d<caret>ef | "} | |
akeeton/MTGO-scry-bug-test | MTGO-scry-bug-test.sikuli/MTGO-scry-bug-test.py | Python | mit | 5,599 | 0.008573 | # Make your image, region, and location changes then change the from-import
# to match.
from configurables_akeeton_desktop import *
import hashlib
import java.awt.Toolkit
import json
import os
import shutil
import time
Settings.ActionLogs = True
Settings.InfoLogs = True
Settings.DebugLogs = True
Set... | o_bottom_capture, card_sent_to_bottom_capture_dest_path)
shutil.move(card_drawn_capture, card_drawn_capture_dest_path)
card_hash_to_capture[1][card_sent_to_bottom_hash] = card_sent_to_bottom_capture_dest_path |
card_hash_to_capture[1][card_drawn_hash] = card_drawn_capture_dest_path
with open(os.path.join(ATTEMPT_NUM_PATH, 'stats.json'), 'w') as stats_file:
json.dump(card_hash_to_times_card_sent_to_bottom_and_drawn, stats_file, sort_keys=True, indent=4)
stats_file.write('\n')
... |
nanoscopy/afm-calibrator | nanoscopy/audio.py | Python | mit | 2,692 | 0.015602 | import pyaudio
import struct
from threading import Thread, Condition
import time
from logging import thread
import socket
CHUNK = 2**12
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
class AudioReader(Thread):
def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999):
Thread._... | data) / 2
fmt = "%dh" % (count)
| shorts = struct.unpack(fmt, data)
buf.extend(shorts)
if len(buf)>=CHUNK*2:
for l in self.listeners:
l(buf)
buf=[]
else:
for l in self.listeners:
l(data)
... |
tweepy/tweepy | tweepy/mixins.py | Python | mit | 949 | 0.001054 | # Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.
from collections.abc import Mapping
class EqualityComparableID:
__slots__ = ()
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
| return NotImplemented
class HashableID(EqualityComparableID):
__slots__ = ()
def __hash__(self):
return self.id
class DataMappi | ng(Mapping):
__slots__ = ()
def __contains__(self, item):
return item in self.data
def __getattr__(self, name):
try:
return self.data[name]
except KeyError:
raise AttributeError from None
def __getitem__(self, key):
try:
return getat... |
bvillasen/phyGPU | tools/tools.py | Python | gpl-3.0 | 1,660 | 0.037349 | import sys, os
def timeSplit( ETR ):
h = int(ETR/3600)
m = int(ETR - 3600*h)/60
s = int(ETR - 3600*h - 60*m)
return h, m, s
def printProgress( current, total, deltaIter, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsStri... | ETRstring = " ETR= {0}:{1:02}:{2:02} ".format(hours, minutes, seconds)
if deltaTime < 0.0001: ETRstring = " ETR= "
terminalString += dotsString + percentString + ETRstring
sys. | stdout. write(terminalString)
sys.stdout.flush()
def printProgressTime( current, total, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsString = "[" + nDots*"." + (20-nDots)*" " + "]"
percentString = "{0:.0f}%".format(percent)... |
warwick-one-metre/opsd | warwick/observatory/operations/dome/astrohaven/__init__.py | Python | gpl-3.0 | 4,416 | 0.001812 | #
# This file is part of opsd.
#
# opsd 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.
#
# opsd is distributed in the hope that it wil... | timeout when opening or closing the dome (takes up to ~80 seconds for the onemetre dome)
self._movement_timeout = dome_config | _json['movement_timeout']
# Timeout period (seconds) for the dome controller
# The dome heartbeat is pinged once per LOOP_DELAY when the dome is under
# automatic control and is fully open or fully closed. This timeout should
# be large enough to account for the time it takes to open a... |
rslnautic/practica-verificacion | src/tweet_crawler.py | Python | apache-2.0 | 1,614 | 0.004337 | """Twitter crawler script"""
import tweepy
from database import MongoDB
class Twitter(object): # pylint: disable=too-few-public-methods
"""Class Twitter"""
def __init__(self):
self.consumer_key = "40GvlhlFPNbVGkZnPncPH8DgB"
self.consumer_secret = "G595ceskX8iVH34rsuLSqpFROL0brp8ezzZR2dGvTKv... | sert({"tweet": tweet})
# Returns the *count* numbers of tweets of your timeline and save it into a database
def _user_timeline(self, count=200):
tweets = []
public_tweets = self.api | .user_timeline(id=self.auth.get_username(), count=count)
for tweet in public_tweets:
text = tweet.text
tweets.append(text)
return tweets
if __name__ == '__main__':
twepp = Twitter()
twepp.print_tweets(10)
twepp.save_tweets(10) |
IanLewis/kay | kay/management/preparse.py | Python | bsd-3-clause | 3,612 | 0.013566 | # -*- coding: utf-8 -*-
"""
Kay preparse management command.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
| All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
from os import listdir, path, mkdir
from werkzeug.utils import import_string
import kay
import kay.app
from kay.utils import local
from kay.utils.jinja2utils.compiler import compile_dir
from kay.manag | ement.utils import print_status
IGNORE_FILENAMES = {
'kay': ('debug', 'app_template'),
'app': ('kay'),
}
def find_template_dir(target_path, ignore_filenames):
ret = []
for filename in listdir(target_path):
target_fullpath = path.join(target_path, filename)
if path.isdir(target_fullpath):
if fi... |
HeyIamJames/Data_Structures | stack.py | Python | gpl-2.0 | 248 | 0.008065 | from linked_list import LinkedList
class Stack(o | bject):
def __init__(self, iterable=None):
self._list = LinkedList(iterable)
def push(self, | val):
self._list.insert(val)
def pop(self):
return self._list.pop()
|
apmckinlay/csuneido | vs2019scintilla/scripts/Dependencies.py | Python | gpl-2.0 | 5,533 | 0.023857 | #!/usr/bin/env python
# Dependencies.py - discover, read, and write dependencies file for make.
# The format like the output from "g++ -MM" which produces a
# list of header (.h) files used by source files (.cxx).
# As a module, provides
# FindPathToHeader(header, includePath) -> path
# FindHeadersInFile(filePath... | sed when one source file is used to create two object files with different
preprocessor definitions. """
result = []
for dep in dependencies:
result.append(dep)
if (dep[0] == current):
depAdd = [additional, dep | [1]]
result.append(depAdd)
return result
def ExtractDependencies(input):
""" Create a list of dependencies from input list of lines
Each element contains the name of the object and a list of
files that it depends on.
Dependencies that contain "/usr/" are removed as they are system headers. """
deps... |
c0710204/edx-platform | common/lib/xmodule/xmodule/imageannotation_module.py | Python | agpl-3.0 | 7,154 | 0.002935 | """
Module for Image annotations using annotator.
"""
from lxml import etree
from pkg_resources import resource_string
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from xblock.core import Scope, String
from xmodule.annotator_mixin import get_instructions, html_to_text
from xmodule.... | s them as a string, otherwise None. """
return get_instructions(xmltree)
def student_view(self, context):
""" Renders parameters | to template. """
context = {
'display_name': self.display_name_with_default,
'instructions_html': self.instructions,
'token': retrieve_token(self.user_email, self.annotation_token_secret),
'tag': self.instructor_tags,
'openseadragonjson': self.opensea... |
Senbjorn/mipt_lab_2016 | lab_19/task_H.py | Python | gpl-3.0 | 1,281 | 0.042155 | #task_H
def dijkstra(start, graph):
n = len(graph)
D = [None] * n
D[start] = 0
index = 0
Q = [sta | rt]
while index < len(Q):
v = Q[index]
index += 1
for u in graph[v]:
if D[u] == None or D[v] + min(graph[v][u]) < D[u]:
D[u] = D[v] + min(graph[v][u])
Q.append(u)
return D
def reverse(graph):
n = len(graph)
graph_reversed = {x: {} for x, y in zip(range(n), range(n))}
for i in range(n):
for v in... | rsed, v, i, w)
def add(graph, a, b, w):
if b in graph[a]:
grph[a][b].append(w)
else:
graph[a][b] = [w]
def min_vertex(x, D, graph):
A = {v: w + D[v] for v, w in zip([u for u in graph[x].keys if D[u] != None], [min(graph[x][u]) for u in graph[x].keys if D[u] != None])}
L = list(A.items)
min_i = L[0][0]
min_v... |
meta-it/misc-addons | attachment_large_object/tests/__init__.py | Python | lgpl-3.0 | 78 | 0 | from . import test_attachment
fast_su | ite = [test_attachment,
| ]
|
dakiri/splunk-app-twitter | twitter2/django/twitter2/views.py | Python | apache-2.0 | 944 | 0.004237 | from .forms import SetupForm
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shor | tcuts import redirect
from splunkdj.decorators.render import render_to
from splunkdj.setup import create_setup_view_context
@login_required
def home(request):
# Redirect to the default view, which happens to be a non-framework view
return redirect('/en-us/app/twitter2/twitter_general')
| @render_to('twitter2:setup.html')
@login_required
def setup(request):
result = create_setup_view_context(
request,
SetupForm,
reverse('twitter2:home'))
# HACK: Workaround DVPL-4647 (Splunk 6.1 and below):
# Refresh current app's state so that non-framework views
# ... |
illume/numpy3k | numpy/testing/decorators.py | Python | bsd-3-clause | 9,735 | 0.003287 | """Decorators for labeling test objects
Decorators that merely return a modified version of the original
function object are straightforward. Decorators that return a new
function object need to use
nose.tools.make_decorator(original_function)(decorator) in returning
the decorator, in order to preserve metadata such ... | l_condition()
else:
fail_val = lambda : fail_condition
def knownfail_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
from noseclasses import KnownFailureTest
def knownfailer(*... | tor(f)(knownfailer)
return knownfail_decorator
# The following two classes are copied from python 2.6 warnings module (context
# manager)
class WarningMessage(object):
"""Holds the result of a single showwarning() call."""
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
... |
aronsky/home-assistant | tests/components/advantage_air/test_sensor.py | Python | apache-2.0 | 4,781 | 0.000627 | """Test the Advantage Air Sensor Platform."""
from datetime import timedelta
from json import loads
from homeassistant.components. | advantage_air.const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from homeassistant.components.advantage_air.sensor import (
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
ADVANTAGE_AIR_SET_COUNTDOWN_VALUE,
)
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import ATTR_ENTITY_ID
from hom... | ime_changed
from tests.components.advantage_air import (
TEST_SET_RESPONSE,
TEST_SET_URL,
TEST_SYSTEM_DATA,
TEST_SYSTEM_URL,
add_mock_config,
)
async def test_sensor_platform(hass, aioclient_mock):
"""Test sensor platform."""
aioclient_mock.get(
TEST_SYSTEM_URL,
text=TEST_... |
MostlyOpen/odoo_addons | myo_survey/wizard/__init__.py | Python | agpl-3.0 | 936 | 0 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... | our option) any later version.
#
# This program is distributed in the hope that it will be usef | ul,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# 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.... |
approvals/ApprovalTests.Python | approvaltests/reporters/generic_diff_reporter.py | Python | apache-2.0 | 2,752 | 0.00109 | import subprocess
from typing import List, Optional
from approvaltests import ensure_file_exists
from approvaltests.command import Command
from approvaltests.core.reporter import Reporter
from approvaltests.utils import to_json
PROGRAM_FILES = "{ProgramFiles}"
class GenericDiffReporterConfig:
def __init__(self,... | elf.name = config.name
self.path = self.expand_program_files(config.path)
self.extra_args = config.extra_args
def __str__(self) -> str:
if self.extra_args:
config = {
"name": self.name,
| "path": self.path,
"arguments": self.extra_args,
}
else:
config = {"name": self.name, "path": self.path}
return to_json(config)
@staticmethod
def run_command(command_array):
subprocess.Popen(command_array)
def get_command(self, received:... |
jeblair/GitPython | git/objects/commit.py | Python | bsd-3-clause | 20,799 | 0.002164 | # commit.py
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
from gitdb import IStream
from git.util import (
hex_to_bin,
Actor,
Iterable,
Stats,
... | iter_items(cls, repo, rev, paths='', **kwargs):
"""Find all commits matching the given criteria.
:param repo: is the Repo
:param rev: revision specifier, see git-rev-parse for viable options
:param paths:
is an optional path or list of paths, if set only Commits that include... | ist where
``max_count`` is the maximum number of commits to fetch
``skip`` is the number of commits to skip
``since`` all commits since i.e. '1970-01-01'
:return: iterator yielding Commit items"""
if 'pretty' in kwargs:
raise ValueError("--pretty cannot be... |
NickyChan/NBASchedule | main.py | Python | gpl-3.0 | 7,776 | 0.010973 | # -*- coding: utf-8 -*-
# 中文对齐不能用python自带的函数,需要自己根据中文长度增/减空格
# Python 2.7.12 & matplotlib 2.0.0
import re
from urllib2 import *
import matplotlib.pyplot as plt
#Get a set of records from nba.hupu.com due to given team
def getDataSet(team):
statUserAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (K... | record.Load(statRecord, countGame)
if record.done == True:
results.append(record.scoreDiff)
if record.result == '胜':
countWin += 1
else:
countLose += 1
record.Print()
... | m])
record.Load(statRecord, countGame)
if streak == '':
streak = record.result
streakCount = 1
continue
if record.result == streak:
streakCount += 1
else:
b... |
mpolednik/reddit-button-hue | app/discovery/bridges.py | Python | mit | 649 | 0 | import threading
import upnp
import nupnp
class DiscoveryThread(threading.Thread):
| def __init__(self, bridges):
super(DiscoveryThread, self).__init__()
self.bridges = bri | dges
self.upnp_thread = upnp.UPnPDiscoveryThread(self.bridges)
self.nupnp_thread = nupnp.NUPnPDiscoveryThread(self.bridges)
def run(self):
self.upnp_thread.start()
self.nupnp_thread.start()
self.upnp_thread.join()
self.nupnp_thread.join()
def discover():
bridg... |
kohr-h/odl | odl/contrib/solvers/functional/__init__.py | Python | mpl-2.0 | 416 | 0 | # Copyright 2014-2017 The ODL contributors
#
# This file is part of ODL.
#
# 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 https://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
__all__ = ()
from .nonl | ocalmeans_functionals import *
__all__ += nonlocalmeans_functionals.__all__
|
AhmedHani/Python-Neural-Networks-API | OptimizationAlgorithms/RPROP.py | Python | mit | 310 | 0.003226 | __author__ = | 'Ahmed Hani Ibrahim'
from LearningAlgorithm import *
class RPROP(LearningAlgorithm):
def learn(self, learningRate, input, output, network):
"""
:param learningRate:
:param input:
:param output:
| :param network:
:return:
"""
pass |
h2oloopan/easymerge | EasyMerge/tests/reddit/r2/r2/controllers/promotecontroller.py | Python | mit | 34,376 | 0.000698 | # The contents of this file are subject to the Common Public Attribution
# License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, ... | def GET_edit_promo(self, link):
if not link or link.promoted is None:
return self.abort404()
rendered = wrap_links(link, skip=False)
form = PromoteLinkForm(link, rendered)
page = Reddit(title=_("edit sponsored link"), content=form,
show_sidebar=False, e... | oCampaign('campaign'))
def GET_edit_promo_campaign(self, campaign):
if not campaign:
return self.abort404()
link = Link._byID(campaign.link_id)
return self.redirect(promote.promo_edit_url(link))
@validate(VSponsorAdmin(),
link=VLink("link"),
campa... |
mtrgroup/django-mtr-utils | mtr/utils/urls.py | Python | mit | 186 | 0 | from django.conf.urls import patterns, url
urlpatterns = patterns(
'mtr.utils.views',
url(r'^model/(?P<nam | e>.+)/pk/(?P<pk>\d+)$',
'model_label', name='model_label | ')
)
|
begea/X-Serv-14.5-Sumador-Simple | check.py | Python | gpl-3.0 | 1,680 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script de comprobación de entrega de ejercicio
Para ejecutarlo, desde la shell:
$ python check.py login_github
"""
import os
import random
import sys
ejercicio = 'X-Serv-14.5-Sumador-Simple'
student_files = [
'servidor-sumador.py'
]
repo_files = [
'check... | rror: " + filename + " no encontrado en el repositorio."
if not error:
print "Parece que la entrega se ha realizado bien."
print
print "La salida de pep8 es: (si todo va bien, no ha de mostrar nada)"
print
for filename in student_files:
if filename | in github_file_list:
os.system('pep8 --repeat --show-source --statistics /tmp/'
+ aleatorio + '/' + filename)
else:
print "Fichero " + filename + " no encontrado en el repositorio."
print
|
Gandi/pyramid_kvs | setup.py | Python | gpl-2.0 | 1,633 | 0.000612 | import os
import re
import sys
from setuptools import setup, find_packages
PY3 = sys.version_info[0] == 3
here = os.path.abspath(os.path.dirname(__file__))
name = 'pyramid_kvs'
with open(os.path.join(here, 'README.rst')) as readme:
README = readme.read()
with open(os.path.join(here, 'CHANGES.rst')) as changes:
... | append('python3-memcached')
else:
requires.append('python-memcached')
tests_require = ['nose', 'coverage']
if sys.version_info < (2, 7):
tests_require += ['unittest2']
extras_require = {'test': tests_require}
setup(name=name.replace('_', '-'),
version=version,
description='Session and cache for ... | "Programming Language :: Python",
"Framework :: Pyramid",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"License :: OSI Approved :: GNU General Public License v2 (GPLv2)",
],
author='Gandi',
author_email='feedback@gandi.net',
url... |
udbhav/kishore | kishore/tests/music.py | Python | mit | 2,056 | 0.002432 | from django.core.urlresolvers import reverse
from kishore.models import Artist, Song, Release
from base import KishoreTestCase
class ArtistTestCase(KishoreTestCase):
def test_index(self):
resp = self.client.get(reverse('kishore_artists_index'))
self.assertEqual(resp.status_code, 200)
def test... | with self.settings(KISHORE_AUDIO_PLAYER="kishore.models.SoundcloudPlayer"):
r = Release.objects.get(pk=1)
self.assertTrue(r.get_player_html())
# try non-streamable
r | = Release.objects.get(pk=2)
self.assertFalse(r.get_player_html())
|
msegado/edx-platform | lms/djangoapps/monitoring/__init__.py | Python | agpl-3.0 | 41 | 0 | """
LMS speci | fic monitoring helpers.
"""
| |
etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/_pyinstaller_hooks_contrib/hooks/rthooks/pyi_rth_enchant.py | Python | gpl-3.0 | 968 | 0.004132 | #-----------------------------------------------------------------------------
# Copyright (c) 2005-2020, PyInstaller Development Team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# The full license is in the file COPYING.txt, ... | -----------------------
import os
import sys
# On Mac OS X tell enchant library where to look for enchant backends (aspell, myspell, ...).
# Enchant is looking for backends in directory 'PREFIX/lib/enchant'
# Note: env. var. ENCHANT_PREFIX_DIR is implemented only in the development version:
# https://github.com/Ab... | hub.com/AbiWord/enchant/pull/2
# TODO Test this rthook.
if sys.platform.startswith('darwin'):
os.environ['ENCHANT_PREFIX_DIR'] = os.path.join(sys._MEIPASS, 'enchant')
|
intel-analytics/analytics-zoo | pyzoo/zoo/chronos/autots/model/auto_seq2seq.py | Python | apache-2.0 | 4,638 | 0.002803 | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | im: LSTM hidden channel for decoder and encoder.
hp.grid_search([32, 64, 128])
:param lstm_layer_num: LSTM la | yer number for decoder and encoder.
e.g. hp.randint(1, 4)
:param dropout: float or hp sampling function from a float space. Learning rate. Dropout
rate. e.g. hp.uniform(0.1, 0.3)
:param teacher_forcing: If use teacher forcing in training. e.g. hp.choice([True, False])
... |
GadgeurX/NetworkLiberator | Daemon/Utils.py | Python | gpl-3.0 | 1,119 | 0.007149 | import netifaces
from netaddr import *
for inter in netifaces.interfaces():
addrs = netifaces.ifaddresses(inter)
try:
print(addrs)
print(addrs[netifaces.AF_INET][0]["addr"])
print(addrs[netifaces.AF_INET][0]["broadcast"])
print(addrs[netifaces.AF_INET][0]["netmask"])
loc... | ixlen)).iter_hosts():
ips.append(str(ip))
except:
print("Error")
def get_lan_ip():
global local_ip
return local_ip
def get_broadcast_ip():
global broadcast
return broadcast
def get_all_ | ips():
global ips
return ips
def get_gateway():
global gateway
return gateway
def get_mac():
global mac
return mac |
DES-SL/EasyLens | easylens/Scripts/des_script.py | Python | mit | 1,168 | 0.006849 | __author__ = 'sibirrer'
#this file is ment to be a shell script to be run with Monch cluster
# set up the scene
from cosmoHammer.util.MpiUtil import MpiPool
import time
import sys
import pickle
import dill
start_time = time.time()
#path2load = '/mnt/lnec/sibirrer/input.txt'
path2load = str(sys.argv[1])
f = open(pa... | .isMaster():
f = open(path2dump, 'wb')
pickle.dump(samples, f)
f.close()
end_time = time.time()
print(end_time - start_time, 'total time needed for computation')
print('R | esult saved in:', path2dump)
print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
|
SCM-NV/qmworks-namd | scripts/pyxaid/plot_average_energy.py | Python | mit | 3,318 | 0 | #! /usr/bin/env python
"""
This program plots the average electronic energy during a NAMD simulatons
averaged over several initial conditions.
It plots both the SH and SE population based energies.
Example:
plot_average_energy.py -p . -nstates 26 -nconds 6
Note that the number of states is the same as given in the ... | 5, nstates * 2 + 5, 2))
xs = np.stack(np.loadtxt(f'{inpfile}{j}', usecols=cols)
for j in range(nconds)).transpose()
# Rows = timeframes ; Columns = states ; tensor = initial conditions
xs = xs.swapaxes(0, 1)
return xs
def read_pops(path, fn, nstates, nconds):
inpfile = os.path.jo... | = tuple(range(3, nstates * 2 + 3, 2))
xs = np.stack(np.loadtxt(f'{inpfile}{j}', usecols=cols)
for j in range(nconds)).transpose()
# Rows = timeframes ; Columns = states ; tensor = initial conditions
xs = xs.swapaxes(0, 1)
return xs
def main(path_output, nstates, nconds):
outs = ... |
nanjj/softlayer-python | SoftLayer/CLI/firewall/detail.py | Python | mit | 1,514 | 0 | """Detail firewall."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import firewall
from SoftLayer.CLI import formatting
from SoftLayer import utils
@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(e... | the firewall
:returns: a formatted table of the firewall rules
"""
table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_mask',
'dest', 'dest_mask'])
table.sortby = '#'
for rule in rules:
table.add_row([
rule['orderValue'],
... | dress'],
rule['destinationPortRangeStart'],
rule['destinationPortRangeEnd']),
utils.lookup(rule, 'destinationIpSubnetMask')])
return table
|
TheIoTLearningInitiative/CodeLabs | Sandbox/Edison_Bluetooth/projects/gardening-system/spp.py | Python | apache-2.0 | 3,138 | 0.015296 | #!/usr/bin/python
# Python modules imports
from optparse import OptionParser, make_option
import pyupm_grove as g
import os, sys, socket, uuid, dbus, dbus.service
import dbus.mainloop.glib
#import gardening_system
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
# Set up consta... | while True:
try:
data = server_sock.recv(1024)
gardening_system.function(data)
if data == 'b':
server_sock.send(gardening_system.requestData())
except soc... | gardening_system.myProgram()
except IOError:
pass
server_sock.close()
print("\nYour device is now disconnected\nPress [ENTER] to continue")
def bluetoothConnection():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
obj = bus.get_object(BUS_NAM... |
thinkl33t/mqtt2telegram | scripts/test.py | Python | lgpl-3.0 | 54 | 0.018519 | #!../venv/bin/python
import sys
print (sys.argv[1 | :])
| |
Osmose/kitsune | kitsune/search/tests/test_search_advanced.py | Python | bsd-3-clause | 31,926 | 0 | import json
from datetime import datetime, timedelta
from django.contrib.contenttypes.models import ContentType
from nose.tools import eq_
from kitsune import search as constants
from kitsune.access.tests import permission
from kitsune.forums.tests import forum, post, restricted_forum, thread
from kitsune.products.t... | def test_num_votes_none(self):
"""Tests num_voted filtering where num_votes is ''"""
q = question(save=True)
questionvote(question=q, save=True)
self.refresh()
qs = {'q': '', 'w': 2, 'a': 1, 'num_voted': 2, 'num_votes': ''}
response = self.client.get(reverse('search.a... | thread(title=u'crash', save=True)
post(thread=thread1, save=True)
self.refresh()
response = self.client.get(reverse('search.advanced'), {
'author': '', 'created': '0', 'created_date': '',
|
paulovn/artifact-manager | lib/artmgr/transport/local.py | Python | gpl-2.0 | 4,422 | 0.015604 | # ********************************************************************** <====
from artmgr.transport.basew import BaseWTransport
# ********************************************************************** ====>
import os
import sys
import errno
import stat
import re
# chunksize for reading/writing local files
CHUNK = ... | ate( self, path ):
"""
Make a folder in the repository, assuming all parent folders exist
"""
os.mkdir( os.path.join(self._basedir,path) )
def folder_list( self, path ):
"""
Return the list of all components (files & folders) in a folder
*This method is optio... | th) )
|
haiy/XF_PRISM | src/XF-Prism/rc_generator.py | Python | gpl-3.0 | 1,587 | 0.028986 | #author :haiyfu
#date:April 14
#description:
#contact:haiyangfu512@gmail.com
"""
This little part is to check how many different values in
a column and store the unqiue values in a list.
For FCBF initially.
The last column is the class .
"""
from sys import argv
#only count the target file and return... | pen(sn)
atrn=len(fin.readline().split(","))
#Initialize the result list
fin.seek(0,0)
rc=[]
rc.append(atrn)
rc.append([])
l=fin.readline().strip("\r \n ").split(",")
for x in l:
rc[1] | .append([x])
count=0
for l in fin:
l=l.strip("\n \r").split(",")
idx=0
if(len(l)<rc[0]):
break
for x in l:
if x not in rc[1][idx]:
rc[1][idx].append(x)
rc[1][idx].sort()
idx=idx+1
count=count+1
#print... |
PAIR-code/lit | lit_nlp/components/scrambler.py | Python | apache-2.0 | 2,899 | 0.00276 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | key in fields_to_scramble]
| new_example = copy.deepcopy(example)
for text_key in text_keys:
new_example[text_key] = self.scramble(example[text_key])
return [new_example]
|
Tigge/platinumshrimp | utils/str_utils.py | Python | mit | 1,370 | 0.00073 | import re
import html
# The regular string.split() only takes a max number of splits,
# but it won't unpack if there aren't enough values.
# This function ensures that we always get the wanted
# number of returned values, even if the string doesn't include
# as many splits values as we want, simply by filling in extra... | (s + ((count - 1 - s.count(sep)) * sep)).split(sep, count - 1)
# Sanitize a s | tring by removing all new lines and extra spaces
def sanitize_string(s):
return " ".join(s.split()).strip()
# Unescape HTML/XML entities
def unescape_entities(text):
def replace_entity(match):
try:
if match.group(1) in html.entities.name2codepoint:
return chr(html.entities.... |
marteinn/The-Big-Username-Blacklist-Python | setup.py | Python | mit | 1,848 | 0.001083 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import re
from setuptools import setup
if sys.argv[-1] == "publish":
os.system("python setup.py sdist upload")
sys.exit()
packages = [
"the_big_username_blacklist"
]
# Handle requirements
install_requires = []
tests_requires... | description="Validate usernames against a black | list", # NOQA
long_description=long_description,
author="Martin Sandström",
author_email="martin@marteinn.se",
url="https://github.com/marteinn/the-big-username-blacklist-python",
packages=packages,
package_data={"": ["LICENSE", ], "the_big_username_blacklist": ["*.txt"]},
package_dir={"the... |
dmccloskey/SBaaS_COBRA | SBaaS_COBRA/stage02_physiology_graphData_execute.py | Python | mit | 4,655 | 0.017401 | #SBaaS
from .stage02_physiology_graphData_io import stage02_physiology_graphData_io
from SBaaS_models.models_COBRA_execute import models_COBRA_execute
from .stage02_physiology_analysis_query import stage02_physiology_analysis_query
#System
import copy
class stage02_physiology_graphData_execute(stage02_physiology_graph... | 'stage02_physiology_simulatedDat | a_query':
weights = self.import_graphWeights_simulatedData(row['simulation_id']);
weights_str = 'stage02_physiology_simulatedData_query';
else:
print('weights source not recognized');
# run the analysis for different algorithms/par... |
aterrel/dynd-python | dynd/ndt/dim_helpers.py | Python | bsd-2-clause | 4,145 | 0.000965 | from __future__ import absolute_import, division, print_function
| from dynd._pydynd import w_type, \
make_var_dim, make_strided_dim, make_fixed_dim, make_cfixed_dim
__all__ = ['var', 'strided', 'fixed', 'cfixed']
class _Dim(object):
__slots__ = []
def __mul__(self, rhs):
if isinstance(rhs, w_type):
# Apply all the dimensions to get
| # produce a type
for dim in reversed(self.dims):
rhs = dim.create(rhs)
return rhs
elif isinstance(rhs, (str, type)):
# Allow:
# ndt.strided * 'int32'
# ndt.strided * int
rhs = w_type(rhs)
for dim in... |
Alphalink/netbox | netbox/tenancy/models.py | Python | apache-2.0 | 1,852 | 0.00216 | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.urls import reverse
from django.utils.encoding import python_2_unicode_compatible
from extras.models import CustomFieldModel, CustomFieldValue
from utilities.models import CreatedUpdatedModel
from utilities.utils im... | cally a customer or an internal
department.
"""
name = models.CharField(max_length=30, unique=True)
slug = models.SlugField(unique=True)
group = models.ForeignKey('TenantGroup', related_name='tenants', blank=True, null=True, on_delete=models.SET_NULL)
description = models.CharField(max_length=10... | ustom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
class Meta:
ordering = ['group', 'name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('tenancy:tenant', args=[self.slug])
def to_c... |
neuroticnerd/armory | armory/phone/lookup.py | Python | apache-2.0 | 2,647 | 0.000756 | # -*- encoding: utf-8 -*-
from __future__ import absolute_import
import requests
import json
import logging
from bs4 import BeautifulSoup as htmldoc
def carrier_lookup():
return None
class CarrierLookup(object):
def __init__(self, number, logname=None):
self.number = number
self._logname =... | s.headers['referer'] = lookup
params = {
'Type': 'lookup',
'PhoneNumber': "{0}".format(self.number),
'VisitorSid': sid,
'CSRF': csrf,
}
log.debug('\nparams: | {0}\n'.format(jsonify(params)))
url = '{0}/functional-demos'.format(host)
r = s.post(url, params=params)
info = json.loads(r.content)
return info
|
simone-campagna/py-configment | src/configment/configment.py | Python | apache-2.0 | 5,069 | 0.001578 | #!/usr/bin/env python
#
# Copyright 2014 Simone Campagna
#
# 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 l... | try:
return self.do_validation(reset=False, throw_on_errors=throw_on_errors)
except: # pylint: disable=bare-except
return False
def impl_load_file(self, filename, throw_on_errors=False):
default_base_dir = Pathname.get_default_base_dir()
Pathname.set_default_base_di... | on_errors)
finally:
Pathname.set_default_base_dir(default_base_dir)
return result
def impl_dump_s(self, stream=None, filename=None, throw_on_errors=False):
default_base_dir = Pathname.get_default_base_dir()
try:
if filename is not None:
base_d... |
tvwenger/millennium-compact-groups | compact_group.py | Python | gpl-3.0 | 5,674 | 0.003877 | """
compact_group.py - Part of millennium-compact-groups package
Defines CompactGroup object to handle information about a single
compact group.
Copyright(C) 2016 by
Trey Wenger; tvwenger@gmail.com
Chris Wiens; cdw9bf@virginia.edu
Kelsey Johnson; kej7a@virginia.edu
GNU General Pub | lic License v3 (GNU GPLv3)
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 Foundatio | n, 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 WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You shoul... |
7sDream/zhihu-oauth | test/test_client_people_badge.py | Python | mit | 762 | 0 | from .test_base_class import ZhihuClientClassTest
PEOPLE_SLUG = 'giantchen'
class TestPeopleBadgeNumber(ZhihuClientClassTest):
| def test_badge_topics_number(self):
self.assertEqual(
len(list(self.client.people(PEOPLE_SLUG).badge.topics)), 2,
)
def test_people_has_badge(self):
self.assertTrue(self.client.people(PEOPLE_SLUG).badge.has_badge)
def test_people_has_identity(self):
self.a | ssertFalse(self.client.people(PEOPLE_SLUG).badge.has_identity)
def test_people_is_best_answerer_or_not(self):
self.assertTrue(self.client.people(PEOPLE_SLUG).badge.is_best_answerer)
def test_people_identify_information(self):
self.assertIsNone(self.client.people(PEOPLE_SLUG).badge.identity)
|
jhnphm/xbs_xbd | python/scripts/test.py | Python | gpl-3.0 | 122 | 0.008197 | #! /b | in/python
import xbh as xbhpkg
xbh = xbhpkg.Xbh()
#xbh.switch_to_app()
xbh.calc_checksum()
print(xbh.get_results())
| |
feroda/django-pro-history | current_user/registration.py | Python | agpl-3.0 | 349 | 0 | class FieldRegistry(object):
| _registry = {}
def add_field(self, model, field):
reg = self.__class__._registry.setdefault(model, [])
reg.append(field)
def get_fields(self, model):
return self.__class__._registry.get(model, [])
def __contains__(self, model):
return model in sel | f.__class__._registry
|
tizz98/cs216 | p11/rand.py | Python | unlicense | 1,083 | 0.025854 | """
Generates 40 random numbers and writes them
to a file. No number is repeated.
~ Created by Elijah Wilson 2014 ~
"""
# used for generating random integers
from random import randint
# open the output file -> "in.data"
f = open("in.data", "w")
# create an empty list
succ = []
# loops through 40 times for gene... | put the random number in the list
succ.append(str(randNum))
# loops through 40 times for writing to file
for x in xrange(0,40):
| # makes sure it isn't the last line to be written
# to write a new line char
if x != 39:
f.write(succ[x] + "\n")
else:
# if it is the last line to be written
# don't write a new line char
f.write(succ[x])
#close the file
f.close() |
jordanemedlock/psychtruths | temboo/core/Library/Box/Files/ZipFile.py | Python | apache-2.0 | 4,646 | 0.005166 | # -*- coding: utf-8 -*-
###############################################################################
#
# ZipFile
# Creates a zipped version of the specified Box file and returns a link to the new compressed file.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License... | """
return self._output.get('Response | ', None)
def get_URL(self):
"""
Retrieve the value for the "URL" output from this Choreo execution. ((string) The url for the newly created zip file.)
"""
return self._output.get('URL', None)
class ZipFileChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, ... |
spatialaudio/python-sounddevice | setup.py | Python | mit | 2,712 | 0 | import os
import platform
from setuptools import setup
# "import" __version__
__version__ = 'unknown'
for line in open('sounddevice.py'):
if line.startswith('__version__'):
exec(line)
break
MACOSX_VERSIONS = '.'.join([
'macosx_10_6_x86_64', # for compatibility with pip < v21
'macosx_10_6_... |
elif system == 'Windows':
| if architecture0 == '32bit':
oses = 'win32'
else:
oses = 'win_amd64'
else:
oses = 'any'
return 'py3', 'none', oses
cmdclass = {'bdist_wheel': bdist_wheel_half_pure}
setup(
name='sounddevice',
version=__vers... |
demonchild2112/travis-test | grr/server/grr_response_server/databases/mysql_foreman_rules.py | Python | apache-2.0 | 1,746 | 0.005727 | #!/usr/bin/env python
"""The MySQL database methods for foreman rule handling."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from grr_response_core.lib import rdfvalue
from grr_response_server import foreman_rules
from grr_response_server.databases im... | """
query = ("INSERT INTO foreman_rules "
" (hunt_id, expiration_time, rule) "
"VALUES (%s, FROM_UNIXTIME(%s), %s) "
"ON DUPLICATE KEY UPDATE "
" expiration_time=FROM_UNIXTIME(%s), rule=%s")
exp_str = mysql_utils.RDFDatetimeToTimestamp(rule.expiration_time)... | str])
@mysql_utils.WithTransaction()
def RemoveForemanRule(self, hunt_id, cursor=None):
query = "DELETE FROM foreman_rules WHERE hunt_id=%s"
cursor.execute(query, [hunt_id])
@mysql_utils.WithTransaction(readonly=True)
def ReadAllForemanRules(self, cursor=None):
cursor.execute("SELECT rule FROM for... |
vivisect/vstruct | vstruct2/bases.py | Python | apache-2.0 | 4,994 | 0.009211 | import traceback
from vstruct2.compat import int2bytes, bytes2int
# This routine was coppied from vivisect to allow vstruct
# to be free from dependencies
MAX_WORD = 16
def initmask(bits):
return (1<<bits)-1
bitmasks = [ initmask(i) for i in range(MAX_WORD*8) ]
def bitmask(value,bits):
return value & bitmasks... | bytes:
self._vs_value = self._prim_parse(self._vs_backbyt | es, self._vs_backoff)
return self._vs_value
def _prim_load(self, fd, offset):
# easy base case...
fd.seek(offset)
byts = fd.read(self._vs_size)
return self._prim_parse(byts, 0)
def vsEmit(self):
return self._prim_emit( self._prim_getval() )
def _prim_norm(... |
crackhopper/TFS-toolbox | tests/core/layer/dropout_test.py | Python | mit | 426 | 0.044601 | import pytest
import tensorflow as tf
import nu | mpy as np
import tfs.core.layer.ops as ops
from tfs.core.layer.dropout import Dropout
from tfs.network import Network
net = Network()
@pytest.fixture
def l():
| l = Dropout(
net,
keep_prob=1.0,
)
return l
class TestDropout:
def test_build_inverse(self,l):
_in = tf.zeros([1,10,10,4])
_out=l.build(_in)
assert _out.get_shape().as_list()==[1,10,10,4]
|
luoxufeiyan/python | Forec/0015/0015.py | Python | mit | 410 | 0.02439 | # c | oding = utf-8
__author__ = 'Forec'
import xlwt
import re
book = xlwt.Workbook(encoding = 'utf-8', style_compression=0)
sheet = book.add_sheet('student',cell_overwrite_ok = True)
line = 0
info = re.compile(r'\"(\d+)\" : \"(.*?)\"')
with open('city.txt',"r") as f:
data = f.read()
for x in info.findall(data):
for... | xls') |
lixiangning888/whole_project | modules/signatures_orginal_20151110/injection_rwx.py | Python | lgpl-3.0 | 1,229 | 0.004068 | # Copyright (C) 2014 Optiv, Inc. (brad.spengler@optiv.com)
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.or | g
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
... | :
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx"... |
mdevaev/slog | src/common.py | Python | gpl-2.0 | 1,483 | 0.002697 | # -*- mode: python; coding: utf-8; -*-
import os
APP_NAME = "SLog"
VERSION = "0.9.4"
WEBSITE = "http://vialinx.org"
LICENSE = """
SLog is a PyGTK-based GUI for the LightLang SL dictionary.
Copyright 2007 Nasyrov Renat <renatn@gmail.com>
This file is part of SLog.
SLog is free software; you can redistribute it and/... | , "slog")
LOGO_ICON = "slog.png"
LOGO_ICON_SPY = "slog_spy.png"
#FTP_LL_URL = "ftp://ftp.lightlang.org.ru/dicts"
FTP_LL_URL = "ftp://etc.edu.ru/pub/soft | /for_linux/lightlang"
FTP_DICTS_URL = FTP_LL_URL + "/dicts"
FTP_REPO_URL = FTP_DICTS_URL + "/repodata/primary.xml"
REPO_FILE = os.path.expanduser("~/.config/slog/primary.xml")
SL_TMP_DIR = "/tmp/sl"
def get_icon(filename):
return os.path.join(PIXMAP_DIR, filename)
|
nttcom/eclcli | eclcli/identity/v3/user.py | Python | apache-2.0 | 15,378 | 0 | # Copyright 2012-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | identity_client = self.app.client_manager.identity
project_id = None
if parsed_args.project:
project_id = common.find_project(identity_client,
parsed_args.project,
parsed_args.project_domain).id
... | id = common.find_domain(identity_client,
parsed_args.domain).id
enabled = True
if parsed_args.disable:
enabled = False
if parsed_args.password_prompt:
parsed_args.password = utils.get_password(self.app.stdin)
try:
... |
jordanemedlock/psychtruths | temboo/core/Library/Zendesk/Search/__init__.py | Python | apache-2.0 | 296 | 0.006757 | from temboo.Library.Zendesk.Search.SearchAll import SearchAll, SearchAllInputSet, SearchAllResultSet, SearchAllChoreographyExecution
from temboo.Library.Zendesk.Search.SearchAnonymous import SearchAnonymous, SearchAnony | mousInputSet, S | earchAnonymousResultSet, SearchAnonymousChoreographyExecution
|
navarro0/racing-all-afternoon | course.py | Python | mit | 3,892 | 0.023124 | import random
## Course texture colors ##
###########################
class Course(object):
def __init__(self, num):
## Default colors, fall back to these
fog = [0,0,0]
light_road = [0,0,0]
dark_road = [0,0,0]
light_offroad = [0,0,0]
dark_offroad = [0 | ,0,0]
light_ | wall = [0,0,0]
dark_wall = [0,0,0]
light_rumble = [0,0,0]
dark_rumble = [0,0,0]
## Course road geometry
self.geometry = [0,0,0,0,0,0,0,0]
last_seg = 0
## Start with a straightaway by default
## Exactly six "segments" are made
for i in range(7):
... |
sssllliang/edx-analytics-pipeline | edx/analytics/tasks/tests/acceptance/test_internal_reporting_user.py | Python | agpl-3.0 | 2,665 | 0.004878 | """
End to end test of the internal reporting user table loading task.
"""
import os
import logging
import datetime
import pandas
from luigi.date_interval import Date
from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase
from edx.analytics.tasks.url import url_path_join
log = logging.getLogger(__nam... | expected_output_csv = os.path.join(self.data_dir, 'output', 'acceptance_expe | cted_d_user.csv')
expected = pandas.read_csv(expected_output_csv, parse_dates=True)
cursor.execute("SELECT * FROM {schema}.d_user".format(schema=self.vertica.schema_name))
response = cursor.fetchall()
d_user = pandas.DataFrame(response, columns=['user_id', 'user_year_of_... |
gangadharkadam/letzerp | erpnext/startup/__init__.py | Python | agpl-3.0 | 986 | 0.002028 | # -*- coding: utf-8 -*-
# ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... | 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, see <http://www.gnu.org/licenses/>.
# default settings that can be made for a user.
from __future__ import unicode_literals
import frappe
# product_name = "ERPNext"
product_name = "let... |
sulantha2006/Processing_Pipeline | Utils/PipelineLogger.py | Python | apache-2.0 | 498 | 0.026104 | __author__ = 'Sulantha'
import logging
class PipelineLogger:
logFunctions={'info':log | ging.info,
'debug':logging.debug,
'warning':logging.warning,
'error':logging.error,
'critical':logging.critical,
'exception':logging.exception}
@staticmethod
def log(moduleName, level, message):
level = level.lower()
... | duleName)
PipelineLogger.logFunctions[level](message)
|
oblique-labs/pyVM | rpython/rlib/test/test_signature.py | Python | mit | 10,192 | 0.005789 | import py
from rpython.rlib.signature import signature, finishsigs, FieldSpec, ClassSpec
from rpython.rlib import types
from rpython.annotator import model
from rpython.rtyper.llannotation import SomePtr
from rpython.annotator.signature import SignatureError
from rpython.translator.translator import TranslationContext,... | hsigs' in str(exc)
def test_any_as_argument():
@signature(types.any(), types.int(), returns=types.float())
def f(x, y):
return x + y
@signature(types.int(), returns=types.float())
def g(x):
re | turn f(x, x)
sig = getsig(g)
assert sig == [model.SomeInteger(), model.SomeFloat()]
@signature(types.float(), returns=types.float())
def g(x):
return f(x, 4)
sig = ge |
jehomez/pymeadmin | prueba_de_inventario.py | Python | gpl-2.0 | 1,191 | 0.004209 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# sin título.py
#
# Copyright 2012 Jesús Hómez <jesus@soneview>
#
# 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 Softwa | re F | oundation; 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 Ge... |
Digital-Preservation-Finland/dpres-siptools | siptools/scripts/create_audiomd.py | Python | lgpl-3.0 | 6,706 | 0 | """Command line tool for creating audioMD metadata."""
from __future__ import unicode_literals, print_function
import os
import sys
import click
import six
import audiomd
from siptools.mdcreator import MetsSectionCreator
from siptools.utils import fix_missing_metadata, scrape_file
click.disable_unicode_literals_war... | dict['codec_quality'])
params['compression'] = audiomd.amd_compression(*compression)
return audiomd.amd_file_data(params)
def _get_audio_info(stream_dict):
"""Creates and returns the audioInfo XML element.
:stream_dict: Metadata dict of a stream
:r | eturns: AudioMD audioInfo element
"""
return audiomd.amd_audio_info(
duration=stream_dict['duration'],
num_channels=stream_dict['num_channels'])
if __name__ == '__main__':
RETVAL = main() # pylint: disable=no-value-for-parameter
sys.exit(RETVAL)
|
jimklo/LearningRegistry | LR/lr/controllers/extract.py | Python | apache-2.0 | 10,398 | 0.009233 | import logging
import StringIO
from iso8601 import parse_date
from datetime import datetime
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from lr.model.base_mode | l import appConfig
from | lr.lib.base import BaseController, render
import json
import ijson
import collections, sys
import math
from urllib2 import urlopen,HTTPError
import lr.lib.helpers as h
log = logging.getLogger(__name__)
import couchdb
class ExtractController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol... |
Korotkin/text_processor_sample | src/plugins.py | Python | gpl-3.0 | 821 | 0.004872 | # -*- coding: utf-8 -*-
__all__ = ("clear_tags", "get_text_from_html", "clear_text")
def clear_tags(obj):
"""
Remove not used blocks, such a | s table of contents, advertisements
"""
SEARCH_TAG = ["div", "table"]
for i in SEARCH_TAG:
res= obj.soup(i)
for row in res:
if row["align"]=="right":
row.clear()
res= obj.soup("title")
if len(res):
res[0].clear()
def join_rows(obj):
"""
... | n
"""
pass
def get_text_from_html(obj):
"""
Return text without html tags
"""
obj.text = obj.soup.get_text()
def clear_text(obj):
"""
Remove special/not used symbols
"""
obj.text = obj.text.replace("\t", "")
|
yangdongsheng/autotest | frontend/tko/models.py | Python | gpl-2.0 | 30,170 | 0.001624 | from django.db import models as dbmodels, connection
from django.utils import datastructures
from autotest.frontend.afe import model_logic, readonly_connection
_quote_name = connection.ops.quote_name
class TempManager(model_logic.ExtendedManager):
_GROUP_COUNT_NAME = 'group_count'
def _get_key_unless_is_func... | t of dicts, where
each dict corresponds to single row and contains a key for each grouped
field as well as all of the extra select fields.
"""
sql, params = self._get_group_query_sql(query, group_by)
cursor = readonly_connection.connection().cursor()
cursor.execute(sql, p... | zip(field_names, row)) for row in cursor.fetchall()]
return row_dicts
def get_count_sql(self, query):
"""
Get the SQL to properly select a per-group count of unique matches for
a grouped query. Returns a tuple (field alias, field SQL)
"""
if query.query.distinct:
... |
tvalacarta/tvalacarta | python/main-classic/channels/ecuadortv.py | Python | gpl-3.0 | 680 | 0.010294 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# tvalacarta - XBMC Plugin
# Canal para ecuador tv
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#------------------------------------------------------------
import os
import sys
import urlparse,re
import urllib
import datet... | tools
from core.item import Item
import youtube_channel
__channel__ = "ecuadortv"
DEBUG = True
YOUTUBE_CHANNEL_ID = "RTVEcuador"
def isGeneric():
return True |
def mainlist(item):
logger.info("tvalacarta.channels.ecuadortv mainlist")
return youtube_channel.playlists(item,YOUTUBE_CHANNEL_ID)
|
zomux/deepy | examples/auto_encoders/recursive_auto_encoder.py | Python | mit | 593 | 0.008432 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging, os
logging.basicConfig(level=logging.INFO)
from deepy.networks import RecursiveAutoEncoder
from deepy.trainers import SGDTrainer, LearningRateAnnealer
from util import get_data, VECTOR_SIZE
model_path = os.path.join(os.path.dirname(__file__), "models", "... | ner(model)
annealer = LearningRateAnnealer()
trainer.run(get_dat | a(), epoch_controllers=[annealer])
model.save_params(model_path)
|
CompassionCH/compassion-modules | crm_compassion/migrations/12.0.1.0.0/pre-migration.py | Python | agpl-3.0 | 409 | 0 | def migrate(cr, version):
if not version:
return
# Replace ids of better_zip by ids of city_zip
cr.execute("""
ALTER TABLE crm_event_compassion
DROP CONSTRAINT crm_event_compassion_zip_id_fkey;
UPDATE crm_event_compassion e
SET | zip_id = (
SELECT id FROM res_city_zip
WHERE openupgrade_legacy_12_0_better_zip_id = e.zip_id)
""")
| |
openstack/nomad | cyborg/tests/unit/api/controllers/v1/test_fpga_program.py | Python | apache-2.0 | 2,179 | 0 | # Copyright 2017 Huawei Technologies Co.,LTD.
# 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
#
# Unl... | rogram_fpga_with_bitstream')
def test_program(self, mock_program, mock_get_dep):
self.headers['X-Roles'] = 'admin'
self.headers['Content-Type'] = 'application/json'
dep_uuid = self.deployable_uuids[0]
fake_dep = fake_deployable.fake_deployable_obj(self.context,
... | alue = fake_dep
mock_program.return_value = None
body = [{"image_uuid": "9a17439a-85d0-4c53-a3d3-0f68a2eac896"}]
response = self.\
patch_json('/accelerators/deployables/%s/program' % dep_uuid,
[{'path': '/program', 'value': body,
'op': '... |
micha-shepher/oervoer-wizard | oervoer/order.py | Python | gpl-3.0 | 2,431 | 0.008638 | '''
Created on Oct 11, 2014
@author: mshepher
'''
from globals import Globals
class Order(object):
EIGENAAR = 0
DIER = 1
GESLACHT = 2
GECASTREERD = 3
AKTIEF = 4
OVERGANGS = 5
GEWICHT = 6 #numerical
PAKKETKG = 7 #float
SOORT = 8
PUP = 9
RAS = 10
def __init__(self,orde... | elf.wei | ght
def get_package(self):
return self.package
def get_kind(self):
return self.kind
def get_owner(self):
return self.owner
def get_animal(self):
return self.animal
def get_ras(self):
return self.ras
def set_result(self, result):
... |
erkarl/browl-api | apps/posts/models.py | Python | mit | 211 | 0 | from django.db import models
from django.contrib.auth.models import User
clas | s Post(models.Model):
title = models.CharField(max_lengt | h=255)
body = models.TextField()
user = models.ForeignKey(User)
|
XianliangJ/collections | ShrewAttack/plotter.py | Python | gpl-3.0 | 1,097 | 0.012762 | import csv
from util.helper import *
import util.plot_defaults
from matplotlib.ticker import MaxNLocator
from pylab import figure
parser = argparse.ArgumentParser()
parser.add_argument('--file', '-f',
help="data file directory",
required=True,
action="store... | ue,
| action="store",
dest="dir")
args = parser.parse_args()
to_plot = []
cong = ['reno', 'cubic', 'vegas']
bursts = ['0.03', '0.05', '0.07', '0.09']
graphfiles = []
for burst in bursts:
for tcptype in cong:
data = read_list(args.file + '/' + tcptype + '-' + burst +'-raw_data.txt')
... |
avocado-framework/avocado-vt | virttest/unittests/test_utils_zchannels.py | Python | gpl-2.0 | 3,733 | 0.00375 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | d_safely_removable_not_first(self):
not_safe = OUT_OK.copy()
not_safe[7] = not_safe[7].replace("11122122", "01021112")
virttest.utils_zchannels.cmd_status_output = mock.Mock(return_value=(0,
"\n".join(not_safe)))
subchannel_p... | s.get_info()
device = subchannel_paths.get_first_unused_and_safely_removable()
self.assertIsNotNone(device)
self.assertEqual("0.0.26ab", device[1])
class TestChannelPaths(unittest.TestCase):
def test__split(self):
chpids = "12345678"
ids = ChannelPaths._split(chpids)
... |
square/pants | tests/python/pants_test/tasks/test_eclipse_integration.py | Python | apache-2.0 | 3,401 | 0.010879 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
from pant... | ets; ideally should test that the build "works"
def test_eclipse_on_protobuf(self):
self._eclipse_test(['exam | ples/src/java/com/pants/examples/protobuf::'])
def test_eclipse_on_jaxb(self):
self._eclipse_test(['examples/src/java/com/pants/examples/jaxb/main'])
def test_eclipse_on_unicode(self):
self._eclipse_test(['testprojects/src/java/com/pants/testproject/unicode::'])
def test_eclipse_on_hello(self):
sel... |
Qwlouse/Findeco | node_storage/validation.py | Python | gpl-3.0 | 1,992 | 0.001011 | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
import re
import unicodedata
h1_start = re.compile(r"^\s*=(?P<title>[^=]+)=*[ \t]*")
valid_title = re.compile(r"[^=]+")
general_heading = re.compile(r"^\s*(={2,6}(?P<title>" + valid_title.pattern +
... | not in short_title_set:
return new_st
def get_heading_matcher(l | evel=0):
if 0 < level < 7:
s = "%d" % level
elif level == 0:
s = "1, 6"
else:
raise ValueError(
"level must be between 1 and 6 or 0, but was %d." % level)
pattern = r"^\s*={%s}(?P<title>[^=§]+)" \
r"(?:§\s*(?P<short_title>[^=§\s][^=§]*))?=*\s*$"
retu... |
SkyLined/headsup | decode/GIF_IMAGE.py | Python | apache-2.0 | 2,315 | 0.019438 | # Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | GE(Structure):
type_name = 'GIF_IMAGE';
def __init__(self, stream, offset, max_size, parent, name):
import C;
from GIF_BLOCK import GIF_BLOCK;
from GIF_COLORTABLE import GIF_COLORTABLE;
from GIF_IMAGE_DESCRIPTOR import GIF_IMAGE_DESCRIPTOR;
from LZW_compressed_data import LZW_compressed_d... |
Structure.__init__(self, stream, offset, max_size, parent, name);
self._descriptor = self.Member(GIF_IMAGE_DESCRIPTOR, 'descriptor');
flags = self._descriptor._Flags;
self._has_local_color_table = flags._LocalColorTable.value == 1;
if self._has_local_color_table:
self._local_colo... |
andrewgolman/Learning_Cards | bot/db/queries.py | Python | gpl-3.0 | 7,726 | 0.001941 | import psycopg2
from db.enums import *
base = psycopg2.connect("dbname='cardkeepersample' user='andrew' host='localhost' password='1234'")
cursor = base.cursor()
# Wrapped queries in alphabetic order
def active_packs(user_id, start=0, count=10):
query = """SELECT packs.pack_id, packs.name FROM user_packs, packs... | ack_info = get_pack(pack_id)
return user_id == pack_info['owner_id'] or pack_info | ['privacy'] == 'public'
def if_registered(user_id):
query = "SELECT * FROM users WHERE users.user_id = %s;"
cursor.execute(query, (user_id,))
return True if len(cursor.fetchall()) else False
def cards_for_learning(user_id):
query = """SELECT cards.front, cards.back, cards.comment FROM user_cards, ca... |
updatengine/updatengine-server | inventory/migrations/0013_auto__add_field_machine_domain__add_field_machine_uuid__add_field_mach.py | Python | gpl-2.0 | 11,272 | 0.006831 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'machine.domain'
db.add_column('inventory_machine', 'domain',
self.gf('... | {'max_length': '1000'}),
'conditions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['deploy.packagecondition']", 'null': 'True', 'blank': ' | True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'filename': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
malikshahzad228/widget-jack | widgets/admin.py | Python | mit | 400 | 0 | from django.contrib import admin
from .models import BackgroundImages, Widget
class WidgetAdmin(admin.ModelAdmin):
list_display = (' | name', 'link', | 'is_featured')
ordering = ('-id',)
class BackgroundAdmin(admin.ModelAdmin):
list_display = ('name', 'created_at')
ordering = ('-id',)
admin.site.register(Widget, WidgetAdmin)
admin.site.register(BackgroundImages, BackgroundAdmin)
|
hammerlab/topiary | topiary/cli/errors.py | Python | apache-2.0 | 1,087 | 0.00092 | # Copyright (c) 2017. Mount Sinai School of Medicine
#
# 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 t | o in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Commandline arguments related to error handlin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.