commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
e6d6b39a2ec03c992f450fd99b42122bc5d9249f | aospy/test/test_objs/runs.py | aospy/test/test_objs/runs.py | from aospy.run import Run
test_am2 = Run(
name='test_am2',
description=(
'Preindustrial control simulation.'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_en... | from aospy.run import Run
test_am2 = Run(
name='test_am2',
description=(
'Preindustrial control simulation.'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_en... | TEST Add 'ps' variable to idealized run | TEST Add 'ps' variable to idealized run
| Python | apache-2.0 | spencerkclark/aospy,spencerahill/aospy | ---
+++
@@ -24,5 +24,5 @@
'gfdl.ncrc2-default-prod/1x0m720d_32pe/history',
data_in_dir_struc='one_dir',
data_in_files={'20-day': {v: '00000.1x20days.nc'
- for v in ['olr', 'temp']}},
+ for v in ['olr', 'temp', 'ps']}},
) |
ee93f680c911f6879e12f7ce7ee3a6c1cfda8379 | app/taskqueue/tasks/stats.py | app/taskqueue/tasks/stats.py | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... | Add missing function doc string. | Add missing function doc string.
| Python | lgpl-2.1 | kernelci/kernelci-backend,kernelci/kernelci-backend | ---
+++
@@ -23,6 +23,7 @@
@taskc.app.task(
name="calculate-daily-statistics", ack_late=True, track_started=True)
def calculate_daily_statistics():
+ """Collect daily statistics on the data stored."""
db_options = taskc.app.conf.DB_OPTIONS
daily_stats = utils.stats.daily.calculate_daily_stats(db_op... |
4be85164344defc9d348594a26c4dab147a8de4a | dvol/test_plugin.py | dvol/test_plugin.py | """
log of integration tests to write:
write test_switch_branches_restarts_containers
command:
docker-compose up -d (in a directory with appropriate docker-compose.yml file)
expected behaviour:
docker containers are started with dvol accordingly
XXX this doesn't seem to work at the moment
command:
do... | """
log of integration tests to write:
write test_switch_branches_restarts_containers
command:
docker-compose up -d (in a directory with appropriate docker-compose.yml file)
expected behaviour:
docker containers are started with dvol accordingly
command:
docker run -ti --volume-driver dvol -v hello:/data... | Tidy up list of tests to write. | Tidy up list of tests to write.
| Python | apache-2.0 | ClusterHQ/dvol,ClusterHQ/dvol,ClusterHQ/dvol | ---
+++
@@ -7,12 +7,11 @@
docker-compose up -d (in a directory with appropriate docker-compose.yml file)
expected behaviour:
docker containers are started with dvol accordingly
- XXX this doesn't seem to work at the moment
command:
docker run -ti --volume-driver dvol -v hello:/data busybox sh
e... |
a7311b1cd9a184af2a98130ba288157f62220da1 | src/formatter.py | src/formatter.py | import json
from collections import OrderedDict
from .command import ShellCommand
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command=None, args=None, formatter=None):
self.__name = name
self.__format = formatter
self.__settings = FormatterSettings(n... | import json
from collections import OrderedDict
from .command import ShellCommand
from .settings import FormatterSettings
class Formatter():
def __init__(self, name, command='', args='', formatter=None):
self.__name = name
self.__settings = FormatterSettings(name.lower())
if formatter:
... | Set default values for command and args | Set default values for command and args
| Python | mit | Rypac/sublime-format | ---
+++
@@ -5,15 +5,15 @@
class Formatter():
- def __init__(self, name, command=None, args=None, formatter=None):
+ def __init__(self, name, command='', args='', formatter=None):
self.__name = name
- self.__format = formatter
self.__settings = FormatterSettings(name.lower())
-
- ... |
e8a0e7c3714445577851c5a84ecf7a036937725a | clang_corpus/__init__.py | clang_corpus/__init__.py | from os import listdir
from os.path import abspath, isfile, join, splitext
# C, C++, Obj-C, & Obj-C++
SOURCE_EXTENSIONS = ('.h', '.hh', '.hpp', '.c', '.cpp', '.cxx', '.m', '.mm')
class SourceFile(object):
""" A simple object which wraps a text file.
"""
def __init__(self, path):
self._path = absp... | from os import listdir
from os.path import abspath, isfile, join, split, splitext
# C, C++, Obj-C, & Obj-C++
SOURCE_EXTENSIONS = ('.h', '.hh', '.hpp', '.c', '.cpp', '.cxx', '.m', '.mm')
class SourceFile(object):
""" A simple object which wraps a text file.
"""
def __init__(self, path):
self._path... | Add an include_paths property to the SourceFile class. | Add an include_paths property to the SourceFile class.
| Python | unlicense | jwiggins/clang-corpus,jwiggins/clang-corpus,jwiggins/clang-corpus | ---
+++
@@ -1,5 +1,5 @@
from os import listdir
-from os.path import abspath, isfile, join, splitext
+from os.path import abspath, isfile, join, split, splitext
# C, C++, Obj-C, & Obj-C++
SOURCE_EXTENSIONS = ('.h', '.hh', '.hpp', '.c', '.cpp', '.cxx', '.m', '.mm')
@@ -14,6 +14,10 @@
@property
def path(s... |
2402afe296191d3fddc98212564fb0158cfdcb51 | upload_redirects.py | upload_redirects.py | import json
from backend.app import app, db
from backend.models import *
from flask import url_for
# read in json redirect dump
with open('data/prod_url_alias.json', 'r') as f:
redirects = json.loads(f.read())
print len(redirects)
old_urls = []
error_count = 0
for i in range(len(redirects)):
nid = None
... | import json
from backend.app import app, db
from backend.models import *
from flask import url_for
# read in json redirect dump
with open('data/nid_url.json', 'r') as f:
redirects = json.loads(f.read())
print len(redirects)
old_urls = []
existing_redirects = Redirect.query.all()
for redirect in existing_redirec... | Check for duplicates in existing dataset. Fix reference to dump file. | Check for duplicates in existing dataset. Fix reference to dump file.
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 | ---
+++
@@ -4,13 +4,17 @@
from flask import url_for
# read in json redirect dump
-with open('data/prod_url_alias.json', 'r') as f:
+with open('data/nid_url.json', 'r') as f:
redirects = json.loads(f.read())
print len(redirects)
old_urls = []
+existing_redirects = Redirect.query.all()
+for redirect in... |
1a761c9360f185d6bd07be9f16ea2cfa239f4bdd | groupy/api/base.py | groupy/api/base.py | from groupy import utils
class Manager:
"""Class for interacting with the endpoint for a resource.
:param session: the requests session
:type session: :class:`~groupy.session.Session`
:param str path: path relative to the base URL
"""
#: the base URL
base_url = 'https://api.groupme.com/v... | from groupy import utils
class Manager:
"""Class for interacting with the endpoint for a resource.
:param session: the requests session
:type session: :class:`~groupy.session.Session`
:param str path: path relative to the base URL
"""
#: the base URL
base_url = 'https://api.groupme.com/v... | Fix pickling/unpickling of Resource objects | Fix pickling/unpickling of Resource objects
Add __getstate__ and __setstate__ methods to the Resource class to avoid hitting the recursion limit when trying to pickle/unpickle Resource objects.
A similar issue/solution can be found here: https://stackoverflow.com/a/12102691
| Python | apache-2.0 | rhgrant10/Groupy | ---
+++
@@ -28,6 +28,12 @@
attr))
return self.data[attr]
+ def __getstate__(self):
+ return self.__dict__
+
+ def __setstate__(self, d):
+ self.__dict__.update(d)
+
class ManagedResource(Resource):
"""Class to represent an A... |
8626733d3a4960013189ffa90fe8e496dd8cc90a | calexicon/constants.py | calexicon/constants.py | from datetime import date as vanilla_date
from dates.base import BasicBCEDate
first_julian_date = BasicBCEDate(-45, 1, 1)
first_vanilla_date = vanilla_date(1, 1, 1)
last_vanilla_date = vanilla_date(9999, 12, 31)
julian_day_number_of_first_vanilla_date = 1721423
julian_day_number_of_last_vanilla_date = (
julian_d... | from datetime import date as vanilla_date
from dates.base import BasicBCEDate
first_julian_date = BasicBCEDate(-45, 1, 1)
first_vanilla_date = vanilla_date(1, 1, 1)
last_vanilla_date = vanilla_date(9999, 12, 31)
julian_day_number_of_first_vanilla_date = 1721423
julian_day_number_of_last_vanilla_date = (
julian_d... | Add another constant for the number of vanilla dates. | Add another constant for the number of vanilla dates.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -11,3 +11,5 @@
julian_day_number_of_first_vanilla_date
+ (last_vanilla_date - first_vanilla_date).days
)
+
+number_of_vanilla_dates = (last_vanilla_date - first_vanilla_date).days |
195f4d25bdf30f355d029697675481ba3193ad77 | gatt/gatt.py | gatt/gatt.py | import os
import platform
if platform.system() == 'Darwin':
if os.environ.get('LINUX_WITHOUT_DBUS', '0') == '0':
from .gatt_linux import *
else:
from .gatt_stubs import *
else:
# TODO: Add support for more platforms
from .gatt_stubs import *
| import os
import platform
if platform.system() == 'Linux':
if os.environ.get('LINUX_WITHOUT_DBUS', '0') == '0':
from .gatt_linux import *
else:
from .gatt_stubs import *
else:
# TODO: Add support for more platforms
from .gatt_stubs import *
| Fix testing for wrong platform name | Fix testing for wrong platform name | Python | mit | getsenic/gatt-python | ---
+++
@@ -1,7 +1,7 @@
import os
import platform
-if platform.system() == 'Darwin':
+if platform.system() == 'Linux':
if os.environ.get('LINUX_WITHOUT_DBUS', '0') == '0':
from .gatt_linux import *
else: |
67717116a2585975e0e773956d6a102be9dc11d6 | ggplot/geoms/geom_boxplot.py | ggplot/geoms/geom_boxplot.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from .geom import geom
from ggplot.utils import is_string
from ggplot.utils import is_categorical
class g... | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from .geom import geom
from ggplot.utils import is_string
from ggplot.utils import is_categorical
class g... | Fix y axis tick labels for boxplot | Fix y axis tick labels for boxplot
| Python | bsd-2-clause | xguse/ggplot,benslice/ggplot,smblance/ggplot,Cophy08/ggplot,mizzao/ggplot,xguse/ggplot,ricket1978/ggplot,mizzao/ggplot,andnovar/ggplot,bitemyapp/ggplot,kmather73/ggplot,udacity/ggplot,ricket1978/ggplot,benslice/ggplot,wllmtrng/ggplot,assad2012/ggplot | ---
+++
@@ -31,9 +31,11 @@
g = self.__group(x,y)
l = sorted(g.keys())
x = [g[k] for k in l]
- plt.setp(ax, yticklabels=l)
q = ax.boxplot(x, vert=False)
plt.setp(q['boxes'], color=color)
plt.setp(q['whiskers'], color=color)
plt.set... |
468e2369a2b1af203d8a00abbfb3b01af26ae89a | bot/multithreading/worker.py | bot/multithreading/worker.py | import queue
from bot.multithreading.work import Work
class Worker:
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class AbstractWorker(Worker):
def __init__(self, name: str... | import queue
from bot.multithreading.work import Work
class Worker:
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class AbstractWorker(Worker):
def __init__(self, name: str... | Create a ImmediateWorker that executes the posted jobs on the same thread synchronously | Create a ImmediateWorker that executes the posted jobs on the same thread synchronously
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -57,3 +57,17 @@
def shutdown(self):
self.queue.join()
+
+
+class ImmediateWorker(AbstractWorker):
+ def __init__(self, error_handler: callable):
+ super().__init__("immediate", error_handler)
+
+ def run(self):
+ pass
+
+ def post(self, work: Work):
+ self._wor... |
423288b4cc8cf1506285913558b3fcff9e7788fa | gitlab/urls.py | gitlab/urls.py | from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from gitlab import views
urlpatterns = patterns('',
url(r'^favicon\.ico$', RedirectView.as_view(url='/static/app/favicon.ico')),
url(r'^push_event/hv$', views.push_event_hv),
url(r'^push_event/web$', views.push_e... | from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from gitlab import views
urlpatterns = patterns('',
url(r'^favicon\.ico$', RedirectView.as_view(url='/static/app/favicon.ico')),
url(r'^push_event/hv$', views.push_event_hv),
url(r'^push_event/web$', views.push_e... | Add URL for monitoring hook | Add URL for monitoring hook | Python | apache-2.0 | ReanGD/web-work-fitnesse,ReanGD/web-work-fitnesse,ReanGD/web-work-fitnesse | ---
+++
@@ -6,5 +6,6 @@
urlpatterns = patterns('',
url(r'^favicon\.ico$', RedirectView.as_view(url='/static/app/favicon.ico')),
url(r'^push_event/hv$', views.push_event_hv),
- url(r'^push_event/web$', views.push_event_web)
+ url(r'^push_event/web$', views.push_event_web),
+ url(r'^push_event/monit... |
2f9be950c372beb2f555cbe84a22366e0b95e721 | hellopy/bot.py | hellopy/bot.py | from wit import Wit
from . import text_to_speech as tts
from . import config
WIT_AI_KEY = config.WIT_AI_KEY
session_id = config.USER
def say(session_id, context, msg):
tts.talk(msg)
def error(session_id, context, e):
# tts.talk("Algo salió mal.")
print(str(e))
def merge(session_id, context, entities... | from wit import Wit
import shutil
import subprocess
import time
from . import text_to_speech as tts
from . import config
WIT_AI_KEY = config.WIT_AI_KEY
session_id = config.USER
def say(session_id, context, msg):
print("HelloPy: " + msg)
tts.talk(msg)
def error(session_id, context, e):
# tts.talk("Algo... | Add functions: mute & open | Add functions: mute & open
| Python | mit | stsewd/hellopy | ---
+++
@@ -1,4 +1,7 @@
from wit import Wit
+import shutil
+import subprocess
+import time
from . import text_to_speech as tts
from . import config
@@ -8,6 +11,7 @@
def say(session_id, context, msg):
+ print("HelloPy: " + msg)
tts.talk(msg)
@@ -16,7 +20,21 @@
print(str(e))
+def first_en... |
f6bf104cbdcdb909a15c80dafe9ae2e7aebbc2f0 | examples/snowball_stemmer_example.py | examples/snowball_stemmer_example.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
from nltk import word_tokenize
stemmer = HungarianStemmer()
test_sentence = "Szeretnék kérni tőled egy óriási szívességet az édesanyám számára."
tokenized_sentence = word_tokenize(test_se... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
from nltk import word_tokenize
stemmer = HungarianStemmer()
test_sentence = "Péter szereti Enikőt és Marit"
tokenized_sentence = word_tokenize(test_sentence)
print('With SnowballStemmer... | Add more information to SnowballStemmer | Add more information to SnowballStemmer
| Python | apache-2.0 | davidpgero/hungarian-nltk | ---
+++
@@ -5,15 +5,12 @@
from nltk.stem.snowball import HungarianStemmer
from nltk import word_tokenize
+
stemmer = HungarianStemmer()
-test_sentence = "Szeretnék kérni tőled egy óriási szívességet az édesanyám számára."
+test_sentence = "Péter szereti Enikőt és Marit"
tokenized_sentence = word_tokenize(test... |
3e1b2b5e87f2d0ed8ecb06b07805723101c23636 | km3pipe/tests/test_config.py | km3pipe/tests/test_config.py | # coding=utf-8
# Filename: test_config.py
"""
Test suite for configuration related functions and classes.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.testing import TestCase, BytesIO
from km3pipe.config import Config
CONFIGURATION = BytesIO("\n".join((
"[DB]",
"username... | # coding=utf-8
# Filename: test_config.py
"""
Test suite for configuration related functions and classes.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.testing import TestCase, StringIO
from km3pipe.config import Config
CONFIGURATION = StringIO("\n".join((
"[DB]",
"userna... | Switch to StringIO for fake config data | Switch to StringIO for fake config data
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -6,11 +6,11 @@
"""
from __future__ import division, absolute_import, print_function
-from km3pipe.testing import TestCase, BytesIO
+from km3pipe.testing import TestCase, StringIO
from km3pipe.config import Config
-CONFIGURATION = BytesIO("\n".join((
+CONFIGURATION = StringIO("\n".join((
"[DB]... |
28c898c39515601b3ed0379cd3721f47e019ef65 | common/lib/xmodule/xmodule/tests/test_conditional_logic.py | common/lib/xmodule/xmodule/tests/test_conditional_logic.py | # -*- coding: utf-8 -*-
"""Test for Conditional Xmodule functional logic."""
from xmodule.conditional_module import ConditionalDescriptor
from . import LogicTest
class ConditionalModuleTest(LogicTest):
"""Logic tests for Conditional Xmodule."""
descriptor_class = ConditionalDescriptor
def test_ajax_requ... | # -*- coding: utf-8 -*-
"""Test for Conditional Xmodule functional logic."""
from xmodule.conditional_module import ConditionalDescriptor
from . import LogicTest
class ConditionalModuleTest(LogicTest):
"""Logic tests for Conditional Xmodule."""
descriptor_class = ConditionalDescriptor
def test_ajax_requ... | Correct spelling in a comment | Correct spelling in a comment
| Python | agpl-3.0 | EDUlib/edx-platform,10clouds/edx-platform,chand3040/cloud_that,DefyVentures/edx-platform,vismartltd/edx-platform,zerobatu/edx-platform,ubc/edx-platform,eduNEXT/edx-platform,cpennington/edx-platform,jazztpt/edx-platform,Lektorium-LLC/edx-platform,Kalyzee/edx-platform,nttks/edx-platform,longmen21/edx-platform,chudaol/edx... | ---
+++
@@ -10,7 +10,7 @@
descriptor_class = ConditionalDescriptor
def test_ajax_request(self):
- "Make shure that ajax request works correctly"
+ "Make sure that ajax request works correctly"
# Mock is_condition_satisfied
self.xmodule.is_condition_satisfied = lambda: True
... |
0225a79fa43f03a48a6134fce4122ae243a10df2 | ptt_preproc_to_target.py | ptt_preproc_to_target.py | #!/usr/bin/env python
import json
from pathlib import Path
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
txt_path = _TARGET... | #!/usr/bin/env python
import json
from pathlib import Path
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets/')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
txt_path = _TARGE... | Put / after dir path | Put / after dir path
| Python | mit | moskytw/mining-news | ---
+++
@@ -8,7 +8,7 @@
l = ptt_core.l
-_TARGETS_DIR_PATH = Path('targets')
+_TARGETS_DIR_PATH = Path('targets/')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir() |
2a8dd80c9769731963fcd75cb24cd8918e48b269 | mythril/analysis/security.py | mythril/analysis/security.py | from mythril.analysis.report import Report
from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas
def fire_lasers(statespace):
issues = []
issues += delegatecall_forward.execute(statespace)
issues += delegat... | from mythril.analysis.report import Report
from mythril.analysis import modules
import pkgutil
def fire_lasers(statespace):
issues = []
_modules = []
for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__):
_modules.append(loader.find_module(name).load_module(name))
for modu... | Implement a nicer way of execution modules | Implement a nicer way of execution modules
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | ---
+++
@@ -1,19 +1,19 @@
from mythril.analysis.report import Report
-from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas
+from mythril.analysis import modules
+import pkgutil
def fire_lasers(statespace)... |
dbb27799a92e58cf03a9b60c17e0f3116fbcf687 | modish/__init__.py | modish/__init__.py | # -*- coding: utf-8 -*-
from .model import ModalityModel
from .estimator import ModalityEstimator
from .visualize import MODALITY_TO_COLOR, MODALITY_ORDER, MODALITY_PALETTE,\
MODALITY_TO_CMAP, ModalitiesViz, violinplot
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
__a... | # -*- coding: utf-8 -*-
from .model import ModalityModel
from .estimator import ModalityEstimator
from .visualize import MODALITY_TO_COLOR, MODALITY_ORDER, MODALITY_PALETTE,\
MODALITY_TO_CMAP, ModalitiesViz, violinplot, barplot
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1... | Add object for saving modish test results | Add object for saving modish test results
| Python | bsd-3-clause | olgabot/anchor,olgabot/modish,YeoLab/anchor | ---
+++
@@ -2,7 +2,7 @@
from .model import ModalityModel
from .estimator import ModalityEstimator
from .visualize import MODALITY_TO_COLOR, MODALITY_ORDER, MODALITY_PALETTE,\
- MODALITY_TO_CMAP, ModalitiesViz, violinplot
+ MODALITY_TO_CMAP, ModalitiesViz, violinplot, barplot
__author__ = 'Olga Botvinnik'
... |
ab4333ad10713b0df25e0ff9bb46da3a0749326f | analyser/tasks.py | analyser/tasks.py | import os
import time
import requests
from krunchr.vendors.celery import celery
@celery.task
def get_file(url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
print path
with open(path, 'w') as f:
f.write(respo... | import os
import time
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
with open(path... | Update job state when we finish the task | Update job state when we finish the task
| Python | apache-2.0 | vtemian/kruncher | ---
+++
@@ -1,19 +1,23 @@
import os
import time
+import rethinkdb as r
import requests
-from krunchr.vendors.celery import celery
+from krunchr.vendors.celery import celery, db
-@celery.task
-def get_file(url, path):
+@celery.task(bind=True)
+def get_file(self, url, path):
name, ext = os.path.splitext(u... |
28c26bf5d220a5a60b807470bbaf339bdf9206a9 | pylearn2/testing/skip.py | pylearn2/testing/skip.py | """
Helper functions for determining which tests to skip.
"""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
from nose.plugins.skip import SkipT... | """
Helper functions for determining which tests to skip.
"""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
from nose.plugins.skip import SkipT... | Add SkipTest for when matplotlib and/or pyplot are not present | Add SkipTest for when matplotlib and/or pyplot are not present
| Python | bsd-3-clause | CIFASIS/pylearn2,lisa-lab/pylearn2,msingh172/pylearn2,w1kke/pylearn2,lamblin/pylearn2,bartvm/pylearn2,sandeepkbhat/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,mkraemer67/pylearn2,jamessergeant/pylearn2,junbochen/pylearn2,TNick/pylearn2,hantek/pylearn2,nouiz/pylearn2,aalmah/pylearn2,skearnes/pylearn2,kose-y/pylea... | ---
+++
@@ -31,22 +31,38 @@
except ImportError:
h5py_works = False
+matplotlib_works = True
+try:
+ from matplotlib import pyplot
+except ImportError:
+ matplotlib_works = False
+
+
def skip_if_no_data():
if 'PYLEARN2_DATA_PATH' not in os.environ:
raise SkipTest()
+
def skip_if_no_scip... |
817aa49dc7abc73863560c510cd81a2fad8f854b | python/servo/packages.py | python/servo/packages.py | # 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/.
WINDOWS_MSVC = {
"cmake": "3.7.2",
"llvm": "7.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"openssl":... | # 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/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "7.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"openssl"... | Update cmake for MSVC builds. | Update cmake for MSVC builds. | Python | mpl-2.0 | emilio/servo,saneyuki/servo,KiChjang/servo,DominoTree/servo,pyfisch/servo,splav/servo,KiChjang/servo,emilio/servo,splav/servo,emilio/servo,paulrouget/servo,larsbergstrom/servo,notriddle/servo,DominoTree/servo,nnethercote/servo,saneyuki/servo,paulrouget/servo,KiChjang/servo,saneyuki/servo,nnethercote/servo,DominoTree/se... | ---
+++
@@ -3,7 +3,7 @@
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
- "cmake": "3.7.2",
+ "cmake": "3.14.3",
"llvm": "7.0.0",
"moztools": "3.2",
"ninja": "1.7.1", |
1212d33d849155f8c1cdc6a610e893318937e7c5 | silk/webdoc/html/v5.py | silk/webdoc/html/v5.py |
"""Module containing only html v5 tags. All deprecated tags have been removed.
"""
from .common import *
del ACRONYM
del APPLET
del BASEFONT
del BIG
del CENTER
del DIR
del FONT
del FRAME
del FRAMESET
del NOFRAMES
del STRIKE
del TT
del U
|
"""
Module containing only html v5 tags. All deprecated tags have been removed.
"""
from .common import ( # flake8: noqa
A,
ABBR,
# ACRONYM,
ADDRESS,
# APPLET,
AREA,
B,
BASE,
# BASEFONT,
BDO,
# BIG,
BLOCKQUOTE,
BODY,
BR,
BUTTON,
Body,
CAPTION,
C... | Replace import * with explicit names | Replace import * with explicit names
| Python | bsd-3-clause | orbnauticus/silk | ---
+++
@@ -1,19 +1,113 @@
-"""Module containing only html v5 tags. All deprecated tags have been removed.
+"""
+Module containing only html v5 tags. All deprecated tags have been removed.
"""
-from .common import *
-
-del ACRONYM
-del APPLET
-del BASEFONT
-del BIG
-del CENTER
-del DIR
-del FONT
-del FRAME
-del ... |
0c8835bb4ab1715ee0de948d9b15a813752b60b5 | dthm4kaiako/gunicorn.conf.py | dthm4kaiako/gunicorn.conf.py | """Configuration file for gunicorn."""
# Details from https://cloud.google.com/appengine/docs/flexible/python/runtime
worker_class = "gevent"
forwarded_allow_ips = "*"
secure_scheme_headers = {"X-APPENGINE-HTTPS": "on"}
| """Configuration file for gunicorn."""
from multiprocessing import cpu_count
# Worker count from http://docs.gunicorn.org/en/stable/design.html#how-many-workers
workers = cpu_count() * 2 + 1
# Details from https://cloud.google.com/appengine/docs/flexible/python/runtime
worker_class = "gevent"
forwarded_allow_ips = "*... | Increase number of server workers | Increase number of server workers
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,5 +1,9 @@
"""Configuration file for gunicorn."""
+from multiprocessing import cpu_count
+
+# Worker count from http://docs.gunicorn.org/en/stable/design.html#how-many-workers
+workers = cpu_count() * 2 + 1
# Details from https://cloud.google.com/appengine/docs/flexible/python/runtime
worker_class =... |
40e9375f6b35b4a05ad311822705b7a7efe46b56 | site_scons/get_libs.py | site_scons/get_libs.py | import os
import sys
from SCons.Script import File
from path_helpers import path
def get_lib_paths():
if sys.platform == 'win32':
lib_paths = set(os.environ['PATH'].split(';'))
else:
lib_paths = set()
if os.environ.has_key('LIBRARY_PATH'):
lib_paths.update(os.environ['LIB... | import os
import sys
from SCons.Script import File
from path_helpers import path
def get_lib_paths():
if sys.platform == 'win32':
lib_paths = set(os.environ['PATH'].split(';'))
else:
lib_paths = set()
if os.environ.has_key('LIBRARY_PATH'):
lib_paths.update(os.environ['LIB... | Add Linux 32-bit search path for Boost libraries | Add Linux 32-bit search path for Boost libraries
| Python | bsd-3-clause | wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware,wheeler-microfluidics/dmf-control-board-firmware | ---
+++
@@ -15,8 +15,9 @@
lib_paths.update(os.environ['LIBRARY_PATH'].split(':'))
if os.environ.has_key('LD_LIBRARY_PATH'):
lib_paths.update(os.environ['LD_LIBRARY_PATH'].split(':'))
- lib_paths = (['/usr/lib', '/usr/lib/x86_64-linux-gnu',
- '/usr/local/l... |
90d8411412b79513338b014da63b18d0d29396d9 | snmpy/log_processor.py | snmpy/log_processor.py | import re, snmpy_plugins
class log_processor:
def __init__(self, conf):
self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])]
self.proc(conf['logfile'])
def len(self):
return len(self.... | import re
import snmpy
class log_processor(snmpy.plugin):
def __init__(self, conf, script=False):
snmpy.plugin.__init__(self, conf, script)
def key(self, idx):
return 'string', self.data[idx - 1]['label']
def val(self, idx):
return 'integer', self.data[idx - 1]['value']
def w... | Convert to use the base class and update for new plugin path. | Convert to use the base class and update for new plugin path.
| Python | mit | mk23/snmpy,mk23/snmpy | ---
+++
@@ -1,12 +1,9 @@
-import re, snmpy_plugins
+import re
+import snmpy
-class log_processor:
- def __init__(self, conf):
- self.data = [{'value':0, 'label': conf['objects'][item]['label'], 'regex': re.compile(conf['objects'][item]['regex'])} for item in sorted(conf['objects'])]
- self.proc(con... |
34330aec6cf0c038d47c43ef926fa615bd568ea3 | sqlservice/__init__.py | sqlservice/__init__.py | # -*- coding: utf-8 -*-
"""The sqlservice package.
"""
from .__pkg__ import (
__description__,
__url__,
__version__,
__author__,
__email__,
__license__
)
from .client import SQLClient
from .model import ModelBase, declarative_base
from .query import Query
from .service import SQLService
| # -*- coding: utf-8 -*-
"""The sqlservice package.
"""
from .__pkg__ import (
__description__,
__url__,
__version__,
__author__,
__email__,
__license__
)
from .client import SQLClient
from .model import ModelBase, declarative_base
from .service import SQLService
from . import event
| Remove Query from import and add explicit event module import. | Remove Query from import and add explicit event module import.
| Python | mit | dgilland/sqlservice | ---
+++
@@ -13,5 +13,5 @@
from .client import SQLClient
from .model import ModelBase, declarative_base
-from .query import Query
from .service import SQLService
+from . import event |
b61ded5a1f59eca7838219d9e904941bd04aa064 | lib/euedb.py | lib/euedb.py | #!/usr/bin/python
# -*- coding: <encoding name> -*-
import os
import sys
import time
import re
import MySQLdb
from MySQLdb import cursors
class mysql:
cn = None
host = None
port = None
user = None
passw = None
def __init__(self, host, user, passw, db, port=3306):
self.port = port
... | #!/usr/bin/python
# -*- coding: <encoding name> -*-
import os
import sys
import time
import re
import MySQLdb
from MySQLdb import cursors
class mysql:
cn = None
host = None
port = None
user = None
passw = None
connected = False
def __init__(self, host, user, passw, db, port=3306):
... | Add better connection management ... | Add better connection management ...
| Python | agpl-3.0 | david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng | ---
+++
@@ -18,6 +18,8 @@
user = None
passw = None
+ connected = False
+
def __init__(self, host, user, passw, db, port=3306):
self.port = port
self.host = host
@@ -25,24 +27,33 @@
self.passw = passw
self.db = db
if not self.connect():
- retu... |
9c24dfc6a6207c9688332a16ee1600b73aec44d8 | narcis/urls.py | narcis/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
from . import views
from projects.views import screenshot
urlpatterns = patterns('',
# Examples:
# url(r'^blog/', inclu... | from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
from . import views
from projects.views import screenshot
urlpatterns = patterns('',
# Examples:
# url(r'^blog/', inclu... | Add URL for django admin access to screenshots | Add URL for django admin access to screenshots
| Python | mit | deckar01/narcis,deckar01/narcis,deckar01/narcis | ---
+++
@@ -18,5 +18,6 @@
url(r'^projects/', include('projects.urls')),
# Access controlled screenshot images
+ url(r'^{0}[0-9]+/[0-9]+/[0-9]+/(?P<id>[0-9a-f\-]+)'.format(settings.PRIVATE_SCREENSHOT_URL.lstrip('/')), screenshot),
url(r'^{0}(?P<id>[0-9a-f\-]+)'.format(settings.PRIVATE_SCREENSHOT_UR... |
94c0c60172c1114d6f0938de88af67ae7203ae95 | pi_setup/system.py | pi_setup/system.py | #!/usr/bin/env python
import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "instal... | #!/usr/bin/env python
import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "instal... | Add python to install script | Add python to install script
| Python | mit | projectweekend/Pi-Setup,projectweekend/Pi-Setup | ---
+++
@@ -7,6 +7,7 @@
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
+ subprocess.call(["apt-get", "-y", "install", "ipython-notebook"])
subprocess.call(["apt-get", "-y", "in... |
9d3750881eaa215f6d06087e6d0f7b6d223c3cd1 | feincms3/plugins/richtext.py | feincms3/plugins/richtext.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _
from content_editor.admin import ContentEditorInli... | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _
from content_editor.admin import ContentEditorInli... | Document the rich text plugin | Document the rich text plugin
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 | ---
+++
@@ -11,11 +11,29 @@
from feincms3.cleanse import CleansedRichTextField
-__all__ = ('CleansedRichTextField', 'RichText', 'RichTextInline')
+__all__ = ('RichText', 'RichTextInline')
@python_2_unicode_compatible
class RichText(models.Model):
+ """
+ Rich text plugin
+
+ Usage::
+
+ cla... |
c6d589859d621ac0eb2b4843a22cfe8e011bbeaf | braid/postgres.py | braid/postgres.py | from fabric.api import sudo, hide
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with hide('running', 'output'):
return sudo('psql --no-align --no-readline --no-password --quiet '
... | from fabric.api import sudo, hide
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query, database=None):
with hide('running', 'output'):
database = '--dbname={}'.format(database) if database else ''
... | Allow to specify a database when running a query | Allow to specify a database when running a query
| Python | mit | alex/braid,alex/braid | ---
+++
@@ -7,10 +7,11 @@
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
-def _runQuery(query):
+def _runQuery(query, database=None):
with hide('running', 'output'):
+ database = '--dbname={}'.format(database) if database else ''
return sudo('psql --no-align --no-readli... |
e2f2541d909861e140030d50cc1981697118bf2e | webvtt/parser.py | webvtt/parser.py | from .exceptions import MalformedFileError
class WebVTTParser:
def _parse(self, content):
self.content = content
def read(self, file):
with open(file, encoding='utf-8') as f:
self._parse(f.readlines())
if not self.is_valid():
raise MalformedFileError
... | from .exceptions import MalformedFileError
class WebVTTParser:
def _parse(self, content):
self.content = content
def read(self, file):
with open(file, encoding='utf-8') as f:
self._parse(f.readlines())
if not self.is_valid():
raise MalformedFileError('The file... | Add message to malformed exception | Add message to malformed exception
| Python | mit | glut23/webvtt-py,sampattuzzi/webvtt-py | ---
+++
@@ -10,7 +10,7 @@
with open(file, encoding='utf-8') as f:
self._parse(f.readlines())
if not self.is_valid():
- raise MalformedFileError
+ raise MalformedFileError('The file does not have a valid format')
return self
|
bc8aa0f8aab15dd704fd34f836464d5e7397c08e | SessionTools/features_JSON.py | SessionTools/features_JSON.py | import json
def getVersion(b64decodedData):
json_map = json.loads(b64decodedData)
if not json_map.has_key("View"):
return None
return json.loads(b64decodedData)["View"]["Dynamo"]["Version"]
def usesListAtLevel(data):
usesList = data.find('"UseLevels": true') > -1
return usesList | # Feature extractors for JSON files (Dynamo 2+)
import json
def getVersion(b64decodedData):
json_map = json.loads(b64decodedData)
if not json_map.has_key("View"):
return None
return json.loads(b64decodedData)["View"]["Dynamo"]["Version"]
def usesListAtLevel(data):
usesList = data.find('"UseLe... | Add structure for feature extractors for JSON files | Add structure for feature extractors for JSON files
| Python | mit | DynamoDS/Coulomb,DynamoDS/Coulomb,DynamoDS/Coulomb | ---
+++
@@ -1,3 +1,5 @@
+# Feature extractors for JSON files (Dynamo 2+)
+
import json
def getVersion(b64decodedData):
@@ -9,3 +11,27 @@
def usesListAtLevel(data):
usesList = data.find('"UseLevels": true') > -1
return usesList
+
+def hasHiddenNodes(data):
+ return data.find('"ShowGeometry": false,')... |
dd6a446a9a1ce2624769e276ddb0700da909334b | pep438/core.py | pep438/core.py | """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid p... | """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid p... | Fix get_pypi_packages for new requirements-parser | Fix get_pypi_packages for new requirements-parser
| Python | mit | treyhunner/pep438 | ---
+++
@@ -30,7 +30,7 @@
def get_pypi_packages(fileobj):
"""Return all PyPI-hosted packages from file-like object"""
- return [p['name'] for p in parse(fileobj) if not p.get('uri')]
+ return [p['name'] for p in parse(fileobj) if not p['uri']]
def get_pypi_user_packages(user): |
746439a977cd556e91424c80cf532e1da8551ae7 | imager/imager_images/urls.py | imager/imager_images/urls.py | from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from imager_images.views import (AlbumCreate, AlbumUpdate, AlbumDelete,
PhotoCreate, PhotoDelete)
urlpatterns = patterns('imager_images.views',
url(r'^upload/$', login_req... | from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from imager_images.views import (AlbumCreate, AlbumUpdate, AlbumDelete,
PhotoCreate, PhotoDelete)
urlpatterns = patterns('imager_images.views',
url(r'^upload/$', login_req... | Change url routes to use primary key instead of id | Change url routes to use primary key instead of id
| Python | mit | nbeck90/django-imager,nbeck90/django-imager | ---
+++
@@ -6,8 +6,8 @@
urlpatterns = patterns('imager_images.views',
url(r'^upload/$', login_required(PhotoCreate.as_view()), name='upload'),
- url(r'^delete/(?P<id>\d+)/$', login_required(PhotoDelete.as_view()), name='delete'),
+ url(r'^delete/(?P<pk>\d+)/$', login_required(PhotoDelete.as_view()), nam... |
92c70c5f54b6822f0f3815b66852a2771ef5d49c | scheduling/student_invite.py | scheduling/student_invite.py | from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)... | from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)... | Set group as read only when inviting students | Set group as read only when inviting students
| Python | agpl-3.0 | wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp | ---
+++
@@ -11,6 +11,7 @@
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
+ group.read_only = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user, |
027ae8b8029d01622e3a9647f3ec6b1fca4c4d9d | chainerrl/wrappers/__init__.py | chainerrl/wrappers/__init__.py | from chainerrl.wrappers.cast_observation import CastObservation # NOQA
from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA
from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA
from chainerrl.wrappers.scale_reward import ScaleReward # NOQA
| from chainerrl.wrappers.cast_observation import CastObservation # NOQA
from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA
from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA
from chainerrl.wrappers.render import Render # NOQA
from chainerrl.wrappers.scale_reward im... | Make Render available under chainerrl.wrappers | Make Render available under chainerrl.wrappers
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | ---
+++
@@ -3,4 +3,6 @@
from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA
+from chainerrl.wrappers.render import Render # NOQA
+
from chainerrl.wrappers.scale_reward import ScaleReward # NOQA |
79aa9edde1bba39a433475929970dd519fecfdf3 | requests/_oauth.py | requests/_oauth.py | # -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module comtains the path hack neccesary for oauthlib to be vendored into requests
while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.o... | # -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module comtains the path hack neccesary for oauthlib to be vendored into requests
while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.o... | Make OAuth path hack platform independent. | Make OAuth path hack platform independent.
| Python | isc | Bluehorn/requests,revolunet/requests,psf/requests,revolunet/requests | ---
+++
@@ -16,7 +16,8 @@
from oauthlib.common import extract_params
from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
except ImportError:
- path = os.path.abspath('/'.join(__file__.split('/')[:-1]+['packages']))
+ directory = os.path.dirname(__file__)
+ path... |
429d840a34c4ec2e3b475e412b53e99ffe2a5677 | studygroups/tasks.py | studygroups/tasks.py | from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from django.utils import translation
import datetime
def send_reminders():... | from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from django.utils import translation
import datetime
def send_reminders():... | Fix task and set language code when sending reminders | Fix task and set language code when sending reminders
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | ---
+++
@@ -11,8 +11,9 @@
def send_reminders():
now = timezone.now()
+ translation.activate(settings.LANGUAGE_CODE)
for reminder in Reminder.objects.filter(sent_at__isnull=True):
- if reminder.meeting_time - now < datetime.timedelta(days=2):
+ if reminder.study_group_meeting.meeting_time... |
fa19a6ec882727bb96f27993d7ac765797c19556 | logger/utilities.py | logger/utilities.py | #!/usr/bin/env python3
"""Small utility functions for use in various places."""
__all__ = ["pick", "is_dunder"]
def pick(arg, default):
"""Handler for default versus given argument."""
return default if arg is None else arg
def is_dunder(name):
"""Return True if a __dunder__ name, False otherwise."""
... | #!/usr/bin/env python3
"""Small utility functions for use in various places."""
__all__ = ["pick", "is_dunder", "find_name"]
import sys
def pick(arg, default):
"""Handler for default versus given argument."""
return default if arg is None else arg
def is_dunder(name):
"""Return True if a __dunder__ nam... | Add a find_name utility function | Add a find_name utility function
| Python | bsd-2-clause | Vgr255/logging | ---
+++
@@ -2,7 +2,9 @@
"""Small utility functions for use in various places."""
-__all__ = ["pick", "is_dunder"]
+__all__ = ["pick", "is_dunder", "find_name"]
+
+import sys
def pick(arg, default):
"""Handler for default versus given argument."""
@@ -11,3 +13,15 @@
def is_dunder(name):
"""Return Tr... |
9eb07a5b7d2875cf79bb698864d11ef29576133e | comics/utils/hash.py | comics/utils/hash.py | import hashlib
def sha256sum(filename):
"""Returns sha256sum for file"""
f = file(filename, 'rb')
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
f.close()
return m.hexdigest()
| import hashlib
def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
if filename is not None:
f = file(filename, 'rb')
else:
f = filehandle
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
... | Make sha256sum work with open filehandles too | Make sha256sum work with open filehandles too
| Python | agpl-3.0 | datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics | ---
+++
@@ -1,14 +1,18 @@
import hashlib
-def sha256sum(filename):
+def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
- f = file(filename, 'rb')
+ if filename is not None:
+ f = file(filename, 'rb')
+ else:
+ f = filehandle
m = hashlib.sha256()
... |
e99976cbee1e43e7112b4759cf5a1a17a1be8170 | utils/gyb_syntax_support/protocolsMap.py | utils/gyb_syntax_support/protocolsMap.py | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'SimpleTypeIdent... | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList'... | Add convenience initializers for `MemberDeclList` | Add convenience initializers for `MemberDeclList`
| Python | apache-2.0 | glessard/swift,atrick/swift,apple/swift,benlangmuir/swift,rudkx/swift,glessard/swift,atrick/swift,rudkx/swift,gregomni/swift,glessard/swift,apple/swift,atrick/swift,glessard/swift,JGiola/swift,atrick/swift,ahoppen/swift,gregomni/swift,JGiola/swift,glessard/swift,ahoppen/swift,ahoppen/swift,JGiola/swift,rudkx/swift,atri... | ---
+++
@@ -11,6 +11,9 @@
'IdentifierPattern': [
'PatternBuildable'
],
+ 'MemberDeclList': [
+ 'MemberDeclBlock'
+ ],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable', |
46b00107e90df8f34a9cce5c4b010fdfb88f5f52 | shovel/code.py | shovel/code.py | # coding: utf-8
from __future__ import absolute_import, division, print_function
from pathlib import Path
from isort import SortImports
from shovel import task
# isort multi_line_output modes
GRID = 0
VERTICAL = 1
HANGING_INDENT = 2
VERTICAL_HANGING_INDENT = 3
HANGING_GRID = 4
HANGING_GRID_GROUPED = 5
@task
def fo... | # coding: utf-8
from __future__ import absolute_import, division, print_function
from pathlib import Path
from isort import SortImports
from shovel import task
# isort multi_line_output modes
GRID = 0
VERTICAL = 1
HANGING_INDENT = 2
VERTICAL_HANGING_INDENT = 3
HANGING_GRID = 4
HANGING_GRID_GROUPED = 5
@task
def fo... | Add 'six' to known_third_party for SortImports | Add 'six' to known_third_party for SortImports
six was being sorted incorrectly due to being classed as first party.
| Python | mit | python-astrodynamics/astrodynamics,python-astrodynamics/astrodynamics | ---
+++
@@ -34,4 +34,5 @@
continue
SortImports(str(pyfile),
multi_line_output=HANGING_GRID,
- skip=['__init__.py'])
+ skip=['__init__.py'],
+ known_third_party=['six']) |
4d27a526dc6d76989ce65cc60991a7156b333fac | tests/test_format.py | tests/test_format.py | import unittest
import ipuz
import puz
import crossword
class FormatUnitTest(unittest.TestCase):
def test_to_ipuz_only_include_ipuz_specific_data(self):
puz_object = puz.read('fixtures/chronicle_20140815.puz')
puzzle = crossword.from_puz(puz_object)
ipuz_dict = crossword.to_ipuz(puzzle)... | import unittest
import ipuz
import puz
import crossword
class FormatUnitTest(unittest.TestCase):
def test_to_ipuz_only_include_ipuz_specific_data(self):
puz_object = puz.read('fixtures/chronicle_20140815.puz')
puzzle = crossword.from_puz(puz_object)
ipuz_dict = crossword.to_ipuz(puzzle)... | Use different puzzle in this test as it uses number that .puz accepts | Use different puzzle in this test as it uses number that .puz accepts
| Python | mit | svisser/crossword | ---
+++
@@ -17,7 +17,7 @@
self.assertNotIn('extensions', ipuz_dict)
def test_to_puz_only_include_puz_specific_data(self):
- with open('fixtures/first.ipuz') as f:
+ with open('fixtures/example.ipuz') as f:
ipuz_dict = ipuz.read(f.read())
puzzle = crossword.from_ip... |
9b12a9cdab0021fea7e5f2d8fd8ffe11d065f0d0 | tests/test_replay.py | tests/test_replay.py | # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
| # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecu... | Implement tests for replay.dump args | Implement tests for replay.dump args
| Python | bsd-3-clause | agconti/cookiecutter,luzfcb/cookiecutter,christabor/cookiecutter,terryjbates/cookiecutter,benthomasson/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,takeflight/cookiecut... | ---
+++
@@ -4,6 +4,13 @@
test_replay
-----------
"""
+
+import os
+import pytest
+
+
+from cookiecutter import replay
+from cookiecutter.config import get_user_config
def test_get_user_config():
@@ -12,3 +19,28 @@
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['rep... |
6b025a122e0b6ac4761f5e821b0f5465f867fe61 | crypto-square/crypto_square.py | crypto-square/crypto_square.py | import math
def encode(s):
s = list(filter(str.isalnum, s.lower()))
size = math.ceil(math.sqrt(len(s)))
s += "." * (size**2 - len(s))
parts = [s[i*size:(i+1)*size] for i in range(size)]
return " ".join(map("".join, zip(*parts))).replace(".", "")
| import math
def encode(s):
s = "".join(filter(str.isalnum, s.lower()))
size = math.ceil(math.sqrt(len(s)))
return " ".join(s[i::size] for i in range(size))
| Use string slices with a stride | Use string slices with a stride
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -2,8 +2,6 @@
def encode(s):
- s = list(filter(str.isalnum, s.lower()))
+ s = "".join(filter(str.isalnum, s.lower()))
size = math.ceil(math.sqrt(len(s)))
- s += "." * (size**2 - len(s))
- parts = [s[i*size:(i+1)*size] for i in range(size)]
- return " ".join(map("".join, zip(*parts))... |
dfbdf5d55a2c8d243b09828ef05c7c3c3ffc8d50 | dags/longitudinal.py | dags/longitudinal.py | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
default_args = {
'owner': 'rvitillo@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 30),
'email': ['telemetry-alerts@mozilla.com', 'rvitillo@mozilla.com'],
... | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
default_args = {
'owner': 'rvitillo@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 30),
'email': ['telemetry-alerts@mozilla.com', 'rvitillo@mozilla.com'],
... | Add update orphaning job to Airflow | Add update orphaning job to Airflow
This depends on the longitudinal job running successfully to run.
| Python | mpl-2.0 | opentrials/opentrials-airflow,opentrials/opentrials-airflow | ---
+++
@@ -19,6 +19,19 @@
job_name="Longitudinal View",
execution_timeout=timedelta(hours=10),
instance_count=30,
- env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.airflow_bucket }}"},
+ env=... |
0c6bf8eca2d4cfd08cc98df3cb0ab706a6fbf7a2 | cxfreeze-setup.py | cxfreeze-setup.py | import sys
from glob import glob
from cx_Freeze import setup, Executable
from version import VERSION
# Dependencies are automatically detected, but it might need
# fine tuning.
excludes = ["Tkinter"]
includes = ["logview", "colorwidget"]
includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"),
... | import sys
from glob import glob
from cx_Freeze import setup, Executable
from version import VERSION
# Dependencies are automatically detected, but it might need
# fine tuning.
excludes = ["Tkinter"]
includes = ["logview", "colorwidget", "pickle"]
includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"),
... | Fix a TypeError when load mergeTool setting | Fix a TypeError when load mergeTool setting
cx-freeze isn't include pickle module on the Windows platform,
it cause "TypeError: unable to convert a C++ 'QVariantList'
instance to a Python object"
| Python | apache-2.0 | timxx/gitc,timxx/gitc | ---
+++
@@ -7,7 +7,7 @@
# Dependencies are automatically detected, but it might need
# fine tuning.
excludes = ["Tkinter"]
-includes = ["logview", "colorwidget"]
+includes = ["logview", "colorwidget", "pickle"]
includeFiles = [("data/icons/gitc.svg", "data/icons/gitc.svg"),
("data/licenses/Apache... |
64303ae1a02b707ff11231a9e3c46405a8a591e7 | host/cgi-bin/liberator.py | host/cgi-bin/liberator.py | #!/usr/bin/env python
import cgi, subprocess, json
arguments = cgi.FieldStorage()
body = arguments.getvalue('body', '')
messageTo = arguments.getvalue('messageTo', '')
exitCode = subprocess.call(['./SendImessage.applescript', messageTo, body])
print 'Content-Type: application/json'
print ''
print json.dumps({'ok': ... | #!/usr/bin/env python
from os.path import expanduser
from time import sleep
import subprocess, json, sys, os
messagesDbPath = '%s/Library/Messages/chat.db' % expanduser('~')
# manually parse the QUERY_STRING because "+" is being weirdly decoded via FieldStorage
queryParameters = {}
keyValues = os.environ['QUERY_STRI... | Verify message sent via SQL | Verify message sent via SQL
| Python | mit | chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator,chainsawsalad/imessage-liberator | ---
+++
@@ -1,13 +1,65 @@
#!/usr/bin/env python
-import cgi, subprocess, json
+from os.path import expanduser
+from time import sleep
+import subprocess, json, sys, os
-arguments = cgi.FieldStorage()
-body = arguments.getvalue('body', '')
-messageTo = arguments.getvalue('messageTo', '')
+messagesDbPath = '%s/Lib... |
3f3818e4a21ffc4e1b8d4426093fc093396b5a5b | pandas_finance.py | pandas_finance.py | #!/usr/bin/env python
import datetime
import scraperwiki
import numpy
import pandas.io.data as web
def get_stock(stock, start, end, service):
"""
Return data frame of finance data for stock.
Takes start and end datetimes, and service name of 'google' or 'yahoo'.
"""
return web.DataReader(stock, ... | #!/usr/bin/env python
import datetime
import sqlite3
import pandas.io.data as web
import pandas.io.sql as sql
def get_stock(stock, start, end):
"""
Return data frame of Yahoo Finance data for stock.
Takes start and end datetimes.
"""
return web.DataReader(stock, 'yahoo', start, end)
def scrape_s... | Use pandas native saving by forcing date to not be index, and be string | Use pandas native saving by forcing date to not be index, and be string | Python | agpl-3.0 | scraperwiki/stock-tool,scraperwiki/stock-tool | ---
+++
@@ -1,56 +1,34 @@
#!/usr/bin/env python
import datetime
-
-import scraperwiki
-import numpy
+import sqlite3
import pandas.io.data as web
+import pandas.io.sql as sql
-def get_stock(stock, start, end, service):
+def get_stock(stock, start, end):
"""
- Return data frame of finance data for stock.... |
3919d64370825d8931672011af4b99355e52ef63 | motobot/core_plugins/help.py | motobot/core_plugins/help.py | from motobot import IRCBot, command, Notice
def get_command_help(bot, command, modifier):
responses = []
func = lambda x: x.type == IRCBot.command_plugin and x.arg.lower() == command.lower()
for plugin in filter(func, bot.plugins):
func = plugin.func
if func.__doc__ is not None:
... | from motobot import IRCBot, command, Notice
def get_command_help(bot, command):
responses = []
func = lambda x: x.type == IRCBot.command_plugin and x.arg.lower() == command.lower()
for plugin in filter(func, bot.plugins):
func = plugin.func
if func.__doc__ is not None:
respon... | Update to new response handling | Update to new response handling
| Python | mit | Motoko11/MotoBot | ---
+++
@@ -1,7 +1,7 @@
from motobot import IRCBot, command, Notice
-def get_command_help(bot, command, modifier):
+def get_command_help(bot, command):
responses = []
func = lambda x: x.type == IRCBot.command_plugin and x.arg.lower() == command.lower()
@@ -9,7 +9,7 @@
func = plugin.func
... |
0eb5966ec3261e6c6101b4c9874321a105fb4426 | dj-resume/urls.py | dj-resume/urls.py | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'apply/', 'resume.views.cs_apply_handler'),
(r'cs/', 'resume.views.index_handler'),
(r'cap/.*', 'belaylibs.dj_be... | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'cs/', 'resume.views.cs_index_handler'),
(r'cap/.*', 'belaylibs.dj_belay.proxyHandler'),
(r'applicant/', 'resume... | Make /cs/ point to the correct handler, no more apply handlre | Make /cs/ point to the correct handler, no more apply handlre
| Python | apache-2.0 | brownplt/k3,brownplt/k3,brownplt/k3 | ---
+++
@@ -5,14 +5,14 @@
# admin.autodiscover()
urlpatterns = patterns('',
- (r'apply/', 'resume.views.cs_apply_handler'),
- (r'cs/', 'resume.views.index_handler'),
+ (r'cs/', 'resume.views.cs_index_handler'),
(r'cap/.*', 'belaylibs.dj_belay.proxyHandler'),
(r'applicant/', 'resume.views.applicant_handle... |
9be2846e408699308798b698754634ce7f370710 | openedx/stanford/cms/urls.py | openedx/stanford/cms/urls.py | from django.conf import settings
from django.conf.urls import url
import contentstore.views
urlpatterns = [
url(
r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN),
contentstore.views.send_test_enrollment_email,
name='send_test_enrollment_email',
),
ur... | from django.conf import settings
from django.conf.urls import url
import contentstore.views
urlpatterns = [
url(
r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN),
contentstore.views.send_test_enrollment_email,
name='send_test_enrollment_email',
),
ur... | Add names to stanford view handlers | Add names to stanford view handlers
| Python | agpl-3.0 | Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform | ---
+++
@@ -13,14 +13,17 @@
url(
r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
contentstore.views.utility_handler,
+ name='utility_handler',
),
url(
r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
contentstore.views.utility_captions_hand... |
89526f9af257096d2253b00b72d0cea1493fec52 | django_prices_openexchangerates/management/commands/update_exchange_rates.py | django_prices_openexchangerates/management/commands/update_exchange_rates.py | from django.core.management.base import BaseCommand
from ...tasks import update_conversion_rates, create_conversion_dates
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--all',
action='store_true',
dest='all_currencies',
... | from django.core.management.base import BaseCommand
from ...tasks import update_conversion_rates, create_conversion_rates
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--all',
action='store_true',
dest='all_currencies',
... | Fix typo create_conversion_rates in commands | Fix typo create_conversion_rates in commands
| Python | bsd-3-clause | mirumee/django-prices-openexchangerates | ---
+++
@@ -1,6 +1,6 @@
from django.core.management.base import BaseCommand
-from ...tasks import update_conversion_rates, create_conversion_dates
+from ...tasks import update_conversion_rates, create_conversion_rates
class Command(BaseCommand):
@@ -15,7 +15,7 @@
def handle(self, *args, **options):
... |
d74b524cec824e77adbcf9cc23e28a6efba02985 | takePicture.py | takePicture.py | import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 15:
img = cam.capture('gregTest.jpg')
time.sleep(.25)
x +=1
exit()
| import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 50:
img = cam.capture('tempGregTest.jpg')
os.unlink('gregTest.jpg')
os.rename('tempGregTest.jpg','gregTest.jpg')
time.sleep(.25)
x +=1
exit()
| Add temp pic file sequence to takepicture file | Add temp pic file sequence to takepicture file
| Python | mit | jwarshaw/RaspberryDrive | ---
+++
@@ -10,8 +10,10 @@
cam.vflip = True
x = 0
-while x < 15:
- img = cam.capture('gregTest.jpg')
+while x < 50:
+ img = cam.capture('tempGregTest.jpg')
+ os.unlink('gregTest.jpg')
+ os.rename('tempGregTest.jpg','gregTest.jpg')
time.sleep(.25)
x +=1
|
0c5abad8259cccfd1ce50b27a124089d9ea946dd | copr_build.py | copr_build.py | #!/usr/bin/env python3
import json, os, sys
import requests
api_url = "https://copr.fedorainfracloud.org/api_2"
api_login = os.environ["copr_login"]
api_token = os.environ["copr_token"]
r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json()
chroots = []
for i in r.get("chroots"):
... | #!/usr/bin/env python3
import os
import sys
import requests
api_url = "https://copr.fedorainfracloud.org/api_2"
api_login = os.environ["copr_login"]
api_token = os.environ["copr_token"]
project_id = int(os.environ["copr_projectid"])
r = requests.get("%s/projects/%s/chroots" % (api_url, project_id))
if not r.ok:
pr... | Fix copr build trigger script | Fix copr build trigger script
| Python | mit | kyl191/nginx-pagespeed,kyl191/nginx-pagespeed,kyl191/nginx-pagespeed | ---
+++
@@ -1,21 +1,48 @@
#!/usr/bin/env python3
-import json, os, sys
+import os
+import sys
import requests
api_url = "https://copr.fedorainfracloud.org/api_2"
api_login = os.environ["copr_login"]
api_token = os.environ["copr_token"]
+project_id = int(os.environ["copr_projectid"])
-r = requests.get("%s/proje... |
bff8d72c83c7f8a9321e4a065daa621c9e7d0539 | pipeline_dart2js/compiler.py | pipeline_dart2js/compiler.py | from os.path import dirname
from django.conf import settings
from pipeline.compilers import SubProcessCompiler
class Dart2jsCompiler(SubProcessCompiler):
output_extension = 'js'
def match_file(self, filename):
return filename.endswith('.dart')
def compile_file(self, infile, outfile, outdated=Fal... | from os.path import dirname
from django.conf import settings
from pipeline.compilers import SubProcessCompiler
class Dart2jsCompiler(SubProcessCompiler):
output_extension = 'js'
def match_file(self, filename):
return filename.endswith('.dart')
def compile_file(self, infile, outfile, outdated=Fal... | Update to new command line | Update to new command line
| Python | apache-2.0 | wienczny/django-pipeline-dart2js | ---
+++
@@ -13,7 +13,7 @@
if not outdated and not force:
return # No need to recompiled file
- command = "%s %s --out=%s %s" % (
+ command = "%s %s -o %s %s" % (
getattr(settings, 'PIPELINE_DART2JS_BINARY', '/usr/bin/env dart2js'),
getattr(setti... |
9f1964f9f83c493f9bc6e08e2058d1e14ace031f | synapse/tests/test_cells.py | synapse/tests/test_cells.py | import synapse.axon as s_axon
import synapse.cells as s_cells
import synapse.cryotank as s_cryotank
from synapse.tests.common import *
class CellTest(SynTest):
def test_getcells(self):
data = s_cells.getCells()
data = {k: v for k, v in data}
self.isin('cortex', data)
| import synapse.axon as s_axon
import synapse.cells as s_cells
import synapse.cryotank as s_cryotank
from synapse.tests.common import *
class CellTest(SynTest):
def test_getcells(self):
data = s_cells.getCells()
data = {k: v for k, v in data}
self.isin('cortex', data)
def test_deploy(s... | Add a test for s_cells.deploy() | Add a test for s_cells.deploy()
| Python | apache-2.0 | vertexproject/synapse,vertexproject/synapse,vertexproject/synapse | ---
+++
@@ -9,3 +9,9 @@
data = s_cells.getCells()
data = {k: v for k, v in data}
self.isin('cortex', data)
+
+ def test_deploy(self):
+ with self.getTestDir() as dirn:
+ s_cells.deploy('cortex', dirn, {'test': 1})
+ d = s_common.yamlload(dirn, 'boot.yaml')
+ ... |
e08b4f1b74f0fcd987299d4786b5374fe86a21bc | Lib/idlelib/macosxSupport.py | Lib/idlelib/macosxSupport.py | """
A number of function that enhance IDLE on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
def runningAsOSXApp():
""" Returns True iff running from the IDLE.app bundle on OSX """
return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0])
def... | """
A number of function that enhance IDLE on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
def runningAsOSXApp():
""" Returns True iff running from the IDLE.app bundle on OSX """
return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0])
def addOpenEv... | Add missing svn:eol-style property to text files. | Add missing svn:eol-style property to text files.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | |
831c810b96c0ed1b6c254b0b6b2c3b1b259b51bb | src/pyckson/model/union.py | src/pyckson/model/union.py | from typing import Tuple, Union
def inspect_optional_typing(annotation) -> Tuple[bool, type]:
# seems like at some point internal behavior on typing Union changed
# https://bugs.launchpad.net/ubuntu/+source/python3.5/+bug/1650202
if "Union" not in str(annotation):
return False, type(None)
if ... | from typing import Tuple, Union
def inspect_optional_typing(annotation) -> Tuple[bool, type]:
# seems like at some point internal behavior on typing Union changed
# https://bugs.launchpad.net/ubuntu/+source/python3.5/+bug/1650202
if "Union" not in str(annotation) and "Optional" not in str(annotation):
... | Fix optional inspection in 3.9 | Fix optional inspection in 3.9
| Python | lgpl-2.1 | antidot/Pyckson | ---
+++
@@ -4,7 +4,7 @@
def inspect_optional_typing(annotation) -> Tuple[bool, type]:
# seems like at some point internal behavior on typing Union changed
# https://bugs.launchpad.net/ubuntu/+source/python3.5/+bug/1650202
- if "Union" not in str(annotation):
+ if "Union" not in str(annotation) and "O... |
a753841d01eb3e9493e08e20e8a28c9b08fdef53 | comics/sets/models.py | comics/sets/models.py | from django.db import models
from django.utils import timezone
from comics.core.models import Comic
class Set(models.Model):
name = models.SlugField(max_length=100, unique=True,
help_text='The set identifier')
add_new_comics = models.BooleanField(default=False,
help_text='Automatically add ne... | from django.db import models
from django.utils import timezone
from comics.core.models import Comic
class Set(models.Model):
name = models.SlugField(
max_length=100, unique=True,
help_text='The set identifier')
add_new_comics = models.BooleanField(
default=False,
help_text='Au... | Fix all warnings in sets app | flake8: Fix all warnings in sets app
| Python | agpl-3.0 | datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics | ---
+++
@@ -5,11 +5,14 @@
class Set(models.Model):
- name = models.SlugField(max_length=100, unique=True,
+ name = models.SlugField(
+ max_length=100, unique=True,
help_text='The set identifier')
- add_new_comics = models.BooleanField(default=False,
+ add_new_comics = models.BooleanFi... |
4410e03df12b99c46467b6fe93f7b8cb206d441c | decorators.py | decorators.py | import time
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:p... | import time
from functools import wraps
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonD... | Remove unreachable code. Use functools.wraps. | Remove unreachable code. Use functools.wraps.
- Remove code that was unreachable. Thanks Jaskirat
(http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/#c24691)
- Use functools.wraps to make the retry decorator "well behaved"
- Fix typo
| Python | bsd-3-clause | saltycrane/retry-decorator | ---
+++
@@ -1,4 +1,6 @@
import time
+from functools import wraps
+
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
@@ -7,7 +9,7 @@
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:... |
ebd024b4f8ee6e490c183da0bada28a2aaf328d8 | comrade/users/urls.py | comrade/users/urls.py | from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
reverse_lazy = lazy(reverse, unicode)
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='lo... | from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
reverse_lazy = lazy(reverse, unicode)
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='lo... | Rename url namespace users -> account. | Rename url namespace users -> account.
| Python | mit | bueda/django-comrade | ---
+++
@@ -8,14 +8,14 @@
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='logout'),
url(r'^password/forgot/$', 'password_reset',
- {'post_reset_redirect':reverse_lazy('users:password_reset_done')},
+ {'post_reset_redirect':reverse_lazy('... |
37490a9bd916480775271cf7e0c91b11a7eac913 | distarray/tests/run_ipcluster.py | distarray/tests/run_ipcluster.py | import six
from subprocess import Popen, PIPE
def run_ipcluster(n=4):
"""Convenient way to start an ipcluster for testing.
You have to wait for it to start, however.
"""
# FIXME: This should be reimplemented to signal when the cluster has
# successfully started
if six.PY2:
cmd = 'ipcl... | import sys
import six
from subprocess import Popen, PIPE
if six.PY2:
ipcluster_cmd = 'ipcluster'
elif six.PY3:
ipcluster_cmd = 'ipcluster3'
else:
raise NotImplementedError("Not run with Python 2 *or* 3?")
def start(n=12):
"""Convenient way to start an ipcluster for testing.
You have to wait for... | Add a `stop` command to the script. | Add a `stop` command to the script. | Python | bsd-3-clause | enthought/distarray,enthought/distarray,RaoUmer/distarray,RaoUmer/distarray | ---
+++
@@ -1,25 +1,36 @@
+import sys
import six
from subprocess import Popen, PIPE
-def run_ipcluster(n=4):
+if six.PY2:
+ ipcluster_cmd = 'ipcluster'
+elif six.PY3:
+ ipcluster_cmd = 'ipcluster3'
+else:
+ raise NotImplementedError("Not run with Python 2 *or* 3?")
+
+
+def start(n=12):
"""Conveni... |
b471da17f2e7b13d30746481e5db13f4d88de4d6 | django/contrib/admin/__init__.py | django/contrib/admin/__init__.py | from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. T... | # ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInli... | Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. | Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%4014359
| Python | bsd-3-clause | adieu/django-nonrel,adieu/django-nonrel,adieu/django-nonrel | ---
+++
@@ -1,3 +1,6 @@
+# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
+# has been referenced in documentation.
+from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options im... |
0683e96d0cd55797639c84003e03c48ae7211912 | sidecar/__init__.py | sidecar/__init__.py | from pyramid.config import Configurator
from pyramid.events import BeforeRender
from sqlalchemy import engine_from_config
from . import helpers
from .model import Session, Base
def add_renderer_globals(event):
event['h'] = helpers
def main(global_config, **settings):
"""
This function returns a Pyramid... | from pyramid.config import Configurator
from pyramid.events import BeforeRender
from sqlalchemy import engine_from_config
from . import helpers
from .model import Session, Base
def add_renderer_globals(event):
event['h'] = helpers
def main(global_config, **settings):
"""
This function returns a Pyramid... | Disable config.scan() as well for now | Disable config.scan() as well for now
| Python | mit | storborg/sidecar,storborg/sidecar | ---
+++
@@ -24,6 +24,6 @@
config.include('.views')
config.add_subscriber(add_renderer_globals, BeforeRender)
- config.scan()
+ #config.scan()
return config.make_wsgi_app() |
2d5710dfc8361bb4c383e8fe8a2e2ca267c11875 | luhn/luhn.py | luhn/luhn.py | # File: luhn.py
# Purpose: Write a program that can take a number and determine whether
# or not it is valid per the Luhn formula.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 09:55 PM
class Luhn(object):
def __init__(self, card_number):
... | # File: luhn.py
# Purpose: Write a program that can take a number and determine whether
# or not it is valid per the Luhn formula.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 09:55 PM
class Luhn(object):
def __init__(self, card_number):
... | Convert card number to string for iteration | Convert card number to string for iteration
| Python | mit | amalshehu/exercism-python | ---
+++
@@ -11,5 +11,10 @@
self.card_number = card_number
def addends(self):
- luhn_function = lambda x: (2 * x - 9) if (x > 4) else (2 * x)
-
+ def luhn_function(x): return (2 * x - 9) if (x > 4) else (2 * x)
+ prev_digits = [item for item in str(self.card_number)]
+
+ ... |
88d93f580ce2f587ac5fa1b41e7ab3f67a9c6be4 | avalonstar/apps/live/urls.py | avalonstar/apps/live/urls.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from .views import AwayView, BumperView, GameView, PrologueView
urlpatterns = patterns('',
url(r'^away/$', name='live-away', view=AwayView.as_view()),
url(r'^bumper/$', name='live-bumper', view=Bumper... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from .views import (AwayView, BumperView, DiscussionView, GameView,
PrologueView)
urlpatterns = patterns('',
url(r'^away/$', name='live-away', view=AwayView.as_view()),
url(r'^bumper/$', name='liv... | Add DiscussionView to the URLs. | Add DiscussionView to the URLs.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | ---
+++
@@ -2,12 +2,14 @@
from django.conf import settings
from django.conf.urls import patterns, include, url
-from .views import AwayView, BumperView, GameView, PrologueView
+from .views import (AwayView, BumperView, DiscussionView, GameView,
+ PrologueView)
urlpatterns = patterns('',
url(r'^away/$... |
0fed581409f0dfa4788964d02d066e8e30f1387f | webapp/byceps/blueprints/shop_admin/service.py | webapp/byceps/blueprints/shop_admin/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
from collections import Counter
from ..shop.models import PaymentState
def count_ordered_articles(article):
"""Count how often the article has been ordered, grou... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
from collections import Counter
from ..shop.models import PaymentState
def count_ordered_articles(article):
"""Count how often the article has been ordered, grou... | Make sure every payment state is present in the counter. | Make sure every payment state is present in the counter.
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -16,6 +16,9 @@
"""Count how often the article has been ordered, grouped by the
order's payment state.
"""
+ # Ensure every payment state is present in the resulting dictionary,
+ # even if no orders of the corresponding payment state exist for the
+ # article.
counter = Counter... |
0cb5447de992389be9587d7706637212bfe3b90b | tests/events/tests.py | tests/events/tests.py | # -*- coding: utf-8 -*-
from mock import Mock
from unittest2 import TestCase
from raven.events import Message
class MessageTest(TestCase):
def test_to_string(self):
unformatted_message = 'My message from %s about %s'
client = Mock()
message = Message(client)
message.logger = Mock... | # -*- coding: utf-8 -*-
from mock import Mock
from unittest2 import TestCase
from raven.events import Message
class MessageTest(TestCase):
def test_to_string(self):
unformatted_message = 'My message from %s about %s'
client = Mock()
message = Message(client)
message.logger = Mock... | Update test to match current behavior | Update test to match current behavior
| Python | bsd-3-clause | johansteffner/raven-python,Photonomie/raven-python,jbarbuto/raven-python,nikolas/raven-python,lepture/raven-python,smarkets/raven-python,arthurlogilab/raven-python,lepture/raven-python,hzy/raven-python,recht/raven-python,inspirehep/raven-python,nikolas/raven-python,openlabs/raven,patrys/opbeat_python,ewdurbin/raven-pyt... | ---
+++
@@ -19,12 +19,6 @@
}
self.assertEqual(message.to_string(data), unformatted_message)
- self.assertEqual(message.logger.warn.call_count, 1)
-
- args, kwargs = message.logger.warn.call_args
- self.assertEqual(args, ('Unable to find params for message',))
- self.ass... |
edf2388300b0c0b230cd1b1ec91268a13ee6e6ba | homepage/views.py | homepage/views.py | from django.views.generic import FormView, RedirectView
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.contrib.auth import login, logout
class LoginView(FormView):
template_name = 'homepage/login.html'
form_class = AuthenticationForm
def ... | from django.views.generic import FormView, RedirectView
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.contrib.auth import login, logout
class LoginView(FormView):
template_name = 'homepage/login.html'
form_class = AuthenticationForm
def ... | Fix wrong URL for success login | Fix wrong URL for success login
| Python | mit | polarkac/TaskTracker,polarkac/TaskTracker | ---
+++
@@ -15,7 +15,7 @@
return super().form_valid(form)
def get_success_url(self):
- return reverse('tasks-project-detail', args=['none'])
+ return reverse('tasks-project-detail', args=['general'])
class LogoutView(RedirectView):
|
e7f97bf1ddcf05bee3c3b6fc79c5cefb36af280a | lingcod/layers/urls.py | lingcod/layers/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<se... | from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_pu... | Add another url pattern for debugging public layers | Add another url pattern for debugging public layers
| Python | bsd-3-clause | Ecotrust/madrona_addons,Ecotrust/madrona_addons | ---
+++
@@ -1,10 +1,17 @@
from django.conf.urls.defaults import *
+import time
urlpatterns = patterns('lingcod.layers.views',
- url(r'^public/',
+ url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
+
+ # Useful for debugging, avoids GE caching interference
+ url(... |
f4f5a6ffa1fd60437b83bfc435a180ddf2433ea4 | tests/test_confirmation.py | tests/test_confirmation.py | import pytest
import linkatos.confirmation as confirmation
def test_no_confirmation_with_url():
expecting_confirmation = False
parsed_m = {'out': 'http://ex.org', 'channel': 'ch', 'type': 'url'}
assert confirmation.update_confirmation_if_url(parsed_m,
ex... | import pytest
import linkatos.confirmation as confirmation
def test_no_confirmation_with_url():
expecting_confirmation = False
parsed_m = {'out': 'http://ex.org', 'channel': 'ch', 'type': 'url'}
assert confirmation.update_if_url(parsed_m,
expecting_confi... | Fix change of function names | test: Fix change of function names
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -6,7 +6,7 @@
expecting_confirmation = False
parsed_m = {'out': 'http://ex.org', 'channel': 'ch', 'type': 'url'}
- assert confirmation.update_confirmation_if_url(parsed_m,
+ assert confirmation.update_if_url(parsed_m,
expecting_confirmati... |
a2c55857cc9d910978c6c1ae963e0669176e061f | timezone_field/__init__.py | timezone_field/__init__.py | __version__ = '1.0'
__all__ = ['TimeZoneField', 'TimeZoneFormField']
from timezone_field.fields import TimeZoneField
from timezone_field.forms import TimeZoneFormField
| __version__ = '1.1'
__all__ = ['TimeZoneField', 'TimeZoneFormField']
from timezone_field.fields import TimeZoneField
from timezone_field.forms import TimeZoneFormField
| Bump version number to 1.1 | Bump version number to 1.1
| Python | bsd-2-clause | mfogel/django-timezone-field | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '1.0'
+__version__ = '1.1'
__all__ = ['TimeZoneField', 'TimeZoneFormField']
from timezone_field.fields import TimeZoneField |
96bb2ba0dc6e58195b598e03d177114becfeba7a | nxpy/util.py | nxpy/util.py | import re
from lxml import etree
def new_ele(tag, attrs={}, **extra):
etree.Element(tag, attrs, **extra)
def sub_ele(parent, tag, attrs={}, **extra):
etree.SubElement(parent, tag, attrs, **extra)
# Globals
tag_pattern = re.compile(r'({.*})?(.*)')
whitespace_pattern = re.compile(r'[\n\r\s]+')
| import re
# Globals
tag_pattern = re.compile(r'({.*})?(.*)')
whitespace_pattern = re.compile(r'[\n\r\s]+')
| Remove new_ele() and sub_ele() functions | Remove new_ele() and sub_ele() functions
| Python | apache-2.0 | Kent1/nxpy | ---
+++
@@ -1,13 +1,4 @@
import re
-from lxml import etree
-
-
-def new_ele(tag, attrs={}, **extra):
- etree.Element(tag, attrs, **extra)
-
-
-def sub_ele(parent, tag, attrs={}, **extra):
- etree.SubElement(parent, tag, attrs, **extra)
# Globals
tag_pattern = re.compile(r'({.*})?(.*)') |
4e29782102f121cccfbfbcaccc28fe9ccc99e495 | trackon/update-trackers.py | trackon/update-trackers.py | from cgi import FieldStorage
from logging import debug, error, info
from time import time
from trackon import tracker
MAX_MIN_INTERVAL = 60*60*5
DEFAULT_CHECK_INTERVAL = 60*15
def main():
args = FieldStorage()
now = int(time())
if 'tracker-address' in args:
t = args['tracker-address'].value
... | from cgi import FieldStorage
from logging import debug, error, info
from time import time
from trackon import tracker
MAX_MIN_INTERVAL = 60*60*5
DEFAULT_CHECK_INTERVAL = 60*15
def main():
args = FieldStorage()
now = int(time())
if 'tracker-address' in args:
t = args['tracker-address'].value
... | Reduce frequency of 'random' ssl tests. | Reduce frequency of 'random' ssl tests.
| Python | mit | CorralPeltzer/newTrackon | ---
+++
@@ -31,8 +31,8 @@
ti = tracker.allinfo() or {}
for t in ti:
if 'next-check' not in ti[t] or ti[t]['next-check'] < now:
- # Gross hack: 1% of the time we try over https
- if ti[t].get('ssl', True) or (now%100 == 0):
+ # Gross hack: 0.... |
9130a94153b7d9f70883da737fb60d41db73e09a | try_telethon.py | try_telethon.py | #!/usr/bin/env python3
import traceback
from telethon_examples.interactive_telegram_client \
import InteractiveTelegramClient
def load_settings(path='api/settings'):
"""Loads the user settings located under `api/`"""
result = {}
with open(path, 'r', encoding='utf-8') as file:
for line in file... | #!/usr/bin/env python3
import traceback
from telethon_examples.interactive_telegram_client \
import InteractiveTelegramClient
def load_settings(path='api/settings'):
"""Loads the user settings located under `api/`"""
result = {}
with open(path, 'r', encoding='utf-8') as file:
for line in file... | Support configuring SOCKS proxy in the example | Support configuring SOCKS proxy in the example
| Python | mit | LonamiWebs/Telethon,LonamiWebs/Telethon,kyasabu/Telethon,andr-04/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon | ---
+++
@@ -24,11 +24,18 @@
if __name__ == '__main__':
# Load the settings and initialize the client
settings = load_settings()
+ kwargs = {}
+ if settings.get('socks_proxy'):
+ import socks # $ pip install pysocks
+ host, port = settings['socks_proxy'].split(':')
+ kwargs = dic... |
ee259a377bc574c113640601064ceb259707d35f | akhet/__init__.py | akhet/__init__.py | from akhet.static import add_static_route
def includeme(config):
"""Add certain useful methods to a Pyramid ``Configurator`` instance.
Currently this adds the ``.add_static_route()`` method. (See
``pyramid_sqla.static.add_static_route()``.)
"""
config.add_directive('add_static_route', add_static_r... | Add 'includeme' function. (Accidently put in SQLAHelper.) | Add 'includeme' function. (Accidently put in SQLAHelper.)
| Python | mit | koansys/akhet,koansys/akhet | ---
+++
@@ -0,0 +1,9 @@
+from akhet.static import add_static_route
+
+def includeme(config):
+ """Add certain useful methods to a Pyramid ``Configurator`` instance.
+
+ Currently this adds the ``.add_static_route()`` method. (See
+ ``pyramid_sqla.static.add_static_route()``.)
+ """
+ config.add_directi... | |
52b022869b7092fc519accc2132c3f842502aeae | create_input_files.py | create_input_files.py | from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, content):
self.filename = filename
self.content = content
connect_tbl=input_table('connectivity.csv',
[['Connectivity Table'],
['x1','y1','x2','y2','E','... | from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, name, headers, content=[]):
self.filename = filename
self.name = name
self.headers = headers
self.content = content
connect_filename = 'connectivity.csv'
connect_name = ['Connectivity Ta... | Clean up input tables class and instance declarations | Clean up input tables class and instance declarations
| Python | mit | ndebuhr/openfea,ndebuhr/openfea | ---
+++
@@ -1,26 +1,48 @@
from utils import write_csv_rows, read_csv_rows
class input_table:
- def __init__(self, filename, content):
+ def __init__(self, filename, name, headers, content=[]):
self.filename = filename
+ self.name = name
+ self.headers = headers
self.content =... |
33620c30a7e79243a9a1f32cdad7e2af8e1fa278 | auditlog/admin.py | auditlog/admin.py | from django.contrib import admin
from auditlog.filters import ResourceTypeFilter
from auditlog.mixins import LogEntryAdminMixin
from auditlog.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_... | from django.contrib import admin
from auditlog.filters import ResourceTypeFilter
from auditlog.mixins import LogEntryAdminMixin
from auditlog.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_... | Add actor username to search fields | Add actor username to search fields
| Python | mit | jjkester/django-auditlog | ---
+++
@@ -13,6 +13,7 @@
"changes",
"actor__first_name",
"actor__last_name",
+ "actor__username",
]
list_filter = ["action", ResourceTypeFilter]
readonly_fields = ["created", "resource_url", "action", "user_url", "msg"] |
f25c0074a013255141371b46cff0a506ad0b2ab5 | axiom/__init__.py | axiom/__init__.py | # -*- test-case-name: axiom.test -*-
from axiom._version import __version__
from epsilon import asTwistedVersion
version = asTwistedVersion("axiom", __version__)
| # -*- test-case-name: axiom.test -*-
from axiom._version import __version__
from twisted.python import versions
def asTwistedVersion(packageName, versionString):
return versions.Version(packageName, *map(int, versionString.split(".")))
version = asTwistedVersion("axiom", __version__)
| Add a local asTwistedVersion implementation to Axiom, so as to not add another setup-time dependency on Epsilon | Add a local asTwistedVersion implementation to Axiom, so as to not add another setup-time dependency on Epsilon | Python | mit | hawkowl/axiom,twisted/axiom | ---
+++
@@ -1,5 +1,8 @@
# -*- test-case-name: axiom.test -*-
from axiom._version import __version__
-from epsilon import asTwistedVersion
+from twisted.python import versions
+
+def asTwistedVersion(packageName, versionString):
+ return versions.Version(packageName, *map(int, versionString.split(".")))
versio... |
0c3a0fd8eee8ca4ced29dbb69570aa1605ea0d5d | PEATSA/Database/Scripts/JobMailer.py | PEATSA/Database/Scripts/JobMailer.py | #! /usr/bin/python
import sys, time, optparse, os
import PEATSA.Core as Core
import PEATSA.WebApp as WebApp
import ConstructJob
import MySQLdb
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage=usage, version="% 0.1", description=__doc__)
parser.add_option("-c", "--configurationFile", dest="configu... | #! /usr/bin/python
import sys, time, optparse, os
import PEATSA.Core as Core
import PEATSA.WebApp as WebApp
import ConstructJob
import MySQLdb
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage=usage, version="% 0.1", description=__doc__)
parser.add_option("-c", "--configurationFile", dest="configu... | Print error on mailing a failed job note | Print error on mailing a failed job note | Python | mit | dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat,dmnfarrell/peat | ---
+++
@@ -30,6 +30,7 @@
for id in ids:
job = WebApp.Data.Job(id, connection)
print 'Sending mail for job %s to %s' % (job.identification, job.email())
+ print job.error()
WebApp.UtilityFunctions.SendNotificationEmail(job)
connection.close()
time.sleep(30) |
ddcb5b11a2f050e1eb8ae185888dde2ef1c66d72 | dedupe/convenience.py | dedupe/convenience.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | Index of the list should be an int | Index of the list should be an int
| Python | mit | dedupeio/dedupe-examples,dedupeio/dedupe,neozhangthe1/dedupe,tfmorris/dedupe,datamade/dedupe,pombredanne/dedupe,datamade/dedupe,nmiranda/dedupe,pombredanne/dedupe,neozhangthe1/dedupe,dedupeio/dedupe,davidkunio/dedupe,01-/dedupe,01-/dedupe,nmiranda/dedupe,tfmorris/dedupe,davidkunio/dedupe | ---
+++
@@ -16,7 +16,7 @@
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
- return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
+ return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs)
def blockData(dat... |
c8b28cc0afc45c2e7b7ca83a41bc67804c7e9506 | src/samples/showvideo.py | src/samples/showvideo.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libavg import avg, app
import sys
class VideoPlayer(app.MainDiv):
def init(self):
self.videoNode = avg.VideoNode(
href=sys.argv[1],
parent=self)
self.videoNode.play()
app.App().run(VideoPlayer(), app_resolu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libavg import avg, app
import sys
class VideoPlayer(app.MainDiv):
def onArgvParserCreated(self, parser):
parser.set_usage("%prog <video>")
def onArgvParsed(self, options, args, parser):
if len(args) != 1:
parser.print_help()
... | Add checks for script parameters and correct onInit name | Add checks for script parameters and correct onInit name
| Python | lgpl-2.1 | libavg/libavg,libavg/libavg,libavg/libavg,libavg/libavg | ---
+++
@@ -5,9 +5,21 @@
import sys
class VideoPlayer(app.MainDiv):
- def init(self):
+
+ def onArgvParserCreated(self, parser):
+ parser.set_usage("%prog <video>")
+
+ def onArgvParsed(self, options, args, parser):
+ if len(args) != 1:
+ parser.print_help()
+ sys.exit... |
97919d06b252af37e7c955ff800b309599e2debc | usingnamespace/forms/user.py | usingnamespace/forms/user.py | import colander
import deform
from csrf import CSRFSchema
class LoginForm(CSRFSchema):
"""The user login form."""
username = colander.SchemaNode(colander.String(),
title="Username",
widget=deform.widget.TextInputWidget(css_class='form-control'),
)
password = colander.Sc... | import colander
import deform
from schemaform import SchemaFormMixin
from csrf import CSRFSchema
class LoginForm(CSRFSchema, SchemaFormMixin):
"""The user login form."""
username = colander.SchemaNode(colander.String(),
title="Username",
__buttons__ = (deform.form.Button(name=_("Submit"), css... | Add SchemaFormMixin to the LoginForm | Add SchemaFormMixin to the LoginForm
| Python | isc | usingnamespace/usingnamespace | ---
+++
@@ -1,12 +1,15 @@
import colander
import deform
+from schemaform import SchemaFormMixin
from csrf import CSRFSchema
-class LoginForm(CSRFSchema):
+class LoginForm(CSRFSchema, SchemaFormMixin):
"""The user login form."""
username = colander.SchemaNode(colander.String(),
title="Use... |
85458434391144aa40101ba9f97c4ec47c975438 | zsh/scripts/pyjson_helper.py | zsh/scripts/pyjson_helper.py | import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument('json_file')
args = parser.parse_args()
if __name__ == '__main__':
with open(args.json_file) as f:
data = json.load(f)
print '\n###'
print 'Loaded JSON in variable `data`.'
print '###'
| import argparse
import json
import inspect
parser = argparse.ArgumentParser()
parser.add_argument('json_file')
args = parser.parse_args()
def load_json(json_file):
with open(json_file) as f:
return json.load(f)
if __name__ == '__main__':
data = load_json(args.json_file)
print '\n'
print inspe... | Print code used to load json in python helper | zsh: Print code used to load json in python helper
| Python | mit | achalddave/dotfiles,achalddave/dotfiles | ---
+++
@@ -1,13 +1,19 @@
import argparse
import json
+import inspect
parser = argparse.ArgumentParser()
parser.add_argument('json_file')
args = parser.parse_args()
+def load_json(json_file):
+ with open(json_file) as f:
+ return json.load(f)
+
if __name__ == '__main__':
- with open(args.json_f... |
4102320e908dfa6e2fc320d73f118670ad5b1501 | tests/basics/fun_name.py | tests/basics/fun_name.py | def Fun():
pass
class A:
def __init__(self):
pass
def Fun(self):
pass
try:
print(Fun.__name__)
print(A.__init__.__name__)
print(A.Fun.__name__)
print(A().Fun.__name__)
except AttributeError:
print('SKIP')
raise SystemExit
# __name__ of a bound native method is not ... | def Fun():
pass
class A:
def __init__(self):
pass
def Fun(self):
pass
try:
print(Fun.__name__)
print(A.__init__.__name__)
print(A.Fun.__name__)
print(A().Fun.__name__)
except AttributeError:
print('SKIP')
raise SystemExit
# __name__ of a bound native method is not ... | Add test for getting name of func with closed over locals. | tests/basics: Add test for getting name of func with closed over locals.
Tests correct decoding of the prelude to get the function name.
| Python | mit | pozetroninc/micropython,adafruit/circuitpython,MrSurly/micropython,henriknelson/micropython,selste/micropython,kerneltask/micropython,trezor/micropython,pozetroninc/micropython,selste/micropython,pozetroninc/micropython,pramasoul/micropython,kerneltask/micropython,henriknelson/micropython,henriknelson/micropython,tobba... | ---
+++
@@ -22,3 +22,11 @@
str((1).to_bytes.__name__)
except AttributeError:
pass
+
+# name of a function that has closed over variables
+def outer():
+ x = 1
+ def inner():
+ return x
+ return inner
+print(outer.__name__) |
8fa89c8642721896b7b97ff928bc66e65470691a | pinax/stripe/tests/test_utils.py | pinax/stripe/tests/test_utils.py | import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import convert_tstamp, plan_from_stripe_id
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(
sta... | import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import convert_tstamp
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(
stamp,
datet... | Remove test for function that no longer exists | Remove test for function that no longer exists
| Python | mit | pinax/django-stripe-payments | ---
+++
@@ -3,7 +3,7 @@
from django.test import TestCase
from django.utils import timezone
-from ..utils import convert_tstamp, plan_from_stripe_id
+from ..utils import convert_tstamp
class TestTimestampConversion(TestCase):
@@ -35,15 +35,3 @@
stamp,
None
)
-
-
-class TestP... |
27b1d403540503f6e9d0ccd679918e3efe63ecf7 | tests/test_navigation.py | tests/test_navigation.py | def get_menu_titles(page) -> list:
page.wait_for_load_state()
menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a")
return [title.as_element().inner_text() for title in menu_list]
flag = True
def test_check_titles(page):
global flag
if(flag):
page.goto("i... | def get_menu_titles(page) -> list:
page.wait_for_load_state()
menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a")
return [title.as_element().inner_text() for title in menu_list]
flag = True
def test_check_titles(page):
global flag
if(flag):
page.goto("i... | Delete debug comments and tool | Delete debug comments and tool
| Python | agpl-3.0 | PyAr/PyZombis,PyAr/PyZombis,PyAr/PyZombis | ---
+++
@@ -12,7 +12,6 @@
global flag
if(flag):
page.goto("index.html")
- page.set_viewport_size({"width": 1050, "height": 600})
menu_list = get_menu_titles(page)
page.wait_for_load_state()
for menu_item in menu_list:
@@ -23,10 +22,6 @@
page_title = page.title().split... |
508c9ef5f7dfd974fdad650cf1a211dad9d41db5 | skipper/config.py | skipper/config.py | from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('c... | from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('c... | Handle env vars in volumes | Handle env vars in volumes
| Python | apache-2.0 | Stratoscale/skipper,Stratoscale/skipper | ---
+++
@@ -23,7 +23,7 @@
normalized_config[key] = {}
_normalize_config(value, normalized_config[key])
elif isinstance(value, list):
- normalized_config[key] = value
+ normalized_config[key] = [_interpolate_env_vars(x) for x in value]
else:
... |
1e150c4d5797f17ba8bea53d328cb613adc6bc0f | self_play.py | self_play.py | import random
from game import Game, DiscState
class SelfPlay:
def __init__(self, game):
self.game = game
def play(self):
while self.game.winner is None:
col_index = self.calc_move(self.game.current_player)
if self.game.can_add_disc(col_index):
success = self.game.try_turn(self.game.... | import random
from game import Game, DiscState
class SelfPlay:
def __init__(self, game):
self.game = game
self.log = []
def play(self):
while self.game.winner is None:
col_index = self.calc_move(self.game.current_player)
if self.game.can_add_disc(col_index):
success = self.game.t... | Add log to self play | Add log to self play
| Python | mit | misterwilliam/connect-four | ---
+++
@@ -6,6 +6,7 @@
def __init__(self, game):
self.game = game
+ self.log = []
def play(self):
while self.game.winner is None:
@@ -13,6 +14,7 @@
if self.game.can_add_disc(col_index):
success = self.game.try_turn(self.game.current_player, col_index)
assert success
+ ... |
4dabc48455ebb8f22d37cd964ceb16373f784362 | mothermayi/colors.py | mothermayi/colors.py | BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def green(text):
return GREEN + text + ENDC
def red(text):
return RED + text + ENDC
| BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def green(text):
return GREEN + text + ENDC
def red(text):
return RED + text + ENDC
def yellow(text):
return YELLOW + text + ENDC
| Add a function for getting yellow | Add a function for getting yellow
| Python | mit | EliRibble/mothermayi | ---
+++
@@ -11,3 +11,6 @@
def red(text):
return RED + text + ENDC
+
+def yellow(text):
+ return YELLOW + text + ENDC |
70cc77a9146f9d4afd78df9a2f8da8673f0320de | extractor.py | extractor.py | import extractor.ui.mainapplication as ui
import Tkinter as tk
def main():
## root = tk.Tk()
## root.title('SNES Wolfenstein 3D Extractor')
## root.minsize(400, 100)
## ui.MainApplication(root).pack(side="top", fill="both", expand=True)
## root.mainloop()
ui.MainApplication().mainloop()
main()
| import extractor.ui.mainapplication as ui
import Tkinter as tk
def main():
## root = tk.Tk()
## root.title('SNES Wolfenstein 3D Extractor')
## root.minsize(400, 100)
## ui.MainApplication(root).pack(side="top", fill="both", expand=True)
root = ui.MainApplication()
root.mainloop()
main()
| Split program call into two lines. | Split program call into two lines.
| Python | mit | adambiser/snes-wolf3d-extractor | ---
+++
@@ -6,7 +6,7 @@
## root.title('SNES Wolfenstein 3D Extractor')
## root.minsize(400, 100)
## ui.MainApplication(root).pack(side="top", fill="both", expand=True)
-## root.mainloop()
- ui.MainApplication().mainloop()
+ root = ui.MainApplication()
+ root.mainloop()
main() |
316a6583036ca18cfdf1a95a122aa2367237fa2c | get/views.py | get/views.py | from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.all()
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context)
| from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.order_by('-pk')
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context)
| Order download links by pk. | get: Order download links by pk.
| Python | bsd-3-clause | ProgVal/Supybot-website | ---
+++
@@ -4,6 +4,6 @@
from models import DownloadLink
def index(request):
- links = DownloadLink.objects.all()
+ links = DownloadLink.objects.order_by('-pk')
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context) |
1e50bdf90756a79d45b0c35353d007c5dad2abfc | hand_data.py | hand_data.py | import time
from lib import Leap
from lib.Leap import Bone
'''
gets the current frame from controller
for each finger, stores the topmost end of each bone (4 points)
adjusts bone location relativity by subtracting the center of the palm
returns the adjusted bone locations in the form:
[(finger1bone1x, finger1bone1y, f... | import time
from lib import Leap
from lib.Leap import Bone
'''
gets the current frame from controller
for each finger, stores the topmost end of each bone (4 points)
adjusts bone location relativity by subtracting the center of the palm
returns the adjusted bone locations in the form:
{feat0=some_float, feat1=some_flo... | Return hand data as dictionary | Return hand data as dictionary
| Python | mit | ssaamm/sign-language-tutor,ssaamm/sign-language-translator,ssaamm/sign-language-translator,ssaamm/sign-language-tutor | ---
+++
@@ -7,7 +7,7 @@
for each finger, stores the topmost end of each bone (4 points)
adjusts bone location relativity by subtracting the center of the palm
returns the adjusted bone locations in the form:
-[(finger1bone1x, finger1bone1y, finger1bone1z), ... finger5bone4z)]
+{feat0=some_float, feat1=some_float, ... |
33f94c28500c96841b1bf5ce507e418364ea556f | StarWebTkeDesenv.py | StarWebTkeDesenv.py | import urllib.parse
import urllib.request
import http.cookiejar
url = 'http://stwebdv.thyssenkruppelevadores.com.br/scripts/gisdesenv.pl/swfw3.r'
values = {'usuario' : 'admin',
'senha' : 'tke'}
cj = http.cookiejar.CookieJar()
data = urllib.parse.urlencode(values).encode('utf-8')
opener = urllib.request.buil... | import urllib.parse
import urllib.request
import http.cookiejar
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
loginUrl = 'http://stwebdv.thyssenkruppelevadores.com.br/scripts/gisdesenv.pl/swfw3.r'
loginData = {'usuario' : 'admin', 'senha' : 'tke'}
postDa... | Add files to be compiled. | Add files to be compiled.
| Python | mit | taschetto/sublimeSettings,taschetto/sublimeSettings | ---
+++
@@ -2,15 +2,22 @@
import urllib.request
import http.cookiejar
-url = 'http://stwebdv.thyssenkruppelevadores.com.br/scripts/gisdesenv.pl/swfw3.r'
-values = {'usuario' : 'admin',
- 'senha' : 'tke'}
+cj = http.cookiejar.CookieJar()
+opener = urllib.request.build_opener(urllib.request.HTTPCookieProce... |
4bd6ed79562435c3e2ef96472f6990109c482117 | deen/constants.py | deen/constants.py | import sys
__version__ = '0.9.1'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... | import sys
__version__ = '0.9.2'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... | Add X509 support only when pyOpenSSL is installed | Add X509 support only when pyOpenSSL is installed
| Python | apache-2.0 | takeshixx/deen,takeshixx/deen | ---
+++
@@ -1,6 +1,6 @@
import sys
-__version__ = '0.9.1'
+__version__ = '0.9.2'
ENCODINGS = ['Base64',
'Base64 URL',
@@ -27,7 +27,14 @@
'NTLM',
'Whirlpool']
-MISC = ['X509Certificate']
+MISC = []
+
+try:
+ import OpenSSL.crypto
+except ImportError:
+ pass
+else:
+ M... |
ff06ce55d0856cff774bdec5f0e872e093216bce | diffs/__init__.py | diffs/__init__.py | from __future__ import absolute_import, unicode_literals
from django.apps import apps as django_apps
from .signals import connect
__version__ = '0.0.1'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(klass):
"""
Decorator function that registers a class to record diffs... | from __future__ import absolute_import, unicode_literals
from .signals import connect
__version__ = '0.0.1'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(klass):
"""
Decorator function that registers a class to record diffs.
@register
class ExampleModel(model... | Reorganize imports to be later | Reorganize imports to be later
| Python | mit | linuxlewis/django-diffs | ---
+++
@@ -1,6 +1,4 @@
from __future__ import absolute_import, unicode_literals
-
-from django.apps import apps as django_apps
from .signals import connect
@@ -18,8 +16,10 @@
class ExampleModel(models.Model):
...
"""
+ from django.apps import apps as django_apps
+ from dirtyfields impo... |
d0728b29514c0731dedee662ce19e73181bc4c34 | pyfarm/models/gpu.py | pyfarm/models/gpu.py | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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/lice... | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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/lice... | Fix docstring for module (minor) | Fix docstring for module (minor)
| Python | apache-2.0 | pyfarm/pyfarm-master,pyfarm/pyfarm-master,pyfarm/pyfarm-master | ---
+++
@@ -16,7 +16,7 @@
"""
GPU
--------
+---
Model describing a given make and model of graphics card.
Every agent can have zero or more GPUs associated with it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.