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 |
|---|---|---|---|---|---|---|---|---|
mtik00/obfuscator | docs/auto-generate.py | Python | gpl-2.0 | 4,778 | 0.003139 | #!/usr/bin/env python
"""
This script is used to create default documentation for a library.
"""
# Imports ######################################################################
import os
import re
import argparse
# Metadata #####################################################################
__author__ = "Timothy Mc... | s, bottom-up.
@type top: str
@param top: The top-level directory you want removed
@type remove_top: bool
@param remove_top: Whether or not to remove the top director | y
'''
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
if remove_top:
os.rmdir(top)
if __name__ == '__main__':
parser = argparse.ArgumentPa... |
prometheanfire/openstack-guest-agents-unix | tests/test_kms.py | Python | apache-2.0 | 3,525 | 0.000284 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2011 Openstack, LLC.
# 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... | mpts to make at network '
'connections before giving up',
'networkRetries=5',
'',
'hostedWhitelist[comment]=None',
'hostedWhitelist=',
'',
'enableProxy[comment]=Use a HTTP Proxy',
'enableProxy=0',
'',
| 'serverURL[comment]=Remote server URL',
'serverURL=https://proxy1.example.com/XMLRPC;'
'https://proxy2.example.com/XMLRPC;',
'',
'proxyPassword[comment]=The password to use for an authenticated '
'proxy',
'proxyPassword=',
... |
spreeker/democracygame | external_apps/docutils-snapshot/test/functional/tests/standalone_rst_latex.py | Python | bsd-3-clause | 259 | 0 | exec(open('functional/tests/_standalone_rst_defaults.py').read())
# Source and destination file names.
test_source | = "standalone_rst_latex.txt"
test_destination = "standalone_rst_latex.tex"
# Keyword parameters passed to publish_file.
writer_name = " | latex"
|
msullivan/advent-of-code | 2019/5b.py | Python | mit | 1,470 | 0.002041 | #!/usr/bin/env python3
import sys
def run(p, input):
ip = 0
output = []
while True:
instr = p[ip]
def read(i):
mode = (instr // (10**(1+i))) % 10
return p[p[ip+i]] if mode == 0 else p[ip+i]
if instr % 100 == 1:
p[p[ip+3]] = read(1) + read(2)
... | ip += 2
elif instr % 100 == 4:
output.append(read(1))
| ip += 2
elif instr % 100 == 5:
if read(1) != 0:
ip = read(2)
else:
ip += 3
elif instr % 100 == 6:
if read(1) == 0:
ip = read(2)
else:
ip += 3
elif instr % 100 == 7:
if read... |
termie/pupa | nova/db/sqlalchemy/migrate_repo/versions/012_add_ipv6_flatmanager.py | Python | apache-2.0 | 6,625 | 0.000906 | # Copyright (c) 2011 NTT.
# 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 appl... | False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('dns',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('vlan', Integer()),
Column(... | , assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('vpn_public_port', Integer()),
Column('vpn_private_address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=Fa... |
msbeta/apollo | modules/tools/open_space_visualization/hybrid_a_star_visualizer.py | Python | apache-2.0 | 6,581 | 0.00152 | #!/usr/bin/env python
###############################################################################
# Copyright 2018 The Apollo 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 ... | ain__':
visualize_ | flag = True
HybridAStarPlan(visualize_flag)
|
Tosh007/DnD5_CharCreator | menu_warlock.py | Python | gpl-3.0 | 1,304 | 0.003067 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'menu_warlock.ui'
#
# Created by: PyQ | t5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Warlock(object):
def setupUi(self, Warlock):
Warlock.setObjectName("Warlock")
Warlock.resize(261, 181)
self.gridLayout = QtWidgets.QGridLayout(Warlock)
... | me("label_spellSlotLevel")
self.gridLayout.addWidget(self.label_spellSlotLevel, 1, 0, 1, 1)
self.label_spellSlots = QtWidgets.QLabel(Warlock)
self.label_spellSlots.setObjectName("label_spellSlots")
self.gridLayout.addWidget(self.label_spellSlots, 0, 0, 1, 1)
self.retranslateUi(W... |
steder/goose | goose/ftest/__init__.py | Python | mit | 43 | 0 | " | ""Tests that do require database | setup"""
|
egabancho/invenio-communities | invenio_communities/__init__.py | Python | gpl-2.0 | 1,040 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014, 2015 CERN.
#
# Invenio 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 optio... | S 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 Inven | io; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""In... |
magnastrazh/NEUCOGAR | nest/serotonin/research/C/nest-2.10.0/examples/nest/music/msgtest.py | Python | gpl-2.0 | 1,200 | 0.001667 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# msgtest.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 ... | c License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import nest
nest.sli_run("statusdict/have_music ::")
if not nest.spp():
import sys
print("NEST was not compiled with support for MUSIC, not running.")
sys.exit()
mmip = nest.Create('music_message_in_proxy')
nest.SetStatus(mmip, {'p... | t message data with a granularity of 10 ms:
time = 0
while time < 1000:
nest.Simulate (10)
data = nest.GetStatus(mmip, 'data')
print data
time += 10
|
bugobliterator/ardupilot | Tools/autotest/param_metadata/rstemit.py | Python | gpl-3.0 | 10,018 | 0.001897 | #!/usr/bin/env python
from __future__ import print_function
import re
from param import known_param_fields, known_units
from emit import Emit
try:
from cgi import escape as cescape
except Exception:
from html import escape as cescape
# Emit docs in a RST format
class RSTEmit(Emit):
def blurb(self):
... | (widths, heights)
def tablify(self, rows, headings=None, rowheadings=None):
(widths, heights) = self.tablify_calc_row_widths_heights(rows, rowheadings, headings)
# create dividing lines
bar = ""
| heading_bar = ""
for width in widths:
bar += "+"
heading_bar += "+"
bar += "-" * width
heading_bar += "=" * width
bar += "+"
heading_bar += "+"
# create table
ret = bar + "\n"
if headings is not None:
ro... |
smmribeiro/intellij-community | python/testData/refactoring/introduceVariable/substringContainsEscapes.after.py | Python | apache-2.0 | 52 | 0.019231 | a = u"lo \u00d6sterreich\\!\n | "
print(u | "Hel%s\n" % a) |
patrickwolf/python-tutorial | pyintro_b_modules/y_packages_self_contained/package_self_contained/__init__.py | Python | mit | 74 | 0 | from module1 import | Module1
from module2 | import Module2
import subpackage
|
RIEI/printerStats | daemon/models/HPLJ4200/getcounter.py | Python | gpl-2.0 | 373 | 0.008043 | __author__ = 'pferland'
from BeautifulSoup import BeautifulSoup
import urllib2
import re
def getcounter(shost):
html = urllib2.urlopen("http://" + shost + "/hp/device/this.LCDi | spatcher?dispatch=html&cat=0&pos=1")
soup = BeautifulSoup(html.read())
for supply in soup.findAll("font", {'face': 'Helvetica,Arial'}):
pri | nt str(supply) + "\r\n"
return 0 |
thetypist/scrappybot | quotesbot/pipelines.py | Python | mit | 289 | 0 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/e | n/latest/topics/item-pi | peline.html
class QuotesbotPipeline(object):
def process_item(self, item, spider):
return item
|
Zanzibar82/pelisalacarta | python/main-classic/channels/youanimehd.py | Python | gpl-3.0 | 12,881 | 0.020053 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para youanimehd creado por Itsuki Minami
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
i... | 9", url="http://youanimehd.com/tags/0-9"))
itemlist.append( Item(channel=__channel__, action="completo" , title="A" , url="http://youanimehd.com/tags/a"))
itemlist.append( Item(channel=__channel__, action="completo" , title="B" , url="http://youanimehd.com/tags/b"))
itemlist.append( Item(channel=__channel... | nel__, action="completo" , title="D" , url="http://youanimehd.com/tags/d"))
itemlist.append( Item(channel=__channel__, action="completo" , title="E" , url="http://youanimehd.com/tags/e"))
itemlist.append( Item(channel=__channel__, action="completo" , title="F" , url="http://youanimehd.com/tags/f"))
iteml... |
TeamBasedLearning/Service | pgtbl/core/tests/test_register_news.py | Python | gpl-3.0 | 2,899 | 0 | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from accounts.models import User
from core.models import News
class CreateNewsTestCase(APITestCase):
"""
Unit test case to test creating a news in the system.
"""
def setUp(self):
"""... | self.user.delete()
def test_valid_create_news(self):
| """
Admin create a news in the system.
"""
self.client.force_authenticate(self.superuser)
self.assertEquals(News.objects.count(), 0)
data = {
'title': 'News title',
'description': 'News description...',
}
response = self.client.post(self... |
wetneb/django | tests/gis_tests/geo3d/tests.py | Python | bsd-3-clause | 12,923 | 0.002089 | from __future__ import unicode_literals
import os
import re
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import HAS_GEOS
from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
from django.utils._os import upath
from django.utils.deprecation ... | ._load_city_data()
for name, pnt_data in ci | ty_data:
city = City3D.objects.get(name=name)
z = pnt_data[2]
self.assertTrue(city.point.hasz)
self.assertEqual(z, city.point.z)
def test_3d_polygons(self):
"""
Test the creation of polygon 3D models.
"""
self._load_polygon_data()
... |
TamiaLab/carnetdumaker | apps/loginwatcher/admin.py | Python | agpl-3.0 | 520 | 0 | """ |
Admin views for the log watcher app.
"""
from django.contrib import admin
from .models import LogEvent
class LogEventAdmin(admin.ModelAdmin):
"""
Admin form for the ``LogEvent`` data model.
"""
list_display = ('event_date',
'type',
'username',
... | entAdmin)
|
erp12/pyshgp | examples/iris.py | Python | mit | 1,859 | 0.001076 | import random
import pandas as pd
from pyshgp.push.instruction_set import InstructionSet
from pyshgp.gp.estimators import PushEstimator
from pyshgp.gp.genome import GeneSpawner
# A sample of the famous Iris dataset.
data = pd.DataFrame(
data=[
[5.1, 3.5, 1.4, 0.2, 0],
[4.9, 3.0, 1.4, 0.2, 0],
... | 1.4, 0.3, 0],
[5.0, 3.4, 1.5, 0.2, 0],
[4.4, 2.9, 1.4, 0.2, 0],
[4.9, 3.1, 1.5, 0.1, 0],
[7.0, 3.2, 4.7, 1.4, 1],
[6.4, 3.2, 4.5, 1.5, 1],
[6.9, 3.1, 4.9, 1.5, 1],
[5.5, 2.3, 4.0, 1.3, 1] | ,
[6.5, 2.8, 4.6, 1.5, 1],
[5.7, 2.8, 4.5, 1.3, 1],
[6.3, 3.3, 4.7, 1.6, 1],
[4.9, 2.4, 3.3, 1.0, 1],
[6.6, 2.9, 4.6, 1.3, 1],
[5.2, 2.7, 3.9, 1.4, 1],
[6.3, 3.3, 6.0, 2.5, 2],
[5.8, 2.7, 5.1, 1.9, 2],
[7.1, 3.0, 5.9, 2.1, 2],
[6.3, 2.9, 5.... |
manhhomienbienthuy/pythondotorg | users/migrations/0004_auto_20150503_2100.py | Python | apache-2.0 | 776 | 0.002577 | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20150503_2026'),
]
operations = [
migrations.AddField(
mod | el_name='membership',
name='membership_type',
field=models.IntegerField(choices=[(0, 'Basic Member'), (1, 'Supporting Member'), (2, 'Sponsor Member'), (3, 'Managing Member'), (4, 'Contributing Member'), (5, 'Fellow')], default=0),
preserve_default=True,
),
migrations.... | model_name='membership',
name='votes',
field=models.BooleanField(verbose_name='I would like to be a PSF Voting Member', default=False),
preserve_default=True,
),
]
|
oaksharks/BBS | main/test.py | Python | gpl-3.0 | 211 | 0.031746 | #coding:utf8
import httplib2
import urllib
from connutils import HTTP
import json
import re
import bs4
| import MySQLdb
aa={"name":"wuhaifeng","age":11}
# i | n 可以判断map中是否包含某个key
print aa["wu"] |
TakayukiSakai/tensorflow | tensorflow/examples/how_tos/reading_data/fully_connected_preloaded.py | Python | apache-2.0 | 5,371 | 0.005399 | # Copyright 2015 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... | t_images, input_labels], num_epochs=FLAGS.num_epochs)
label = tf.cast(label, tf.int32)
images, labels = tf.train.batch(
[image, label], batch_size=FLAGS.batch_size)
# Build a Graph that computes predictions from the inference model.
logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hi... | .training(loss, FLAGS.learning_rate)
# Add the Op to compare the logits to the labels during evaluation.
eval_correct = mnist.evaluation(logits, labels)
# Build the summary operation based on the TF collection of Summaries.
summary_op = tf.merge_all_summaries()
# Create a saver for writing traini... |
exercism/python | exercises/practice/grade-school/grade_school.py | Python | mit | 225 | 0 | class S | chool:
def __init__(self):
pass
def add_student(self, name, grade):
pass
def roster(self):
pass
def grade(self, grade_number):
pass
| def added(self):
pass
|
shiftkey/electron | build/zip.py | Python | mit | 1,544 | 0.016839 | #!/usr/bin/env python
import os
import subprocess
import sys
import zipfile
LINUX_BINARIES_TO_STRIP = [
'electron',
'libffmpeg.so',
'libnode.so'
]
def strip_binaries(target_cpu, dep):
for binary in LINUX_BINARIES_TO_STRIP:
if dep.endswith(binary):
strip_binary(dep, target_cpu)
def strip_binary(binar... | arget_cpu == 'arm64':
strip = 'aarch64-linux-gnu-strip'
elif target_cpu == 'mips64el':
strip = 'mips64el-redhat-linux-strip'
else:
strip = 'strip'
execute([strip, binary_path])
def execute(argv):
try:
output = subprocess.check_output(argv, stderr=subprocess.STDOUT)
return output
except su... | _deps) as f:
for dep in f.readlines():
dep = dep.strip()
dist_files += [dep]
if sys.platform == 'darwin':
mac_zip_results = execute(['zip', '-r', '-y', dist_zip] + dist_files)
else:
with zipfile.ZipFile(dist_zip, 'w', zipfile.ZIP_DEFLATED) as z:
for dep in dist_files:
if target... |
Scan-o-Matic/scanomatic | tests/unit/image_analysis/conftest.py | Python | gpl-3.0 | 470 | 0 | from __future__ import absolute_import
import os
import pytest
from scipy import ndimage
TESTDATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'testdata')
@pytest.fixture(scope='session')
def easy_plate():
return ndimage.io.imread(
os.path.join(TESTDATA, 'test_fixture_easy.tiff')
)
|
@pyt | est.fixture(scope='session')
def hard_plate():
return ndimage.io.imread(
os.path.join(TESTDATA, 'test_fixture_difficult.tiff')
)
|
l8orre/nxtPwt | nxtPwt/nxtWin5Control1.py | Python | mit | 2,721 | 0.016538 | # -*- coding: utf-8 -*-
"""
Copyright (c) 2014 l8orre
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, pub... | s WinControl1 known
def init(self): #, ui_AlgoWin):
""" the AlgoWin """
# maybe this gives trouble w/ MainWIn, self.app.algo = Algo1(self.app, u | i)
### re - init hte algo here!!!
ui = self.ui_nxtWin5
############################
############################
############################
########## Window Maintenance
def show(self):
self.uiFrame = QtGui.QMainWindow()
self.u... |
RemiZOffAlex/specialistoff.net | Zabbix/scripts/test.py | Python | mit | 1,067 | 0.008563 | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argumen... | type=int, nargs='*',
help='an integer for the accumulator')
args = parser.parse_args()
if args.discovery:
data = [
{"{#T1}": "1","{#T2}": "1"},
{"{#T1}": "1","{#T2}": "2"},
{"{#T1}": "2","{#T2}": "1"},
{"{#T1}": "2","{#T2}": "2"}
]
... | pt Exception, ex:
traceback.print_exc(file=sys.stdout)
exit(1)
exit(0)
|
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/examples/openmdao.examples.expected_improvement/openmdao/examples/expected_improvement/test/test_single_objective_ei.py | Python | mit | 1,872 | 0.000534 | """
Test for single criteria EI example.
"""
import logging
import os.path
import random
import unittest
from numpy import pi
from openmdao.examples.expected_improvement.single_objective_ei import Analysis
from openmdao.main.api import set_as_top
from pyevolve import Selectors
class SingleObjectiv | eEITest(unittest.TestCase):
"""Test to make sure the EI sample problem works as it should"""
def tearDown(self):
if os.path.exists('adapt.csv'):
os.remove('adapt.csv')
def test_EI(self):
random.seed(0)
# pyevolve does some caching that causes failures during our
... | omplete unit tests due to stale values in the cache attributes
# below, so reset them here
Selectors.GRankSelector.cachePopID = None
Selectors.GRankSelector.cacheCount = None
Selectors.GRouletteWheel.cachePopID = None
Selectors.GRouletteWheel.cacheWheel = None
analysis =... |
miur/miur | OLD/miur/graph/transform.py | Python | gpl-3.0 | 554 | 0.001805 | #
# SPDX-FileCopyrightText: 2017 Dmytro Kolomoiets <amerlyq@gmail.com> and c | ontributors.
#
# SPDX-License-Identifier: GPL-3.0-only
#
class NodeSuperimposeTr(object):
def __call__(self, g, node_uid, aug):
conv = {}
for uid in aug:
if uid == aug.get_root():
g[node_uid] = aug[uid]
conv[uid] = node_uid
else:
... | |
Cisco-Talos/pyrebox | volatility/volatility/plugins/overlays/windows/vista_sp12_x86_syscalls.py | Python | gpl-2.0 | 43,170 | 0.05388 | # Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 o... | 0x48
'NtCreateProcessEx', # 0x49
'NtCreateProfile', # 0x4a
'NtCreateSection', # 0x4b
'NtCreateSemaphore', | # 0x4c
'NtCreateSymbolicLinkObject', # 0x4d
'NtCreateThread', # 0x4e
'NtCreateTimer', # 0x4f
'NtCreateToken', # 0x50
'NtCreateTransaction', # 0x51
'NtOpenTransaction', # 0x52
'NtQueryInformationTransaction', # 0x53
'NtQueryInformationTransactionManager', # 0x54
'NtPrePrepareEnlistmen... |
vncastanheira/noirgame | player.py | Python | lgpl-3.0 | 3,021 | 0.032771 | # Copyright Vinicius Castanheira (vncastanheira@gmail.com) - 2012
# This program is a part of the Noir Game.
# This program is under the Gnu LGPL.
from pygame import *
from pyganim import *
from entity import Entity
from bullet import Bullet
class Player(Entity):
def __init__(self, x, y, images):
Entity.__init__(... | )
shoot.play()
bulletDir | ection = 0
if self.facingDirection == 'RIGHT':
bulletDirection = self.rect.right
if self.facingDirection == 'LEFT':
bulletDirection = self.rect.left
self.bulletGroup.add(Bullet(bulletDirection, self.rect.centery, self.facingDirection, ["bullet.png"]))
self.bullets -= 1
if event.type == KEY... |
xudongyangwork/algo | day43/xudy.py | Python | mit | 251 | 0.007968 | # -*- coding:utf-8 -*- |
def length_of_last_word(str_):
split_str = str_.split(" ")
if not split_str:
return 0
return len(split_str[-1])
if __name__ == '__main__':
result = length_of_last | _word("hello world")
print(result) |
cul-it/Invenio | modules/webstyle/lib/webinterface_handler_wsgi.py | Python | gpl-2.0 | 27,426 | 0.004704 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011, 2012 CERN.
##
## Invenio 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... | form[2]
# This must be done to avoid a bug in cgi.FieldStorage
self.__environ.setdefault('QUERY_STRING', '')
## Video handler hack:
uri = self.__env | iron['PATH_INFO']
if uri.endswith("upload_video"):
tmp_shared = True
else:
tmp_shared = False
fs = FieldStorage(self, keep_blank_values=1, to_tmp_shared=tmp_shared)
if fs.wsgi_input_consumed:
new_input = InputProcessed()
post_form = (new_in... |
laborautonomo/youtube-dl | youtube_dl/extractor/howcast.py | Python | unlicense | 1,474 | 0.004749 | from __future__ import unico | de_literals
import re
from .common import InfoExtractor
class HowcastIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
_TEST = {
'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly',
'md5': '8b743df908c42f60cf6496586c7f12c3',
... | 'ext': 'mp4',
'description': 'The square knot, also known as the reef knot, is one of the oldest, most basic knots to tie, and can be used in many different ways. Here\'s the proper way to tie a square knot.',
'title': 'How to Tie a Square Knot Properly',
}
}
def _rea... |
chiehtu/kissaten | manage.py | Python | mit | 311 | 0 | #!/usr/bin/env p | ython
import os
import sys
import dotenv
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
dotenv.read_dotenv('project/.env')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| |
krishnazure/ansible | lib/ansible/playbook/playbook_include.py | Python | gpl-3.0 | 5,458 | 0.003115 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
else:
# FIXME/TODO: validate that items[0] is a file, which also
# exists and is readable
new_ds['include'] = items[0]
| if len(items) > 1:
# rejoin the parameter portion of the arguments and
# then use parse_kv() to get a dict of params back
params = parse_kv(" ".join(items[1:]))
if 'tags' in params:
new_ds['tags'] = params.pop('tags')
... |
PRX/Infrastructure | bin/continuity.py | Python | mit | 2,044 | 0.000489 | # TODO WIP this is meant to find discrepencies between the stack templates that
# are deployed to CloudFormation and what is checked in, and do some other
# basic sanity checks on the stacks and their configurations
import boto3
import re
cloudformation = boto3.client("cloudformation")
stacks = cloudformation.descri... | emplate_path = re.findall(r"\# ([a-zA-Z/_\-\.]+yml)", cfn_first_line)[0]
local_path = f"../{template_path}"
try:
local_body = open(local_path, "r").read()
except FileNotFoundError:
print(f"File error: {stack['StackName']}")
if not local_body == cfn_body:
... | ]}")
|
jessamynsmith/boards-backend | blimp_boards/accounts/constants.py | Python | agpl-3.0 | 667 | 0 | BLACKLIST_SIGNUP_DOMAINS = ['gmail.com', 'yahoo.com', 'hotmail.com']
ACCOUNT_RESERVED_KEYWORDS = [
'company', 'admin', 'api', 'signout', 'reset', '404', '500',
'docs', 'signup', 'signin', 'invitation', 'chat', 'report', 'community',
'user', 'notification', 'notifications', 'feedback', 'media', 'static',
... | 'download', 'downloads', 'reports', 'redeem',
'invitations', '_admin', 'tos', 'privacy', 'login', 'register', 'logout',
'context', 'maintenance', 'error', '__debug__', 'webhook', 'approval',
'import', 'discussions', 'inbound_web | hook', 'workspace', 'workspaces',
'referrals', 'account', 'accounts', 'tasks'
]
|
hqpr/findyour3d | findyour3d/quote/tests.py | Python | mit | 814 | 0.003686 | from django.test import TestCase, Client
from django.urls import resolve
from django.core.urlresolvers import reverse
from django.utils import timezone
from findyour3d.users.models import User
class DashboardTests(TestCase):
def setUp(self):
self.starter_user = User.objects.crea | te(username='test', is_active=True,
email='test@test.com', user_type=2,
payment_active=True, plan=1,
paid_at=timezone.now())
self.starter_user.s | et_password('1234567a')
self.starter_user.save()
self.client = Client()
self.client.login(username='test', password='1234567a')
outdate = timezone.now().date() - timezone.timedelta(days=40)
|
bradleyhd/netsim | mapserver/graph/downloader.py | Python | gpl-3.0 | 659 | 0.007587 | import logging
from urllib.request import urlopen
from shutil import copyfileobj
class MapDownloader(object):
def __init__(self):
self.__log = logging.getLogger(__name__)
def to_file(self, top, left, bottom, right, file_path = 'map.osm'):
self.__log.info('Downloading map data for [%f,%f,%f,... | f]' % (top, left, bottom, right))
url = 'http://www.overpass-api.de/api/xapi?way[bbox=%f,%f,%f,%f][highway=*]' % (left, bottom, right, top)
with urlopen(url) as response, open(file_path, 'wb') as out_file:
copyfileobj(response, out_file)
self.__log.info('Download complet | e, saved as %s' % file_path)
|
xu-cheng/youtube-dl | youtube_dl/postprocessor/execafterdownload.py | Python | unlicense | 865 | 0.002312 | from __future__ import unicode_literals
import subprocess
from .common import PostProcessor
from ..utils | import (
shlex_quote,
PostProcessingError,
)
class ExecAfterDownloadPP(PostProcessor):
def __init__(self, downloader=None, verboseOutput=None, exec_cmd=None):
self.verboseOutput = verboseOutput
self.exec_cmd = exec_cmd
def run(self, information):
cmd = self.exec_cmd
if... |
self._downloader.to_screen("[exec] Executing command: %s" % cmd)
retCode = subprocess.call(cmd, shell=True)
if retCode != 0:
raise PostProcessingError(
'Command returned error code %d' % retCode)
return None, information # by default, keep file and do noth... |
rsj217/tornado--scaffold | tornapro/tiger/app/views/auth.py | Python | mit | 1,227 | 0.00326 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'ghost'
import tornado.web
from app import router
f | rom app.helper import BaseAuthHandler
from app.models.auth import User
@router.Route('/auth/login')
class AuthLoginHandler(BaseAuthHandler):
def get(self, *args, **kwargs):
html = ('<form method="post">'
| '<label>username:<label>'
'<input name="username">'
'<input type="submit" value="login">'
'</form>')
self.finish(html)
def post(self, *args, **kwargs):
username = self.get_argument('username')
user = User.findone(username=username)
... |
phobson/bokeh | tests/conftest.py | Python | bsd-3-clause | 1,448 | 0.001381 | import pytest
from tests.plugins.constants import default_upload
from tests.plugins.upload_to_s3 import upload_file_to_s3_by_job_id
pytest_plugins = (
"tests.examples.examples_report_plugin",
"tests.integration.integration_tests_plugin",
"tests.plugins.bokeh_server",
"tests.plugins.jupyter_notebook",
... | not is_slave:
with open(request.config.option.log_file, 'w') as f:
| # Clean-out any existing log-file
f.write("")
with open(pytest.config.option.log_file, 'a') as f:
yield f
|
Tomohiro/apex-python-boilerplate | functions/example/src/example.py | Python | mit | 271 | 0 | """Example Module name.
Module short description
"""
class Example(object):
"""Class description."""
def __init__(self, event):
self.event = event
def work(self):
"""Return the message."""
return 'Hello, %s!' % self.event | ['name | ']
|
mrZizik/lab_reports | webServicesESLab5/main.py | Python | apache-2.0 | 1,487 | 0.03497 | #!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)
from pprint import pprint
import json
import urllib2
@app.route('/', methods=['GET'])
def hello():
try:
greetings = urllib2.urlopen("http://188.130.155.37:8080/User").read()
except (urllib2.HTTPError, urllib2.URLError) as e:
... | esponse = str(var1) +" multiply " + str(var2) + "=" + str(multiply)
elif (req["meth"]=="divide"):
divide = var1/var2
response = str(var1) +" divide " + str(var2) + "=" + str(divide)
else:
response = "Don't know that | method " + meth
else:
response = "Check parameters"
return jsonify({'message': response})
def checkVars(req):
return req['var1'].isdigit() and req['var2'].isdigit() and req['meth']!= None
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005, debug=True)
|
hwaf/hwaf | py-hwaftools/orch/features/feature_download.py | Python | bsd-3-clause | 2,298 | 0.013925 | #!/usr/bin/env python
'''
A feature to download a file.
It requires no previous steps. It provides the 'download_seturl' and
'download' steps
'''
import os
from waflib.TaskGen import feature
import waflib.Logs as msg
from orch.util import urlopen
import orch.features
orch.features.register_defaults(
'download'... | raise
| checksum = tgen.worch.download_checksum
if not checksum:
return
hasher_name, ref = checksum.split(":")
import hashlib, os
# FIXME: check the hasher method exists. check for typos.
hasher = getattr(hashlib, hasher_name)()
hasher.update(tgt.read('rb'))
... |
tiagofrepereira2012/bob.measure | bob/measure/test_error.py | Python | bsd-3-clause | 13,944 | 0.019722 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Wed 11 Dec 15:14:08 2013 CET
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
"""Basic tests for the error measuring system of bob
"""
import os
import numpy
import nose.tools
import bob.io.base
de... | rn list(array == value).count(True)
# This example will demonstrate and check the use of eer_threshold() to
# calculate the threshold that minimizes the EER.
# This test set is not separable.
positives = bob.io.base.load(F('nonsep-positives.hdf5'))
negatives = bob.io.base.load(F('nonsep-negatives.hdf5')) |
threshold = eer_threshold(negatives, positives)
sorted_positives = numpy.sort(positives)
sorted_negatives = numpy.sort(negatives)
# Of course we have to make sure that will set the EER correctly:
ccp = count(correctly_classified_positives(positives,threshold))
ccn = count(correctly_classified_negatives(n... |
agry/NGECore2 | scripts/static_spawns/tatooine/jabba_tp_romo_vax_bunker.py | Python | lgpl-3.0 | 4,612 | 0.014961 | import sys
# Project SWG: Jabba TP Romo Vax Bunker: Static Spawns
# (C)2014 ProjectSWG
from resources.datatables import Options
from resources.datatables import State
def addPlanetSpawns(core, planet):
stcSvc = core.staticService
objSvc = core.objectService
stcSvc.spawnObject('romovax_henchman', 'tatooin... | ), float(-5051.8), float(45.7), float(-6989.7), float(0), float(0), float(0), float(0), 45)
stcSvc.spawnObject('romovax_henchman', 'tatooine', long(0), float(-5030.7), float(46.5), float(-6972.5), float(0), float(0), float(0), float(0), 45)
stcSvc.spawnObject('romovax_henchman', 'tatooine', long(0), float(-5019), flo... | ect('romovax_henchman', 'tatooine', long(0), float(-5045.8), float(42.6), float(-6936), float(0), float(0), float(0), float(0), 45)
stcSvc.spawnObject('romovax_henchman', 'tatooine', long(0), float(-5053.7), float(43.6), float(-6961.9), float(0), float(0), float(0), float(0), 45)
stcSvc.spawnObject('romovax_henchman'... |
wagnerandreoli/clitoolkit | clit/dev/packaging.py | Python | bsd-3-clause | 17,451 | 0.003382 | # -*- coding: utf-8 -*-
"""Packaging tools to publish projects on PyPI and GitHub."""
import os
import sys
from pathlib import Path
from shutil import rmtree
from textwrap import dedent
from typing import List, Optional, Tuple
import click
from clit import DRY_RUN_OPTION
from clit.files import shell
from clit.ui impo... | s would be changed", exit_on_failure=True)
if not self.dry_run:
chosen_lines = shell(self._bump(self.CMD_BUMP_VERSION_GREP, part, allow_dirty), return_lines=True)
new_version = chosen_lines[0].strip("'")
commit_message = chosen_lines[1].strip("'").lower()
click.ec... | rom X to Y"
new_version = "<new ve |
skorokithakis/django-fancy-cache | fancy_tests/tests/urls.py | Python | bsd-3-clause | 239 | 0.008368 | from django | .conf.urls.defaults import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.home, name='home'),
#url(r'^2$', views.home2, name='home2'),
#url(r'^3$', view | s.home3, name='home3'),
)
|
nzlosh/st2 | contrib/runners/inquirer_runner/setup.py | Python | apache-2.0 | 1,838 | 0.000544 | # -*- coding: utf-8 -*-
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 t | he License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITION | S OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import os.path
from setuptools import setup
from setuptools import find_packages
from dist_utils import fetch_requirements
from dist_... |
heibanke/python_do_something | Code/Chapter2/homework2-4_csv_ex.py | Python | apache-2.0 | 647 | 0.017002 | #!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke
import csv
import re
csvfile = o | pen('beijing_jt.csv','r')
reader = csv.reade | r(csvfile)
# reader.next() only can use in py2
next(reader)
jt_info = next(reader)
print(jt_info[1].decode('utf-8'))
csvfile.close()
# convert stations info format
station_pattern = (r'(?P<number>[0-9]+)\s(?P<name>\D+)')
station_list = []
stations = re.findall(station_pattern,jt_info[-1].deco... |
LagrangianPoint/Apache-Rewrite-Maps-Python | under2space.py | Python | mit | 754 | 0.015915 | #!/usr/bin/python -u
"""
This script replaces underscores with spaces (%20)
Project: https://github.com/LagrangianPoint/Apa | che-Rewrite-Maps-Python/
http://httpd.apache.org/docs/current/rewrite/rewritemap.html
http://fragmentsofcode.wordpress.com/2009/02/04/python-script-for-apache-rewritemap/
http://codeblow | .com/questions/apache2-rewritemap-python-when-coming-back-null-apache-dangles/
HINTS FOR DEBUGGING:
RewriteEngine On
RewriteLogLevel 9
RewriteLog /var/log/apache2/rewrite.log
"""
import sys
while sys.stdin:
try:
strLine = sys.stdin.readline().strip() ## It is very important to use strip... |
sdl-static/ircbot-collection | beanbot.py | Python | gpl-2.0 | 7,221 | 0.014402 | #!/usr/bin/env python
#
# Simple IRC Bot to announce messages
#
# Code originally based on example bot and irc-bot class from
# Joel Rosdahl <joel@rosdahl.net>, author of included python-irclib.
#
"""An IRC bot to announce messages on a channel.
This is an example bot that uses the SingleServerIRCBot class from
ircb... | eply(e, "I am a bot written in Python "
"using the python-irclib library")
self.reply(e, "My source code is available at %s" % svn_url)
def | do_command(self, e, cmd):
"""This is the function called whenever someone sends a public or
private message addressed to the bot. (e.g. "bot: blah"). Parse
the CMD, execute it, then reply either to public channel or via
/msg, based on how the command was received. E is the original
event, and FRO... |
Straor/Prog | Python/prog13.py | Python | mit | 255 | 0.031373 | # -*- coding: utf-8 -*-
# programme qui demande un nombre et affiche les 10 triples successifs
chaine = input("donne un nombre : ")
nombre = int(chaine)
triple = nombre
compteur=1
while(compteur<=10):
triple=triple*3
print(triple)
| compteur=compteur+1
| |
peterhinch/micropython-tft-gui | tft/demos/dialog.py | Python | mit | 2,864 | 0.044693 | # dialog.py Test/demo of modal dialog box for Pybboard TFT GUI
# Adapted for (and requires) uasyncio V3
# Released under the MIT License (MIT). See LICENSE.
# Copyright (c) 2016-2020 Peter Hinch
from tft.driver.constants import *
from tft.driver.tft_local import setup
from tft.driver.ugui import Screen, Aperture
fro... | lf.back, args = ('Cat',))
Button(self.locn(120, y), height = 30, width = 80, font = font14, fontcolor = BLACK, fgcolor = GREEN,
text = 'Dog', shape = RECTANGLE,
callback = self.back, args = ('Dog',))
Button(self.locn(width - 26, 1), height = 25, width = 25, font = font10,
... |
callback = self.back, args = ('Close',))
def back(self, button, text):
Aperture.value(text)
Screen.back()
class BaseScreen(Screen):
def __init__(self):
super().__init__()
Label((0, 0), font = font14, value = 'Dialog box demonstration.')
Label((0, 100), f... |
JulianVolodia/Politikon | accounts/migrations/0020_userprofile_last_transaction.py | Python | gpl-2.0 | 428 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0019_auto_20160518_0048'),
]
operations = [
migrations.AddField(
model_name='u | serprofile',
name='last_transaction',
field=models.DateTimeField(null=True, blank=True | ),
),
]
|
genialis/resolwe-bio | resolwe_bio/tests/workflows/test_mirna.py | Python | apache-2.0 | 2,406 | 0.001247 | from resolwe.flow.models import Data
from resolwe.test import tag_process, with_resolwe_host
from resolwe_bio.utils.test import KBBioProcessTestCase
class MicroRNATestCase(KBBioProcessTestCase):
@with_resolwe_host
@tag_process("workflow-mirna")
def test_mirna_workflow(self):
# Prepare data for al... | s": "Homo sapiens",
"build": "fake_genome_RSEM",
}
ref_seq = self.run_process("upload-fasta-nucl", inputs)
bowtie2_index = self.run_process("bowtie2-index", {"ref_seq": ref_seq.id})
single_rea | ds = self.prepare_reads(["reads rsem.fq.gz"])
annotation = self.prepare_annotation(
"annotation_rsem.gtf.gz",
species="Homo sapiens",
build="fake_genome_RSEM",
)
inputs = {
"preprocessing": {
"reads": single_rea... |
udayinfy/openerp-7.0 | move_reports/stock_move_report/stock_move_report.py | Python | agpl-3.0 | 23,230 | 0.008437 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2013 Elico Corp. All Rights Reserved.
# Author: LIN Yu <lin.yu@elico-corp.com>
#
# This program is free software: you can redistribute it a... | 00'),
'end_date': lambda *a: time.strftime('%Y-%m-%d 15:59:59'),
'type': 'in',
}
def generate_report(self, cr, uid, ids, context=None):
| if context is None:
context = {}
data = self.browse(cr, uid, ids, context=context)[0]
context['start_date'] = data.start_date
context['end_date'] = data.end_date
context['type'] = data.type
pi_obj = self.pool.get('stock.move.report')
pi_obj.g... |
norayr/unisubs | utils/management/commands/get_memcached.py | Python | agpl-3.0 | 1,043 | 0.006711 | # Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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 the Free Software Foundation, either version 3 of the
# License, or (at your ... | ld have received a copy of the GNU Affero General Public License
# along with this | program. If not, see
# http://www.gnu.org/licenses/agpl-3.0.html.
from django.core.management.base import BaseCommand
from django.conf import settings
from django.core.cache import cache
class Command(BaseCommand):
help = u'Get a test value from memcached'
def handle(self, *args, **kwargs):
ret... |
jazzband/django-axes | axes/management/commands/axes_reset_logs.py | Python | mit | 643 | 0 | from django.core.management.base import BaseCommand
from axes.handlers.proxy import AxesProxyHandler
class Command(BaseCommand):
| help = "Reset access log records older than given days."
def add_arguments(self, parser):
parser.add_argument(
"--age",
type=int,
default=30,
help="Maximum age for records to keep in days",
)
def handle(self, *args, **opti | ons):
count = AxesProxyHandler.reset_logs(age_days=options["age"])
if count:
self.stdout.write(f"{count} logs removed.")
else:
self.stdout.write("No logs found.")
|
dolejarz/engsci_capstone_transport | python/temporal_analysis/subway_trips.py | Python | mit | 1,027 | 0.008763 | import pandas as pd
import matplotlib.pyplot as plt
df_subway = pd.read_csv('/Users/dolejarz/Documents/Engineering Science/4th Year/CIV455/github/engsci_capstone_transport/gis/subway_buffer/trips_in_buffer.csv')
df_all = pd.read_csv('/Users/dolejarz/Documents/Engineering Science/4th Year/CIV455/github/engsci_capstone... | vot_table(df_all,index='start_hour',aggfunc='count')
#series of hourly distribution of trips as a percent of daily total
subway_percent = pt_subway['tx']/float(pt_subway['tx'].sum())
all_percent = pt_all['tx']/float(pt_all['tx'].sum())
pl | t.figure(figsize=(12,8), dpi=300)
plt.plot(range(24), subway_percent)
plt.plot(range(24), all_percent,color='r')
plt.savefig('subway_vs_all.png')
|
barometz/shirk | plugs/Auth/auth.py | Python | mit | 3,986 | 0.00276 | # Copyright (c) 2012 Dominic van Berkel
# See LICENSE | for details.
from plugs impo | rt plugbase
from util import Event
class AuthPlug(plugbase.Plug):
"""Auth plug. Handles auth stuffs."""
name = 'Auth'
# manual_auths is a dict of source:target that are created after !auth requests so they can be
# responded to appropriately.
manual_auths = dict()
def load(self, startingup=... |
roadmapper/ansible | lib/ansible/modules/cloud/amazon/ec2_vpc_subnet_info.py | Python | gpl-3.0 | 8,136 | 0.002827 | #!/usr/bin/python
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
... | ype: complex
contains:
association_id:
description: The association ID
returned: always
type: str
ipv6_cidr_block:
description: The IPv6 CIDR block that is associated with the subnet.
... | /dict that contains a single item. The state of the cidr block association.
returned: always
type: dict
contains:
state:
description: The CIDR block association state.
returned: al... |
Carlosaarodrigues/orpsoc | orpsoc/system.py | Python | gpl-3.0 | 1,541 | 0.005191 | from orpsoc.orpsocconfigparser import OrpsocConfigParser
from orpsoc.config import Config
import os
import logging
logger = logging.getLogger(__name__)
class System:
def __init__(self, system_file):
logger.debug('__init__() *Entered*' +
'\n system_file=' + str(system_file)
... | \nSYSTEM INFO")
print("Name: " + self.name)
show_list = lambda s: "\n ".join(s.split('\n'))
if self.backend_name:
print("Backend name: " + self.backend_name)
print(" family: " + self.backend['family'])
| print(" device: " + self.backend['device'])
print("\n tcl_files: " + show_list(self.backend['tcl_files']))
print("\n sdc_files: " + show_list(self.backend['sdc_files']))
logger.debug('info() -Done-')
|
blaketmiller/mediator | mediator/torrent.py | Python | gpl-2.0 | 8,786 | 0.000341 | #!/usr/bin/env python
from __future__ import absolute_import
import os
from shutil import rmtree
from mediator import logger
from mediator.config import settings
from mediator.media import Media
class UpdateError(Exception):
pass
class LinkError(Exception):
pass
class Torrent(object):
def __init__(... | ename'] = name
# check if metadata changes to episode means name of episo | de changed
elif self.metadata['type'] == "episode":
name = Media.get_episode_name(series=self.metadata['series'],
season=self.metadata['season'],
episode=self.metadata['episode'])
# update episode name i... |
PetrDlouhy/django-comments-moderation | comments_moderation/settings.py | Python | agpl-3.0 | 358 | 0.002793 | import | os
from importlib import import_module
def import_module_attr(path):
package, module = path.rsplit('.', 1)
return getattr(import_module(package), module)
settings = import_module_attr(
os.getenv('COMMENTS_MODERATION_SETTINGS_MODULE', 'django.conf.settings')
)
MODERATION_MODE = getattr(settings, 'COMMENT... | |
helpyellowsn0w/Kurisu | addons/kickban.py | Python | apache-2.0 | 14,000 | 0.002659 | import datetime
import discord
import json
import re
import time
from discord.ext import commands
from sys import argv
class KickBan:
"""
Kicking and banning users.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.has_... | t.say("💢 I don't have permission to do this.")
@commands.has_permissions(ban_members=True)
@commands.command(pass_context=True, name="silentban", hidden=True)
asy | nc def silentban_member(self, ctx, user, *, reason=""):
"""Bans a user from the server, without a notification. OP+ only."""
try:
try:
member = ctx.message.mentions[0]
except IndexError:
await self.bot.say("Please mention a user.")
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/nccl/__init__.py | Python | bsd-2-clause | 1,328 | 0 | # 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... | e specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for using NVIDIA nccl collective ops.
@@all_max
@@all_min
@@all_prod
@@all_sum
@@broadcast
"""
from __future__ import absolute_im | port
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.nccl.python.ops.nccl_ops import all_max
from tensorflow.contrib.nccl.python.ops.nccl_ops import all_min
from tensorflow.contrib.nccl.python.ops.nccl_ops import all_prod
from tensorflow.contrib.nccl.python.ops.nccl_ops im... |
seanfisk/buzzword-bingo-server | djangorestframework/tests/parsers.py | Python | bsd-3-clause | 7,768 | 0.004119 | # """
# ..
# >>> from djangorestframework.parsers import FormParser
# >>> from djangorestframework.compat import RequestFactory
# >>> from djangorestframework.views import View
# >>> from StringIO import StringIO
# >>> from urllib import urlencode
# >>> req = RequestFactory().get('/')
# >>> ... | ')
# body = CRLF.join(L)
# content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
# return content_type, body
#
# def get_content_type(filename):
# return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
#
#class TestMultiPartParser(TestCase):
# def setUp(self):
# self.req... | _type, self.body = encode_multipart_formdata([('key1', 'val1'), ('key1', 'val2')],
# [('file1', 'pic.jpg', 'blablabla'), ('file1', 't.txt', 'blobloblo')])
#
# def test_multipartparser(self):
# """Ensure that MultiPartParser can parse multipart/form-data that contains a mix of several files and paramete... |
Universal-Model-Converter/UMC3.0a | data/Python/x86/Lib/site-packages/OpenGL/GLUT/fonts.py | Python | mit | 946 | 0.0074 | """Load font "constants" (actually void *s) from the GLUT DLL"""
from OpenGL import platform
import logging
log = logging.getLogger( 'OpenGL.GLUT.fonts' )
for name in [
| 'GLUT_STROKE_ROMAN',
'GLUT_STROKE_MONO_ROMAN',
'GLUT_BITMAP_9_BY_15',
'GLUT_BITMAP_8_BY_13',
'GLUT_BITMAP_TIMES_ROMAN_10',
'GLUT_BITMAP_TIMES_ROMAN_24',
'GLUT_BITMAP_HELVETICA_10',
'GLUT_BITMAP_HELVETICA_12',
'GLUT_BITMAP_HELVETICA_18',
]:
try:
# Win32 just has pointers to v | alues 1,2,3,etc
# GLX has pointers to font structures...
p = platform.getGLUTFontPointer( name )
except (ValueError,AttributeError), err:
if platform.GLUT:
log.warn( '''Unable to load font: %s''', name )
globals()[name] = None
else:
globals()[name] = p
... |
chrswt/vicarious-microservice | tests/translation.py | Python | mit | 2,992 | 0.001003 | import unittest
import requests
class TranslationTests(unittest.TestCase):
def setUp(self):
self.url = 'http://127.0.0.1/api/translate'
def test_given_words(self):
"""Should pass for the basic test cases provided"""
test_words = ['pig', 'banana', 'trash', 'happy', 'duck', 'glove',
... | return HTTP/406 for empty strings')
def test_long_paragraphs(self):
"""Should translate long paragraphs with new lines intact"""
self.maxDiff = None
expected_result = ''
test_paragraph = ''
with open('tests/lorem_ipsum.txt') as input_paragraph:
test_paragraph =... | xpected_result = expected.read()
response = requests.post(self.url, test_paragraph).text
self.assertEqual(response, expected_result,
'Should translate long paragraphs accurately')
if __name__ == '__main__':
unittest.main() |
midnightradio/gensim | docs/src/gallery/core/run_core_concepts.py | Python | gpl-3.0 | 15,054 | 0.002192 | r"""
Core Concepts
=============
This tutorial introduces Documents, Corpora, Vectors and Models: the basic concepts and terms needed to understand and use gensim.
"""
import pprint
###############################################################################
# The core concepts of ``gensim`` are:
#
# 1. :ref:`cor... | r
# are (in order) the occurrences of "coffee", "milk", "sugar" and "spoon" in
# the document. The length of the vector is the number of e | ntries in the
# dictionary. One of the main properties of the bag-of-words model is that it
# completely ignores the order |
quietguy675/website | mysite/settings.py | Python | bsd-3-clause | 3,208 | 0.001247 | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... | [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':... | 1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
|
undeath/joinmarket-clientserver | jmbitcoin/test/test_bip21.py | Python | gpl-3.0 | 6,062 | 0.00165 | import jmbitcoin as btc
import pytest
def test_bip21_decode():
# These should raise exception because of not being valid BIP21 URI's
with pytest.raises(ValueError):
btc.decode_bip21_uri('')
btc.decode_bip21_uri('nfdjksnfjkdsnfjkds')
btc.decode_bip21_uri('175tWpb8K1S7NmH4Zx6rewF9WQrcZv... | 'bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Luke-Jr'
)
# Use list of tuples version for multiple parameter tests, as dicts don't
# have guaranteed ordering.
assert(
btc.encode_bip21_uri('175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W', [
('amoun | t', 20.3),
('label', 'Luke-Jr')
]) ==
'bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=20.3&label=Luke-Jr'
)
assert(
btc.encode_bip21_uri('175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W', [
('amount', 50),
('label', 'Luke-Jr'),
('message', 'Donation ... |
Earthstar/double-d | streetfarer/views.py | Python | mit | 7,086 | 0.004375 | import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, r... | sername=username).count() == 1:
message = {
"status": "error",
"message": "Username already exists"
}
return message
password = request.POST["password"]
password_check = request.POST["passwordCheck"]
if password != password_chec... | "Password does not match"
}
return message
email = request.POST["email"]
User.objects.create_user(username=username, email=email, password=password)
user = authenticate(username=username, password=password)
login(request, user)
message = {
"st... |
Hexadorsimal/pynes | nes/processors/cpu/instructions/addressing_modes/immediate.py | Python | mit | 461 | 0 | from .addressing_mode import AddressingMode
class ImmediateAddressingMode(AddressingMode):
@property
def instruction_size(se | lf):
return 2
def calculate_address(self, processor, parameter):
raise RuntimeError('This should never be called')
def read_source(self, processor, parameter):
return pa | rameter
def write_result(self, processor, parameter, value):
raise RuntimeError('This should never be called')
|
cybojenix/projects_reward_system | cg4/wsgi.py | Python | apache-2.0 | 381 | 0.002625 | """
WSGI config for cg4 project.
It exposes the WSGI callable as a module-level variabl | e named ``application``.
For mor | e information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cg4.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
marmyshev/item_title | openlp/plugins/songs/forms/songmaintenanceform.py | Python | gpl-2.0 | 24,170 | 0.002483 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# ------------------------------------------------------... | horsForm(self)
self.topic_form = TopicsForm(self)
self.song_book_form = SongBookForm(self)
# Disable all edit and delete buttons, as there is no row selected.
self.delete_author_button.setEnabled(False)
self.edit_author_button.setEnabled(False)
self.delete_topic_button.se... | ls
self.add_author_button.clicked.connect(self.on_add_author_button_clicked)
self.add_topic_button.clicked.connect(self.on_add_topic_button_clicked)
self.add_book_button.clicked.connect(self.on_add_book_button_clicked)
self.edit_author_button.clicked.connect(self.on_edit_author_button_cl... |
KuKuKai/104asiajava | 509.py | Python | mit | 712 | 0.050562 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 19:32:49 2018
@author: JinJheng
"""
x,y=map(int,input().split(','))
m,n=map(int,input().split(','))
if n > y:
greater = n
else:
greater = y
while(True):
if((greater % n == 0) and (greater % y == 0)):
q = greater
break
... | m,end='')
print('/',end='')
pr | int(n,'=',int(p/ans),end='')
print('/',end='')
print(int(q/ans))
compute() |
kcartier/tensorflow-toe-in-the-water | tensorflow/python/kernel_tests/linalg_grad_test.py | Python | apache-2.0 | 3,516 | 0.012514 | """Tests for tensorflow.ops.linalg_grad."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
from tensorflow.python.kernel_tests import gradient_checker as gc
class MatrixInverse... |
size=np.prod(shape_)).reshape(shape_).astype(dtype_)
a = tf.constant(m)
epsilon = np.finfo(dtype_).eps
# Optimal stepsize for central difference is O(epsilon^{1/3}).
delta = epsilon**(1.0 / 3.0)
tol = 1e-3
if len(shape_) == 2:
ainv = tf.matrix_in... | ainv = tf.batch_matrix_inverse(a)
theoretical, numerical = gc.ComputeGradient(a,
shape_,
ainv,
shape_,
de... |
google-research/federated | distributed_dp/distributed_discrete_gaussian_query_test.py | Python | apache-2.0 | 6,913 | 0.009258 | # Copyright 2021, Google LLC. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | peError):
query_result, _ = test_utils.run_query(query, [record1, record2])
sess.run(query_result)
@parameterized.product(l2_norm_bound=[0, 3, 10, 14.1])
@silence_tf_error_messages
def test_sum_raise_on_l2_norm_excess(self, l2_norm_bound):
with self.cached_session() as sess:
record = tf... | query_result, _ = test_utils.run_query(query, [record])
sess.run(query_result)
def test_sum_float_norm_not_rounded(self):
"""Test that the float L2 norm bound doesn't get rounded/casted to integers."""
with self.cached_session() as sess:
# A casted/rounded norm bound would be insufficient.
... |
mancoast/CPythonPyc_test | cpython/251_test_strptime.py | Python | gpl-3.0 | 23,903 | 0.003598 | """PyUnit testing against strptime"""
import unittest
import time
import locale
import re
import sys
from test import test_support
from datetime import date as datetime_date
import _strptime
class getlang_Tests(unittest.TestCase):
"""Test _getlang"""
def test_basic(self):
self.failUnlessEqual(_strpti... | ting against full month name failed")
self.compare_against_time(self.LT_ins.a_month, '%b', 1,
"Testing against abbreviated month name failed")
def test_am_pm(self):
# Make sure AM/PM representation done properly
strftime_output = time.strftime("%p", self.ti... | "AM/PM representation not in tuple")
if self.time_tuple[3] < 12: position = 0
else: position = 1
self.failUnless(strftime_output == self.LT_ins.am_pm[position],
"AM/PM representation in the wrong position within the tuple")
def test_timezone(se... |
svebk/DeepSentiBank_memex | scripts/tests/deprecated/read_image_from_hbase.py | Python | bsd-2-clause | 875 | 0.008 | import happybase
fro | m StringIO import StringIO
from PIL import Image
def decode_image_PIL(binary_data):
""" Returns PIL image from bina | ry buffer.
"""
f = StringIO(binary_data)
img = Image.open(f)
return img
if __name__=="__main__":
tab_image = 'image_cache'
col_image = dict()
col_image['image_cache'] = 'image:binary'
conn = happybase.Connection(host='10.1.94.57')
image_rows = dict()
image_rows['image_cache'] =... |
kcrandall/Kaggle_Mercedes_Manufacturing | spark/experiements/jingning/experiment1.py | Python | mit | 13,439 | 0.011087 | # imports
import pandas as pd
import numpy as np
import time
import os
from tabulate import tabulate
import sys
from operator import add
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
from pyspark.sql import functions as F #https://stackoverflow.com/questions/3... | H2OContext.getOrCreate(spark,conf)
print('Making h2o frames...')
trainHF = hc.as_h2o_frame(train, "trainTable")
validHF = hc.as_h2o_frame(valid, "validTable")
testHF = hc.as_h2o_frame(test, "testTable")
print('Done making h2o frames.')
logger.log_string("Train Summary:")
logger.log_string("Rows:{}".format(trainHF.nr... | ))
# logger.log_string(tabulate(trainHF.summary(return_data=True),tablefmt="grid"))
# logger.log_string(trainHF._ex._cache._tabulate('grid',False))
base_train, stack_train = trainHF.split_frame([0.5], seed=12345)
base_valid, stack_valid = validHF.split_frame([0.5], seed=12345)
# def upload_submission(sub,predict_colu... |
chrislit/abydos | abydos/distance/_henderson_heron.py | Python | gpl-3.0 | 2,964 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | ----
>>> cmp = HendersonHeron()
>>> cmp.dist('cat', 'hat')
0.00011668873858680838
>>> cmp.dist('Niall', 'Neil')
0.00048123075776606097
>>> cmp.dist('aluminum', 'Catalan')
| 0.08534181060514882
>>> cmp.dist('ATCG', 'TAGC')
0.9684367974410505
.. versionadded:: 0.4.1
"""
self._tokenize(src, tar)
a = self._intersection_card()
ab = self._src_card()
ac = self._tar_card()
n = self._population_unique_card()
... |
RevansChen/online-judge | Codefights/arcade/python-arcade/level-2/12.Fix-Message/Python/test.py | Python | mit | 819 | 0 | # Python3
from solution1 import fixMessage as f
qa = [
("you'll NEVER believe what that 'FrIeNd' of mine did!!1",
"You'll never believe what that 'friend' of mine did!!1"),
('i',
'I'),
('We are so doomed.',
'We are so doomed.'),
("LOL you've GOT to hear this one XDD",
"Lol you've g... | absolutely nothing to do with it!"),
(':)',
':)')
]
for *q, a in qa:
for i, e in enumerate(q):
print('input{0}: {1}'.format(i + 1, e))
ans = f(*q)
if ans != a:
print(' [failed]')
print(' | output:', ans)
print(' expected:', a)
else:
print(' [ok]')
print(' output:', ans)
print()
|
geopython/QGIS | tests/src/python/test_qgslayoutmap.py | Python | gpl-2.0 | 16,013 | 0.000999 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutItemMap.
.. note:: 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.
"""
... | ap item with a label margin set
"""
format = QgsTextFormat()
format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
format.setSize(20)
format.setNamedStyle("Bold")
format.setColor(QColor(0, 0, 0))
settings = QgsPalLayerSettings()
settings.setFormat(forma... | ctorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory")
vl.setRenderer(QgsNullSymbolRenderer())
f = QgsFeature(vl.fields(), 1)
for x in range(15):
for y in range(15):
f.setGeometry(QgsPoint(x, y))
vl.dataProvider().addFeature(f)
vl.s... |
cliqz/socorro | socorro/unittest/external/fs/test_fs_new_crash_source.py | Python | mpl-2.0 | 1,839 | 0.003263 | # This Source Code Form is subject to the te | rms 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/.
from nose.tools import eq_, ok_
from socorro.external.fs.fs_new_crash_source import (
FSNewCrashSource
)
from socorro.lib.util import DotDict
from socorro.unittest.testbase import TestCase
#========... |
Torkvamedo/smx | project-chat/chatApp/management/commands/start_tornado.py | Python | unlicense | 701 | 0.008559 | from tornado.options import options, d | efine
import django.core.handlers.wsgi
import tornado.httpserver, tornado.ioloop
import tornado.web, tornado.wsgi
import chatApp.sockets
import sockjs.tornado
define('port', type=int, default=8888)
wsgi_app = tor | nado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())
tornado_app = tornado.web.Application(
sockjs.tornado.SockJSRouter(chatApp.sockets.SocketHandler, '/sockjs')
.urls + [('.*', tornado.web.FallbackHandler,dict(fallback=wsgi_app)),])
server = tornado.httpserver.HTTPServer(tornado_... |
UoMCS/Perentie | view/placeholder.py | Python | gpl-3.0 | 1,235 | 0.048583 | #!/usr/bin/env python
"""
A GTK+ widget wh | ich can be used to fill space where a widget is unavailable, for
example if a system doesn't have a memory, this can be shown in its place in a
memory window.
"""
import gtk, gobject
class Placeholder(gtk.Alignment):
def __init__(self, title, body = None, stock_icon_id = gtk.STOCK_DIALOG_INFO):
"""
Draws an ... | ment.__init__(self, 0.5, 0.5)
self.title = title
self.body = body or ""
self.stock_icon_id = stock_icon_id
self.vbox = gtk.VBox(spacing = 15)
self.vbox.set_border_width(15)
self.add(self.vbox)
self.icon = gtk.Image()
self.icon.set_from_stock(self.stock_icon_id, gtk.ICON_SIZE_DI... |
OGKevin/ComBunqWebApp | apiwrapper/endpoints/request_inquiry.py | Python | mit | 2,898 | 0 | from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.monetary_account import MonetaryAccount
class RequestInquiry(Endpoint):
__endpoint_request_inquiry = "request-inquiry"
__endpoint_request_inquiry_batch = "request-inquiry-batch"
__endpoint_request_response = "request-response"
... | t(endpoint)
# Request Response Logic
def get_all_request_responses_for_account(self, user_id, account_id):
endpoint = self._get_base_endpoint(user_id, account_id)
endpo | int += "/%s" % self.__endpoint_request_response
return self._make_get_request(endpoint)
def get_request_response_by_id(self, user_id, account_id, response_id):
endpoint = self._get_base_endpoint(user_id, account_id)
endpoint += "/%s/%d" % (self.__endpoint_request_response, response_id)
... |
twilio/twilio-python | tests/integration/voice/v1/test_byoc_trunk.py | Python | mit | 8,787 | 0.003073 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ByocTrunkTestCase(Integra... | ' | https://voice.twilio.com/v1/ByocTrunks/BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_update_response(self):
self.holodeck.mock(Response(
200,
'''
{
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"sid": "BYaaaaaaaaaaaaaaaaa... |
instana/python-sensor | bin/create_general_release.py | Python | mit | 1,486 | 0.001346 | #!/usr/bin/env python
# (c) Copyright IBM Corp. 2021
# (c) Copyright Insta | na Inc. 2020
# Script to make a new python-sensor release on Github
# Requires the Github CLI to be installed and configured: https://github.com/cli/cli
import os
import sys
import distutils.spawn
from subprocess import check_output
if len(sys.argv) | != 2:
raise ValueError('Please specify the version to release. e.g. "1.27.1"')
if sys.argv[1] in ['-h', '--help']:
filename = os.path.basename(__file__)
print("Usage: %s <version number>" % filename)
print("Exampe: %s 1.27.1" % filename)
print("")
print("This will create a release on Github su... |
raychorn/openstack-dashboard-sample | horizon/openstack_dashboard/dashboards/dashboardname/panel1/tabs.py | Python | gpl-3.0 | 877 | 0.00114 | # vim: | tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# ... |
Damangir/Registry-Management | src/stream_reader/__init__.py | Python | gpl-2.0 | 40 | 0.025 | from long_format impor | t LongFormatReader | |
pythad/nider | examples/draw_on_texture_example/script.py | Python | mit | 1,593 | 0.000628 | from nider.core import Font
from nider.core import Outline
from nider.models import Header
from nider.models import Paragraph
from nider.models import Linkback
from nider.models import Content
from nider.models import TwitterPost
# TODO: change this fontpath to the fontpath on your machine
roboto_font_folder = '/hom... | henderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.',
font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 29),
text_width=65,
align='left',
color='#ededed'
)
linkback = Linkback(text='foo.com | @username',
| font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 24),
color='#ededed'
)
content = Content(para, header, linkback)
img = TwitterPost(content,
fullpath='result.png'
)
# TODO: change this texture path to the texture path on your m... |
minlexx/pyevemon | esi_client/models/get_universe_regions_region_id_not_found.py | Python | gpl-3.0 | 3,034 | 0.00033 | # coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.4.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class GetUniverseRegionsRegionIdNotFound(object):
"""
NO... | result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, o... | turn self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
sivas2811/mocha_739 | mocha/mocha/settings.py | Python | unlicense | 2,537 | 0.002365 | """
Django settings for mocha project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
impo... | 5)60toxze=i7z9&%ia4rjrcyqv@(xbwvia-rm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.ap... | ib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mocha_models',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.