commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e53715c6ee7896d459a46c810480b12dc7a6b5ad
tg/dottednames/jinja_lookup.py
tg/dottednames/jinja_lookup.py
"""Genshi template loader that supports dotted names.""" from os.path import exists, getmtime from jinja2.exceptions import TemplateNotFound from jinja2.loaders import FileSystemLoader from tg import config class JinjaTemplateLoader(FileSystemLoader): """Jinja template loader supporting dotted filenames. Based...
"""Genshi template loader that supports dotted names.""" from os.path import exists, getmtime from jinja2.exceptions import TemplateNotFound from jinja2.loaders import FileSystemLoader from tg import config class JinjaTemplateLoader(FileSystemLoader): """Jinja template loader supporting dotted filenames. Based...
Fix jinja loader on Py3
Fix jinja loader on Py3
Python
mit
lucius-feng/tg2,lucius-feng/tg2
2a83a1606ffb7e761592a5b0a73e31d9b8b1fe08
bin/example_game_programmatic.py
bin/example_game_programmatic.py
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_we...
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_we...
Add Game.process_input use to example code
Add Game.process_input use to example code
Python
unlicense
mmurdoch/Vengeance,mmurdoch/Vengeance
23b54e836a94a2d1ebdb919a30d19ca4523d45b5
project_template.py
project_template.py
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.fol...
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.fol...
Implement selecting template by quick panel
Implement selecting template by quick panel
Python
mit
autopp/SublimeProjectTemplate,autopp/SublimeProjectTemplate
9f71fd2df043bc6eedbd945100633d3184356c89
tools/pyhande/pyhande/utils.py
tools/pyhande/pyhande/utils.py
'''Utility procedures for manipulating HANDE data.''' import numpy as np def groupby_beta_loops(data): '''Group a HANDE DMQMC data table by beta loop. Parameters ---------- data : :class:`pandas.DataFrame` DMQMC data table (e.g. obtained by :func:`pyhande.extract.extract_data`. Returns ------- grouped : :cl...
'''Utility procedures for manipulating HANDE data.''' import numpy as np def groupby_beta_loops(data, name='iterations'): '''Group a HANDE DMQMC data table by beta loop. Parameters ---------- data : :class:`pandas.DataFrame` DMQMC data table (e.g. obtained by :func:`pyhande.extract.extract_data`. Returns --...
Correct location of bracket so that grouping by beta loops is done correctly.
Correct location of bracket so that grouping by beta loops is done correctly.
Python
lgpl-2.1
hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,ruthfranklin/hande,hande-qmc/hande,hande-qmc/hande
7a8a2556bbeb255c991aa5a39aa04b4fed238a7b
kolibri/plugins/setup_wizard/middleware.py
kolibri/plugins/setup_wizard/middleware.py
from django.core.urlresolvers import reverse from django.shortcuts import redirect from kolibri.auth.models import DeviceOwner ALLOWED_PATH_LIST = [ "facility-list", "deviceowner-list", "kolibri:setupwizardplugin:setupwizard", "task-localdrive", "task-startremoteimport", "task-list", ] class...
from django.core.urlresolvers import reverse from django.shortcuts import redirect from kolibri.auth.models import DeviceOwner ALLOWED_PATH_LIST = [ "facility-list", "deviceowner-list", "kolibri:setupwizardplugin:setupwizard", "task-localdrive", "task-startremoteimport", "task-list", "sess...
Add 'session-list' to constants list.
Add 'session-list' to constants list.
Python
mit
DXCanas/kolibri,christianmemije/kolibri,learningequality/kolibri,jonboiser/kolibri,jonboiser/kolibri,rtibbles/kolibri,aronasorman/kolibri,learningequality/kolibri,rtibbles/kolibri,christianmemije/kolibri,jayoshih/kolibri,jayoshih/kolibri,jayoshih/kolibri,learningequality/kolibri,christianmemije/kolibri,DXCanas/kolibri,...
46c0543306d11551f9c818922dc2b2b4bf3d3b4d
byceps/services/email/service.py
byceps/services/email/service.py
""" byceps.services.email.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import List, Optional from ... import email from ...typing import BrandID from .models import EmailConfig def find_sender_address_for_brand(br...
""" byceps.services.email.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import List, Optional from ... import email from ...typing import BrandID from ...util.jobqueue import enqueue from .models import EmailConfig ...
Add function to enqueue e-mails to be sent asynchronously rather than blocking/sending synchronously
Add function to enqueue e-mails to be sent asynchronously rather than blocking/sending synchronously
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
77ac03544f85e95603507e1dc0cec2189e0d5a03
get_ip.py
get_ip.py
#!/usr/bin/python # # Get private IPv4s for a given instance name. # import boto import boto.ec2 import getopt import sys # # Get the profile # def connect(region): profile = metadata['iam']['info']['InstanceProfileArn'] profile = profile[profile.find('/') + 1:] conn = boto.ec2.connection.EC2Connection( ...
#!/usr/bin/python # # Get private IPv4s for a given instance name. # import boto import boto.ec2 import getopt import sys # # Get the profile # def connect(): metadata = boto.utils.get_instance_metadata() region = metadata['placement']['availability-zone'][:-1] profile = metadata['iam']['info']['InstanceP...
Add python script for IPs discovery
Add python script for IPs discovery
Python
bsd-3-clause
GetStream/Stream-Framework-Bench,GetStream/Stream-Framework-Bench
7fabf481ed788350aa0c94eec7c71d6cfb75c14a
store/forms.py
store/forms.py
from django import forms from .models import Review class ReviewForm(forms.models.ModelForm): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'placeholder': 'Your Name', 'class': 'form-control', }), ) ...
from django import forms from .models import Review class ReviewForm(forms.models.ModelForm): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'placeholder': 'Your Name', 'class': 'form-control', }), ) ...
Add product field to ReviewForm
Add product field to ReviewForm
Python
bsd-3-clause
kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop
8a6015610bba2dcdc0a2cb031b2f58606328841f
src/fastpb/generator.py
src/fastpb/generator.py
#!/usr/bin/env python import plugin_pb2 from jinja2 import Template from pkg_resources import resource_string import os.path import sys import tempfile def main(): log = sys.stderr request = plugin_pb2.CodeGeneratorRequest() request.ParseFromString(sys.stdin.read()) path = tempfile.mkdtemp() generateF...
#!/usr/bin/env python import plugin_pb2 from jinja2 import Template from pkg_resources import resource_string import os.path import sys import tempfile def main(): request = plugin_pb2.CodeGeneratorRequest() request.ParseFromString(sys.stdin.read()) response = plugin_pb2.CodeGeneratorResponse() generateF...
Use protoc for file output
Use protoc for file output
Python
apache-2.0
Cue/fast-python-pb
fae5db20daa1e7bcb1b915ce7f3ca84ae8bd4a1f
client/scripts/install-plugin.py
client/scripts/install-plugin.py
import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old versio...
import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old versio...
Update relative path with respect to __file__
Update relative path with respect to __file__
Python
mit
qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv
1d1e8fb72fe578adb871d22accdde60bedff48c6
housemarket/housesales/management/commands/fillsalesdb.py
housemarket/housesales/management/commands/fillsalesdb.py
from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = ('Load house sales data from a CSV and save it into DB') def handle(self, *args, **options): pass
from django.core.management.base import BaseCommand from django.db import transaction from housesales.models import HouseSales import csv from datetime import datetime class Command(BaseCommand): help = ('Load house sales data from a CSV and save it into DB') def add_arguments(self, parser): parser...
Improve performance of db import utility
Improve performance of db import utility
Python
mit
andreagrandi/sold-house-prices
025b356ad4bbaa81ef98467d3c3abd3c8fba98b8
skbio/format/sequences/tests/test_fastq.py
skbio/format/sequences/tests/test_fastq.py
#!/usr/bin/env python import numpy as np from unittest import TestCase, main from skbio.format.sequences.fastq import (format_fastq_record, _phred_to_ascii33, _phred_to_ascii64) class FASTQFormatTests(TestCase): def test_format_f...
#!/usr/bin/env python import numpy as np from unittest import TestCase, main from skbio.format.sequences.fastq import (format_fastq_record, _phred_to_ascii33, _phred_to_ascii64) class FASTQFormatTests(TestCase): def setUp(self): ...
Add tests for different types of phred offsets
Add tests for different types of phred offsets
Python
bsd-3-clause
corburn/scikit-bio,anderspitman/scikit-bio,johnchase/scikit-bio,SamStudio8/scikit-bio,anderspitman/scikit-bio,averagehat/scikit-bio,wdwvt1/scikit-bio,kdmurray91/scikit-bio,demis001/scikit-bio,SamStudio8/scikit-bio,jdrudolph/scikit-bio,gregcaporaso/scikit-bio,corburn/scikit-bio,johnchase/scikit-bio,jairideout/scikit-bio...
89796f6cc61a2e5de18c372468ac1e91b4790085
test/test_get_new.py
test/test_get_new.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir, create_update_dir import os @needinternet def test_check_get_new(fixture_update_dir, create_update_dir): """Test that gets n...
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir, create_update_dir import os @needinternet def test_check_get_new(fixture_update_dir, create_update_dir): """Test that gets n...
Update test for changed filename
Update test for changed filename
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
96a5388fcb8f1164db4612f4049d41a72e81ea09
zerver/lib/mandrill_client.py
zerver/lib/mandrill_client.py
import mandrill from django.conf import settings MAIL_CLIENT = None from typing import Optional def get_mandrill_client(): # type: () -> Optional[mandrill.Mandrill] if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT or settings.VOYAGER: return None global MAIL_CLIENT if not MAIL_CLIE...
import mandrill from django.conf import settings MAIL_CLIENT = None from typing import Optional def get_mandrill_client(): # type: () -> Optional[mandrill.Mandrill] if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT: return None global MAIL_CLIENT if not MAIL_CLIENT: MAIL_CLI...
Fix hardcoded check for settings.VOYAGER.
mandrill: Fix hardcoded check for settings.VOYAGER. Since this delayed sending feature is the only thing settings.MANDRILL_API_KEY is used for, it seems reasonable for that to be the gate as to whether we actually use Mandrill.
Python
apache-2.0
jainayush975/zulip,tommyip/zulip,ahmadassaf/zulip,kou/zulip,SmartPeople/zulip,dawran6/zulip,sonali0901/zulip,arpith/zulip,dhcrzf/zulip,ahmadassaf/zulip,arpith/zulip,aakash-cr7/zulip,kou/zulip,sup95/zulip,sharmaeklavya2/zulip,jrowan/zulip,grave-w-grave/zulip,SmartPeople/zulip,aakash-cr7/zulip,jainayush975/zulip,eeshanga...
02854d24db2418fbbd7be399d0abcb10a691810f
test_bert_trainer.py
test_bert_trainer.py
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
Fix merge conflict and also check for equal eval loss
Fix merge conflict and also check for equal eval loss
Python
apache-2.0
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
f1d9c010b58d69cdcf8f55a3e5937cbdf58c10e6
tools/corintick_dump.py
tools/corintick_dump.py
#!/usr/bin/env python import argparse import glob from pytrthree import TRTHIterator from corintick import Corintick, ValidationError def main(args): db = Corintick(args.config) files = glob.glob(args.files) for ric, df in TRTHIterator(files): cols = args.columns if args.columns else df.columns ...
#!/usr/bin/env python import argparse import glob import os from pytrthree import TRTHIterator from corintick import Corintick, ValidationError def main(args): db = Corintick(args.config) files = glob.glob(os.path.expanduser(args.files)) for ric, df in TRTHIterator(files): cols = args.columns if ...
Fix help docstring and glob parsing
Fix help docstring and glob parsing
Python
mit
plugaai/pytrthree
c111410ad8feb6347e1e493c19b32ff9e8230306
zmon_aws_agent/common.py
zmon_aws_agent/common.py
import time import logging from botocore.exceptions import ClientError from zmon_aws_agent import __version__ MAX_RETRIES = 10 TIME_OUT = 0.5 logger = logging.getLogger(__name__) def get_user_agent(): return 'zmon-aws-agent/{}'.format(__version__) def get_sleep_duration(retries): return 2 ** retries * ...
import time import logging from botocore.exceptions import ClientError from zmon_aws_agent import __version__ MAX_RETRIES = 10 TIME_OUT = 0.5 logger = logging.getLogger(__name__) def get_user_agent(): return 'zmon-aws-agent/{}'.format(__version__) def get_sleep_duration(retries): return 2 ** retries * ...
Handle RequestLimitExceeded the same way as Throttling response
Handle RequestLimitExceeded the same way as Throttling response
Python
apache-2.0
zalando/zmon-aws-agent,zalando/zmon-aws-agent
9adb52b4a3295afcaaa4c830835d42ce0bbbb03e
udemy/missingelement.py
udemy/missingelement.py
import collections # Problem: # Consider an array of non-negative integers. A second array is formed # by shuffling the elements of the first array and deleting a random element. # Given these two arrays, find which element is missing in the second array. # # Assume there will always be one missing element in t...
import collections # Problem: # Consider an array of non-negative integers. A second array is formed # by shuffling the elements of the first array and deleting a random element. # Given these two arrays, find which element is missing in the second array. # # Assume there will always be one missing element in t...
Add XOR approach for finding missing element
Add XOR approach for finding missing element Add approach for finding the missing element in the second list by performing a series of XOR operations.
Python
mit
chinhtle/python_fun
30aa7dce0561e1fd8beeec94098a5d6a6f447a65
src/test.py
src/test.py
#!/usr/bin/env python from __future__ import division import numpy as np from matplotlib import pyplot as plt def main(): koeffs = [.3, 1.2, .1, 7] p = np.poly1d(koeffs) x = np.linspace(-2, 2, 100) y = p(x) + 2 * np.random.randn(100) - 1 # fit fit = np.polyfit(x, y, 3) p_fit = np.poly1...
#!/usr/bin/env python from __future__ import division import numpy as np from matplotlib import pyplot as plt def main(): koeffs = [.3, 1.2, .1, 7] p = np.poly1d(koeffs) x = np.linspace(-2, 2, 100) y = p(x) + 2 * np.random.randn(100) - 1 # fit fit = np.polyfit(x, y, 3) p_fit = np.poly1...
Print real and fitted coeffs
Print real and fitted coeffs
Python
mit
bbci/playground
efed9e50dccea80cb536f106044265f8f1e2a32b
models.py
models.py
import peewee db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres') class IBModel(peewee.Model): class Meta: database = db class User(IBModel): user_id = peewee.CharField(max_length=128, primary_key=True) auth_token = peewee.TextField() class Module(IBModel): module_id = peewee.Te...
import os import peewee class IBModel(peewee.Model): class Meta: database = db class User(IBModel): user_id = peewee.CharField(max_length=128, primary_key=True) auth_token = peewee.TextField() class Module(IBModel): module_id = peewee.TextField() module_code = peewee.CharField(max_length=...
Set up database according to environment
Set up database according to environment
Python
mit
karen/ivle-bot,karenang/ivle-bot
32587292baab9ed1d994fc1643d4bc004832a575
viper/parser/grammar.py
viper/parser/grammar.py
from .languages import SPPF, make_sppf from .linguify_grammar import linguify_grammar_file from viper.lexer import Lexeme from os.path import join, dirname from typing import List class Grammar: def __init__(self, grammar_filename: str): self.file = grammar_filename self.rules = linguify_grammar...
from .ast import ASTNode from .languages import ParseTreeChar, make_sppf from .linguify_grammar import linguify_grammar_file from viper.lexer import Lexeme from os.path import join, dirname from typing import List class Grammar: def __init__(self, grammar_filename: str): self.file = grammar_filename ...
Revise top-level parse function to return ASTNode
Revise top-level parse function to return ASTNode
Python
apache-2.0
pdarragh/Viper
bef1e44e027284e193be889b5ca273c906ae8325
snippets/__main__.py
snippets/__main__.py
import argparse import sys from .generator import Generator from .repository import Repository def run(args=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument('path') parser.add_argument('-o', '--output', default='output') parser.add_argument('-t', '--theme') args = parser.pars...
import argparse import sys from .generator import Generator from .repository import Repository def run(args=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', default='snippets') parser.add_argument('-o', '--output', default='output') parser.add_argument('-t', '--...
Make repository source optional in cli
Make repository source optional in cli
Python
isc
trilan/snippets,trilan/snippets
8f03f4fc5b4b321303225ec60879eb4b6a2c14f5
cli/cli.py
cli/cli.py
import argparse parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser('list', help='List commands') list_p...
import argparse parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser('list', help='List commands') list_p...
Add subparser for run analytics commands
Add subparser for run analytics commands
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
1101fd3855c90ece679e4b9af37c5f3f5dc343eb
spacy/en/__init__.py
spacy/en/__init__.py
# coding: utf8 from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data imp...
# coding: utf8 from __future__ import unicode_literals from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * try: basestring except N...
Fix formatting and remove unused imports
Fix formatting and remove unused imports
Python
mit
recognai/spaCy,raphael0202/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaC...
572207d26c51038b679832b24b2e8381209e6f87
collect.py
collect.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os from collector.acled_africa import generate_urls from collector.parser import parse from collector.register import create_datasets, create_resources, create_gallery_items def main(): ''' Wrapper. ''' server = 'http://test-data.hdx.rwlabs.org' o...
#!/usr/bin/python # -*- coding: utf-8 -*- import os from collector.acled_africa import generate_urls from collector.parser import parse from collector.register import create_datasets, create_resources, create_gallery_items def main(): ''' Wrapper. ''' firstrun = False server = 'http://test-data....
Make subsequent runs only update resources
Make subsequent runs only update resources
Python
mit
mcarans/hdxscraper-acled-africa,mcarans/hdxscraper-acled-africa
1ef70820acb57c54f1212777e60b32db9b47c8a5
examples/python/test_axis_precision.py
examples/python/test_axis_precision.py
#!/usr/bin/env python # Append to effective python path so that can find plplot modules. from plplot_python_start import * import sys from plplot import * from numpy import * # Parse and process command line arguments plparseopts(sys.argv, PL_PARSE_FULL) # Initialize plplot plinit() plsyax(10000, 0) pladv(0) plvpor...
#!/usr/bin/env python # Append to effective python path so that can find plplot modules. from plplot_python_start import * import sys from plplot import * from numpy import * # Parse and process command line arguments plparseopts(sys.argv, PL_PARSE_FULL) # Initialize plplot plinit() # Choose 5 here so there is room...
Use less ridiculous value of ydigmax specified via plsyax. This works well (i.e., gives non-exponential notation for the Y axis) with the recent pldprec change in pldtik.c which removes the ceiling on digfix and simply sets it to digmax.
Use less ridiculous value of ydigmax specified via plsyax. This works well (i.e., gives non-exponential notation for the Y axis) with the recent pldprec change in pldtik.c which removes the ceiling on digfix and simply sets it to digmax. svn path=/trunk/; revision=10608
Python
lgpl-2.1
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
e144820c974548a549d0428a3b439fc0688bd2b2
tests/test_pathutils.py
tests/test_pathutils.py
from os.path import join import sublime import sys from unittest import TestCase from unittest.mock import patch version = sublime.version() try: from libsass import pathutils except ImportError: from sublime_libsass.libsass import pathutils class TestPathutils(TestCase): def test_subpaths(self): ...
from os.path import join import sublime import sys from unittest import TestCase from unittest.mock import patch version = sublime.version() try: from libsass import pathutils except ImportError: from sublime_libsass.libsass import pathutils class TestPathutils(TestCase): def test_subpaths(self): ...
Use patch.object for python 2 compat
Use patch.object for python 2 compat
Python
mit
blitzrk/sublime_libsass,blitzrk/sublime_libsass
595dfa67764a525bcff864e1ddc513496f1376df
microcosm_postgres/temporary/copy.py
microcosm_postgres/temporary/copy.py
""" Copy a table. """ from sqlalchemy import Table def copy_table(from_table, name): """ Copy a table. Based on `Table.tometadata`, but simplified to remove constraints and indexes. """ metadata = from_table.metadata if name in metadata.tables: return metadata.tables[name] sch...
""" Copy a table. """ from sqlalchemy import Table from microcosm_postgres.types import Serial def copy_column(column, schema): """ Safely create a copy of a column. """ return column.copy(schema=schema) def should_copy(column): """ Determine if a column should be copied. """ if ...
Handle serial values on temporary table creation
Handle serial values on temporary table creation Do not copy serial columns because they will be generated automatically if and only they are omitted from the insert().select_from().
Python
apache-2.0
globality-corp/microcosm-postgres,globality-corp/microcosm-postgres
064c0161e91e24217d712cb80656a2d0dad8c3b6
pretty.py
pretty.py
from termcolor import colored def section(msg): print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"])) def task(msg): print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"])) def subtask(msg): print(colored(" ->", "blue", attrs=["bold"]), colored(msg, attrs=["bold"...
from termcolor import colored import datetime def section(msg): print(colored("\n::", "blue", attrs=["bold"]), colored(msg, attrs=["bold"])) def task(msg): print(colored("==>", "green", attrs=["bold"]), colored(msg, attrs=["bold"])) def subtask(msg): print(colored(" ->", "blue", attrs=["bold"]), colored(ms...
Fix progress bar to be 80-col-friendly.
Fix progress bar to be 80-col-friendly.
Python
mit
jonhoo/periscope,jonhoo/periscope
42755823774f4a57849c54d5812e885dfbeee34c
camelot/roundtable/migrations/0002_add_knight_data.py
camelot/roundtable/migrations/0002_add_knight_data.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_knight_data(apps, schema_editor): pass def remove_knight_data(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ...
Use RunPython operation to perform data migration.
Use RunPython operation to perform data migration.
Python
bsd-2-clause
jambonrose/djangocon2014-updj17
2250180ea7cc0eb91c8b1cdc7d565397326f480b
UM/Scene/SceneNodeDecorator.py
UM/Scene/SceneNodeDecorator.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. class SceneNodeDecorator(): def __init__(self): super().__init__() self._node = None def setNode(self, node): self._node = node
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. class SceneNodeDecorator(): def __init__(self): super().__init__() self._node = None def setNode(self, node): self._node = node def getNode(self): return self._node
Add a getter for a Decorator's Scene Node
Add a getter for a Decorator's Scene Node
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
2301b0bfdb216f31428e6c9ca0bf6b2951a5e64b
symposion/forms.py
symposion/forms.py
from django import forms import account.forms class SignupForm(account.forms.SignupForm): first_name = forms.CharField() last_name = forms.CharField() email_confirm = forms.EmailField(label="Confirm Email") def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwarg...
try: from collections import OrderedDict except ImportError: OrderedDict = None import account.forms from django import forms from django.utils.translation import ugettext_lazy as _ class SignupForm(account.forms.SignupForm): first_name = forms.CharField(label=_("First name")) last_name = forms.Char...
Fix order fields in signup form
Fix order fields in signup form
Python
bsd-3-clause
toulibre/symposion,toulibre/symposion
18d973d71255d389369cc4450f721512a13ad6cb
src/impl/geocoder.py
src/impl/geocoder.py
import geopy from rate_limiter import RateLimiter class Geocoder(object): def __init__(self, api_key=None, client_id=None, secret_key=None): if api_key: self._geolocator = geopy.GoogleV3(api_key=api_key) elif client_id and secret_key: self._geolocator = geopy.GoogleV3(clie...
from Geohash import geohash import geopy from rate_limiter import RateLimiter class Geocoder(object): def __init__(self, api_key=None, client_id=None, secret_key=None, reverse_cache_geohash=9): if api_key: self._geolocator = geopy.GoogleV3(api_key=api_key) elif client_id and secret_ke...
Add in-memory geohash cache for reverse geocoding.
Add in-memory geohash cache for reverse geocoding.
Python
mit
cbigler/jackrabbit-googlev3-geocoder
08a95f7793d496d36cc0a753694c2975b2f30c68
accelerator/migrations/0074_update_url_to_community.py
accelerator/migrations/0074_update_url_to_community.py
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator',...
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = ["/people", "/people"] mentor_url = "/directory" mentor_refinement_url = "/directory/?refinementList%5Bhome_program_f...
Add another constraint for the url
[AC-9046] Add another constraint for the url
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
a460713d36e8310a9f975d13d49579e77d83dfe7
examples/with-shapely.py
examples/with-shapely.py
import logging import sys from shapely.geometry import mapping, shape from fiona import collection logging.basicConfig(stream=sys.stderr, level=logging.INFO) with collection("docs/data/test_uk.shp", "r") as input: schema = input.schema.copy() with collection( "with-shapely.shp", "w",...
import logging import sys from shapely.geometry import mapping, shape from fiona import collection logging.basicConfig(stream=sys.stderr, level=logging.INFO) with collection("docs/data/test_uk.shp", "r") as input: schema = input.schema.copy() with collection( "with-shapely.shp", "w",...
Fix validity assertion and add another.
Fix validity assertion and add another.
Python
bsd-3-clause
johanvdw/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona,perrygeo/Fiona,sgillies/Fiona,rbuffat/Fiona
d7f078dca52afbd081760262498200990c318e95
allaccess/tests/__init__.py
allaccess/tests/__init__.py
from .test_backends import AuthBackendTestCase from .test_clients import OAuthClientTestCase, OAuth2ClientTestCase from .test_context_processors import AvailableProvidersTestCase from .test_models import ProviderTestCase, AccountAccessTestCase from .test_views import OAuthRedirectTestCase, OAuthCallbackTestCase
from .test_backends import AuthBackendTestCase from .test_clients import OAuthClientTestCase, OAuth2ClientTestCase from .test_commands import MigrateProvidersTestCase from .test_context_processors import AvailableProvidersTestCase from .test_models import ProviderTestCase, AccountAccessTestCase from .test_views import ...
Add import for test discovery prior to Django 1.6
Add import for test discovery prior to Django 1.6
Python
bsd-2-clause
mlavin/django-all-access,vyscond/django-all-access,iXioN/django-all-access,dpoirier/django-all-access,mlavin/django-all-access,vyscond/django-all-access,dpoirier/django-all-access,iXioN/django-all-access
0ae9fcccb1c67a8d9337e4ef2887fb7ea2e01d51
mpltools/io/core.py
mpltools/io/core.py
import os import matplotlib.pyplot as plt def save_all_figs(directory='./', fmt=None, default_name='untitled%i'): """Save all open figures. Each figure is saved with the title of the plot, if possible. Parameters ------------ directory : str Path where figures are saved. fmt : str, l...
import os import matplotlib.pyplot as plt def save_all_figs(directory='./', fmt=None, default_name='untitled%i'): """Save all open figures. Each figure is saved with the title of the plot, if possible. Parameters ------------ directory : str Path where figures are saved. fmt : str, l...
Refactor formatting of save name.
Refactor formatting of save name.
Python
bsd-3-clause
tonysyu/mpltools,matteoicardi/mpltools
2e28cf549bd7de29143c317871008b3115e44975
tests/vstb-example-html5/tests/rotate.py
tests/vstb-example-html5/tests/rotate.py
# pylint: disable=F0401 from stbt import press, wait_for_match def wait_for_vstb_startup(): wait_for_match('stb-tester-350px.png') def test_that_image_is_rotated_by_arrows(): press("KEY_LEFT") wait_for_match('stb-tester-left.png') press("KEY_RIGHT") wait_for_match('stb-tester-right.png') pre...
# pylint: disable=F0401 from stbt import press, wait_for_match def wait_for_vstb_startup(): wait_for_match('stb-tester-350px.png', timeout_secs=20) def test_that_image_is_rotated_by_arrows(): press("KEY_LEFT") wait_for_match('stb-tester-left.png') press("KEY_RIGHT") wait_for_match('stb-tester-ri...
Fix virtual-stb intermittant test-failure on Travis
Fix virtual-stb intermittant test-failure on Travis test_that_virtual_stb_configures_stb_tester_for_testing_virtual_stbs fails intermittently on Travis because sometimes chrome takes longer than 10s to start-up. This causes the test to fail with: > MatchTimeout: Didn't find match for '.../stb-tester-350px.png' withi...
Python
lgpl-2.1
LewisHaley/stb-tester,LewisHaley/stb-tester,martynjarvis/stb-tester,martynjarvis/stb-tester,LewisHaley/stb-tester,LewisHaley/stb-tester,LewisHaley/stb-tester,stb-tester/stb-tester,stb-tester/stb-tester,LewisHaley/stb-tester,LewisHaley/stb-tester,stb-tester/stb-tester,martynjarvis/stb-tester,stb-tester/stb-tester,martyn...
5f9ce264d8b2d16cf951a52f05dc251358783638
run.py
run.py
#!venv/bin/python from app import app if __name__ == '__main__': app.run()
#!venv/bin/python from app import app if __name__ == '__main__': app.run(host='0.0.0.0')
Make dev server visible across internal network
Make dev server visible across internal network
Python
mit
CapitalD/taplist,CapitalD/taplist,CapitalD/taplist
8f1536ce63e276964648e2938a8200c1fb1dd3a7
api/utils/custom_serializers.py
api/utils/custom_serializers.py
import time from rest_framework import serializers class TimeStampField(serializers.Field): def to_internal_value(self, data): pass def to_representation(self, value): return int(time.mktime(value.timetuple()))
import time from rest_framework import serializers class TimeStampField(serializers.Field): def to_internal_value(self, data): pass def to_representation(self, value): try: return int(time.mktime(value.timetuple())) except OverflowError: return 0
Fix exception on dates older then 1970
Fix exception on dates older then 1970
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
c8ad376bbb44bcae317fc09cee43cfc31dc70ded
src/hades/config/base.py
src/hades/config/base.py
class OptionMeta(type): """Metaclass for options. Classes that derive from options are registered in a global dict""" options = {} def __new__(mcs, name, bases, attributes): if name in mcs.options: raise TypeError("An option named {} is already defined." ...
class OptionMeta(type): """ Metaclass for options. Classes with this metaclass, which are named not declared abstract by setting the abstract keyword argument are added to the :attr:`.options` dictionary. """ options = {} def __new__(mcs, name, bases, attributes, abstract=False): ...
Add ability to define abstract options classes
Add ability to define abstract options classes Only actual options should be added to the options dict of OptionMeta. This patch adds a abstract kwarg to the OptionMeta class, that allows declare, if an option is abstract and should therefore not be added.
Python
mit
agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades
f9a8e5107cc3f9d94f43bd5ce60054f849be2c15
tests/utils.py
tests/utils.py
import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator t...
import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """...
Fix use of Context for dj1.11
Fix use of Context for dj1.11
Python
mit
funkybob/django-sniplates,funkybob/django-sniplates
8095c37e0ab99e9827acbe4621f2fcb9334e1426
games/management/commands/autocreate_steamdb_installers.py
games/management/commands/autocreate_steamdb_installers.py
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = ...
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = ...
Update installer autocreate for games with no icon
Update installer autocreate for games with no icon
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website,Turupawn/website
f87b9dd4674031aceb7e47de37a57ea190ec264d
tmc/exercise_tests/check.py
tmc/exercise_tests/check.py
import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def te...
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) ...
Use a bit better regex for XML error workaround, actually failable compile
Use a bit better regex for XML error workaround, actually failable compile
Python
mit
JuhaniImberg/tmc.py,JuhaniImberg/tmc.py
b0ed850da2573cd8a99fc9f628f2da8a3bc97c71
greenmine/base/monkey.py
greenmine/base/monkey.py
# -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched ...
# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return v...
Send print message to sys.stderr
Smallfix: Send print message to sys.stderr
Python
agpl-3.0
EvgeneOskin/taiga-back,taigaio/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,gauravjns/taiga-back,obimod/taiga-back,dycodedev/taiga-back,WALR/taiga-back,joshisa/taiga-back,bdang2012/taiga-back-casting,Rademade/taiga-back,CMLL/taiga-back,crr0004/taiga-back,taigaio/taiga-back,obimod/taiga-back,dayatz/taiga-ba...
fee78440de784bee91669e6c4f1d2c301202e29d
apps/blogs/serializers.py
apps/blogs/serializers.py
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def t...
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def t...
Add main_image to BlogPost API response.
Add main_image to BlogPost API response.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
8fd5c5c8c7aec1cc045f7f2fcbecb16be129c19b
jobs/templatetags/jobs_tags.py
jobs/templatetags/jobs_tags.py
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingLis...
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page...
Add fix for non pages like search.
Add fix for non pages like search.
Python
mit
OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website
e1a27161621038cc3bdfd4030aef130ee09e92ec
troposphere/dax.py
troposphere/dax.py
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): reso...
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): reso...
Update DAX per 2021-06-24 changes
Update DAX per 2021-06-24 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
94ad884a245dea36110718577e47eb0c7b0c2b0a
skyfield/tests/test_topos.py
skyfield/tests/test_topos.py
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elev...
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large ele...
Add test for subpoint() longitude correctness
Add test for subpoint() longitude correctness
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
88a5a74ee1e3d3f3fe9e6a43bacd73b2f3f5bb96
tests/test_mongo.py
tests/test_mongo.py
import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["con...
import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 ...
Test does start a mongo instance.
Test does start a mongo instance.
Python
bsd-3-clause
jshum/dd-agent,mderomph-coolblue/dd-agent,AniruddhaSAtre/dd-agent,remh/dd-agent,lookout/dd-agent,PagerDuty/dd-agent,Mashape/dd-agent,indeedops/dd-agent,GabrielNicolasAvellaneda/dd-agent,AntoCard/powerdns-recursor_check,citrusleaf/dd-agent,benmccann/dd-agent,gphat/dd-agent,mderomph-coolblue/dd-agent,zendesk/dd-agent,huh...
31c60902c7e09fd01b6b89550df342e5431de961
mysite/profile/search_indexes.py
mysite/profile/search_indexes.py
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_insta...
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValu...
Add a column in the search index for the list of projects.
Add a column in the search index for the list of projects.
Python
agpl-3.0
SnappleCap/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,heeraj123/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,vipul-sharma20/oh-mainline,heeraj123/oh-mainline,openhatch/oh-mainline,willin...
d2bec26a63877e31e2d887e0879a8fd197741147
thinc/t2t.py
thinc/t2t.py
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeaded...
Add import links for MultiHeadedAttention and prepare_self_attention
Add import links for MultiHeadedAttention and prepare_self_attention
Python
mit
spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
310005d0e22b071c1b5ed69cdf2a38371f2f7ec5
cloudenvy/commands/envy_list.py
cloudenvy/commands/envy_list.py
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subp...
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subp...
Print out ENVys with newlines for envy list
Print out ENVys with newlines for envy list
Python
apache-2.0
cloudenvy/cloudenvy
cb7170785af4bf853ff8495aaade520d3b133332
casexml/apps/stock/admin.py
casexml/apps/stock/admin.py
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'sec...
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction l...
Add search fields to stock models
Add search fields to stock models
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsof...
1821577ca19bb05847c37d856896d8e1ce8b3acb
plugins/religion.py
plugins/religion.py
from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headi...
from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=...
Fix .bible: v2 was deprecated, the v3 API requires a key.
Fix .bible: v2 was deprecated, the v3 API requires a key.
Python
unlicense
parkrrr/skybot,TeamPeggle/ppp-helpdesk,crisisking/skybot,jmgao/skybot,rmmh/skybot
3496efef40acc9e204ea9d3129b974ac3e482ca2
direnaj/direnaj_api/celery_app/server_endpoint.py
direnaj/direnaj_api/celery_app/server_endpoint.py
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(...
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(...
Fix for periodic task scheduler (3)
Fix for periodic task scheduler (3)
Python
mit
boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj
9649b145bdb6177de203f575762d3ee9ca70d7e1
bot.py
bot.py
import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jp...
import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) ...
Save Image to File, Open Image if found
Save Image to File, Open Image if found Add image checking using urllib and opencv.
Python
mit
porglezomp/PyDankReddit,powderblock/DealWithItReddit,powderblock/PyDankReddit
b73556be31864eca862618d6f0d5dd5d39c70677
lobster/cmssw/actions.py
lobster/cmssw/actions.py
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): ...
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): ...
Fix overlooked use case for workdir.
Fix overlooked use case for workdir.
Python
mit
matz-e/lobster,matz-e/lobster,matz-e/lobster
402035dd56261bce17a63b64bed810efdf14869e
exponent/substore.py
exponent/substore.py
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore...
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore...
Document exception raised when a store does not exist
Document exception raised when a store does not exist
Python
isc
lvh/exponent
f622e11536c4ebf8f82985329d06efc58c2fe60e
blog/tests/test_views.py
blog/tests/test_views.py
from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self):
from django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Cate...
Add tests for blog index view and post view
Add tests for blog index view and post view
Python
mit
ajoyoommen/weblog,ajoyoommen/weblog
2022c5485289712b8de22fe551d65cf005442826
massa/domain/__init__.py
massa/domain/__init__.py
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(val...
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(val...
Change error message of the weight validator.
Change error message of the weight validator.
Python
mit
jaapverloop/massa
a4808284731ebcc7ae9c29bfeee4db7e943e1b2a
pyinfra/__init__.py
pyinfra/__init__.py
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # no...
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noq...
Add default for `is_cli` to pyinfra.
Add default for `is_cli` to pyinfra.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
27ce88988f22bfb1b3a6ba584da6162b9037b0fa
pony/thirdparty/compiler/__init__.py
pony/thirdparty/compiler/__init__.py
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler...
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler...
Remove deprecation warning from compiler package
Remove deprecation warning from compiler package
Python
apache-2.0
gwecho/pony,gwecho/pony,ponyorm/pony,ponyorm/pony,ponyorm/pony,gwecho/pony,ponyorm/pony
768470b75c0256c933f16856a9754302e5c43bc2
db/sql_server/pyodbc.py
db/sql_server/pyodbc.py
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff a...
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_ta...
Add column support for sql server
Add column support for sql server
Python
apache-2.0
matthiask/south,matthiask/south
7f98aaeda38d7a30ab20ddc1d6ce7ae17d42f358
dduplicated/commands.py
dduplicated/commands.py
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple scr...
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple sc...
Update the print help and add returns to delete and link methods.
Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
Python
mit
messiasthi/dduplicated-cli
27b9bd22bb43b8b86ae1c40a90c1fae7157dcb86
app/tests.py
app/tests.py
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response)
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self....
Add test to verify login required for protected pages
Add test to verify login required for protected pages
Python
mit
rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy
d0374f256b58ed3cb8194e4b46a62b97aee990e1
tests/test_core_lexer.py
tests/test_core_lexer.py
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfs...
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfs...
Add tests for reindenting line
Add tests for reindenting line
Python
mit
9seconds/concierge,9seconds/sshrc
4f2c3df24a59a7c287e59ec7d9b11922e7c49412
tests/test_search.py
tests/test_search.py
from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations
from sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', ...
Add test for no title search
Add test for no title search
Python
mit
CenterForOpenScience/sharepa,erinspace/sharepa,fabianvf/sharepa,samanehsan/sharepa
2640566b45736229cab347b9482a7372488ec53b
eccodes/highlevel/message.py
eccodes/highlevel/message.py
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccod...
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self....
Add get/set methods to the Message class
Add get/set methods to the Message class
Python
apache-2.0
ecmwf/eccodes-python,ecmwf/eccodes-python
d8375d3e3a4a00598ac0cdc38861be9f56fb58c0
edison/tests/sanity_tests.py
edison/tests/sanity_tests.py
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True)
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
Add another inane test to trigger Landscape
Add another inane test to trigger Landscape
Python
mit
briancline/edison
2bbb93a44b76949e34bce3a696a0ad3e3222ad9c
jsonsempai.py
jsonsempai.py
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): ...
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): ...
Raise AttributeError instead of None
Raise AttributeError instead of None
Python
mit
kragniz/json-sempai
027500ce86d838bae1927fe2590a9ce88cb61db4
troposphere/utils.py
troposphere/utils.py
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next...
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next...
Add "include_initial" kwarg to support tailing stack updates
Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.
Python
bsd-2-clause
ikben/troposphere,inetCatapult/troposphere,micahhausler/troposphere,ptoraskar/troposphere,johnctitus/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere,horacio3/troposphere,dmm92/troposphere,craigbruce/troposphere,LouTheBrew/troposphere,xxxVxxx/troposphere,pas256/troposphere,cloudtools/troposp...
eeac557b77a3a63a3497791a2716706801b20e37
kodos/main.py
kodos/main.py
def run(args=None): """Main entry point of the application.""" pass
import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Tr...
Connect the UI to the code and start to connect slots to actions.
Connect the UI to the code and start to connect slots to actions.
Python
bsd-2-clause
multani/kodos-qt4
c2a69c18085d4f9ee932465e143fe051037d98db
util/output_pipe.py
util/output_pipe.py
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than ...
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than ...
Fix bug where previous instances would populate the new OutputPipe
Fix bug where previous instances would populate the new OutputPipe
Python
mit
JBarberU/strawberry_py
5c3c681d60a3d747728d337358455cf00b905e43
utils/message_parsing.py
utils/message_parsing.py
from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if s...
from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswit...
Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
Python
mit
HexadecimalPython/Xeili,awau/Amethyst
c4feb85d3f1f0151b7a64705a555d98221d6d857
setup-utils/data_upgrade_from_0.4.py
setup-utils/data_upgrade_from_0.4.py
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The loca...
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The loca...
Add new WHOWAS keys when upgrading the data to 0.5
Add new WHOWAS keys when upgrading the data to 0.5
Python
bsd-3-clause
Heufneutje/txircd
08b1f3f64580f99ffb18261ab0e9fc691bc3dd67
rpifake/__init__.py
rpifake/__init__.py
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from...
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from...
Make override more global, not just within patch scope
Make override more global, not just within patch scope
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
1d0ac568776798a032906d91c913240dabfd403b
twitter_streaming.py
twitter_streaming.py
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy im...
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming A...
Stop on error from streaming API
Stop on error from streaming API
Python
mit
0x7df/twitter2pocket
a147d7cdd8ff3141ceea0f6902c2f664928f7b65
vocab.py
vocab.py
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: ...
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: ...
Allow reading word list from stdin.
Allow reading word list from stdin.
Python
mit
zqureshi/vocab
e70e6c1cccb235efdd426fcf3cfb7b0be8b9efed
fjord/heartbeat/management/commands/hbhealthcheck.py
fjord/heartbeat/management/commands/hbhealthcheck.py
from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks())...
from django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print ...
Fix imports after renaming healthcheck module
Fix imports after renaming healthcheck module
Python
bsd-3-clause
mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,mozilla/fjord,mozilla/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord
0e1425b9246ae85dbd8bd37244a442662dd205bb
server/auvsi_suas/views/index.py
server/auvsi_suas/views/index.py
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users co...
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web bro...
Use TemplateView to simplify Index view.
Use TemplateView to simplify Index view.
Python
apache-2.0
auvsi-suas/interop,auvsi-suas/interop,auvsi-suas/interop,auvsi-suas/interop
5837df594f9c18ffe62e90dd4d6ba30fdde98dde
flaskbb/utils/database.py
flaskbb/utils/database.py
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr_...
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr_...
Use the naive datetime format for MySQL as well
Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME
Python
bsd-3-clause
realityone/flaskbb,realityone/flaskbb,realityone/flaskbb
1ed5a4fc595031099c44c2ade3dfe2d5610308c8
plugins/lock_the_chat.py
plugins/lock_the_chat.py
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_i...
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_i...
Update lock plugin so admins could write messages
Update lock plugin so admins could write messages
Python
mit
ProtoxiDe22/Octeon
7f411fd01c931b73f717b114934662ebb2739555
spacy/sv/tokenizer_exceptions.py
spacy/sv/tokenizer_exceptions.py
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc."...
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", ...
Remove exceptions containing whitespace / no special chars
Remove exceptions containing whitespace / no special chars
Python
mit
honnibal/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,explosion/spaCy,aikramer2/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,raphael0202/spaCy,banglakit/spaCy,explosion/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,Gre...
497d82e353bfc2db1246982616bf39ec26ba27f8
utilities/__init__.py
utilities/__init__.py
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
Add function to get just stderr from subprocess command
Add function to get just stderr from subprocess command
Python
mit
IanLee1521/utilities
fa9f4ca0bae63b17937c676800fcf80889c70030
cura/CuraSplashScreen.py
cura/CuraSplashScreen.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSpl...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Applicat...
Fix splashscreen size on HiDPI (windows) screens
Fix splashscreen size on HiDPI (windows) screens
Python
agpl-3.0
fieldOfView/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,Curahelper/Cura,totalretribution/Cura,Curahelper/Cura,totalretribution/Cura,senttech/Cura,fieldOfView/Cura,hmflash/Cura,senttech/Cura,hmflash/Cura
181318bbb9f2e4458b1188bfc8a8ada7f3b4b196
moderation_queue/urls.py
moderation_queue/urls.py
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_vi...
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_vi...
Rearrange the photo upload success URL for consistency
Rearrange the photo upload success URL for consistency
Python
agpl-3.0
datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yourn...
34f83765d850fbc97cc3512eac4c2ebab551b5f7
db_logger.py
db_logger.py
import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(m...
import mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_lo...
Connect to MySQL only when needed
Connect to MySQL only when needed
Python
mit
kalinochkind/vkbot,kalinochkind/vkbot,kalinochkind/vkbot
39b6bec6159d147be802e8975ae68fef904d8d19
logger/__init__.py
logger/__init__.py
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["logger...
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from...
Remove redundant import and fix package's __all__
Remove redundant import and fix package's __all__
Python
bsd-2-clause
Vgr255/logging
3418b1ef4ade19ccddef92ec059d1629969d8cef
src/lander/ext/parser/_parser.py
src/lander/ext/parser/_parser.py
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(met...
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKI...
Add normalize_source hook for parsers
Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.
Python
mit
lsst-sqre/lander,lsst-sqre/lander
668f175fcff4414c6c01de31b8f8d703e9588c5f
Optimization.py
Optimization.py
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, *...
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, *...
Fix to handle case where parameters are not passed-in as a KL
Fix to handle case where parameters are not passed-in as a KL
Python
bsd-3-clause
GutenkunstLab/SloppyCell,GutenkunstLab/SloppyCell
c9553679d64ea9fe3db40c4c12ca5833c504ab91
mainapp/documents/file.py
mainapp/documents/file.py
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', ...
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', ...
Put parsed_text into the full-text search index
Put parsed_text into the full-text search index
Python
mit
meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent
8280b9d2f9a88e3b52e76405a6a978e85da2b680
oscar/apps/customer/auth_backends.py
oscar/apps/customer/auth_backends.py
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwa...
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: r...
Correct bug in auth where username=None
Correct bug in auth where username=None
Python
bsd-3-clause
kapt/django-oscar,bschuon/django-oscar,lijoantony/django-oscar,bnprk/django-oscar,pdonadeo/django-oscar,jinnykoo/wuyisj.com,jinnykoo/christmas,monikasulik/django-oscar,machtfit/django-oscar,sonofatailor/django-oscar,marcoantoniooliveira/labweb,spartonia/django-oscar,spartonia/django-oscar,Jannes123/django-oscar,bschuon...
d99cedc62dc0e424d676e791eb0d43d92112587a
app/status/views.py
app/status/views.py
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_statu...
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_statu...
Change variable name & int comparison.
Change variable name & int comparison.
Python
mit
alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmar...
9c2bee9fe8442cad0761d196d78baaff37c9cb08
mff_rams_plugin/config.py
mff_rams_plugin/config.py
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICE
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.
Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.
Python
agpl-3.0
MidwestFurryFandom/mff-rams-plugin,MidwestFurryFandom/mff-rams-plugin
31a9afb135cc5ffcf634e638e88232b71444d975
modules/raycast/config.py
modules/raycast/config.py
def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass
def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD suppo...
Disable embree-based modules on x86 (32-bit)
SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)
Python
mit
vkbsb/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,akien-mga/godot,vkbsb/godot,pkowal1982/godot,godotengine/godot,BastiaanOlij/godot,BastiaanOlij/godot,Zylann/godot,Faless/godot,ZuBsPaCe/godot,ZuBsPaCe/godot,godotengine/godot,josempans/godot,akien-mga/godot,Faless/godot,Valentactive/godot,pkowal1982/godot,godotengine/...
4f9e70866e688ce29096586c8abcf23ef633084f
mqtt/tests/test_client.py
mqtt/tests/test_client.py
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
Add more time to mqtt.test.client
Add more time to mqtt.test.client
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
9fb89f885dd26b530b4cc95427373f06ddc7d13d
emptiness.py
emptiness.py
#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The t...
#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='...
Use current time if no arguments given
Use current time if no arguments given
Python
mit
egeldenhuys/emptiness,egeldenhuys/emptiness,egeldenhuys/emptiness
bf7f2c90f171efb3a631956a15f2c3ed50b5202e
lc0172_factorial_trailing_zeroes.py
lc0172_factorial_trailing_zeroes.py
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. ...
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. ...
Refactor codes and revise main
Refactor codes and revise main
Python
bsd-2-clause
bowen0701/algorithms_data_structures
072774a36c82c3654cdabc6ebfd677b8603db49f
src/models/image.py
src/models/image.py
from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(imag...
import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = l...
Add a timestamp to the filename to allow for chronological ordering in the filesystem
Add a timestamp to the filename to allow for chronological ordering in the filesystem
Python
apache-2.0
CharlieCorner/pymage_downloader