commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
7787db13cb5e130c52cc192664ffdd49c3c1cd09 | add output URL | benofben/azure-resource-manager-dse,benofben/azure-resource-manager-dse | multidc/main.py | multidc/main.py | import json
import opsCenterNode
import dseNodes
# This python script generates an ARM template that deploys DSE across multiple datacenters.
with open('clusterParameters.json') as inputFile:
clusterParameters = json.load(inputFile)
locations = clusterParameters['locations']
vmSize = clusterParameters['vmSize']
... | import json
import opsCenterNode
import dseNodes
# This python script generates an ARM template that deploys DSE across multiple datacenters.
with open('clusterParameters.json') as inputFile:
clusterParameters = json.load(inputFile)
locations = clusterParameters['locations']
vmSize = clusterParameters['vmSize']
... | mit | Python |
48749f16d2f51d0915614ad5c1c4033077d3cfa6 | make api require unique case number, not urn | ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas | api/v0/serializers.py | api/v0/serializers.py | from rest_framework import serializers
from apps.plea.models import Case, UsageStats, Offence
class OffenceSerializer(serializers.ModelSerializer):
class Meta:
model = Offence
exclude = ("case",)
class CaseSerializer(serializers.ModelSerializer):
case_number = serializers.CharField(require... | from rest_framework import serializers
from apps.plea.models import Case, UsageStats, Offence
class OffenceSerializer(serializers.ModelSerializer):
class Meta:
model = Offence
exclude = ("case",)
class CaseSerializer(serializers.ModelSerializer):
urn = serializers.RegexField("^\d{2}/[a-zA-... | mit | Python |
f1048ee71cc5ffa6d38045e6931cb620216ead4d | Handle GET RESPONSE | LedgerHQ/blue-loader-python | ledgerblue/commTCP.py | ledgerblue/commTCP.py | """
*******************************************************************************
* Ledger Blue
* (c) 2019 Ledger
*
* 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.... | """
*******************************************************************************
* Ledger Blue
* (c) 2019 Ledger
*
* 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-2.0 | Python |
8316a60ba2887a511579e8cedb90b3a02fc1889a | Drop dashes from download urls. | mbr/dope,mbr/dope | dope/util.py | dope/util.py | from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
def to_url(self, obj):
return str(obj).replace('-', '')
| from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
to_url = str
| mit | Python |
75af5ca68ba2238bc8efb2a5f9cf2aa24276fb41 | add bcrypt password encryption | bmwachajr/bucketlist | application/models.py | application/models.py | from flask_sqlalchemy import SQLAlchemy
from application import app, db
from sqlalchemy.sql import func
import bcrypt
class User(db.Model):
""" Creates users on the system """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
em... | from flask_sqlalchemy import SQLAlchemy
from application import app, db
from sqlalchemy.sql import func
class User(db.Model):
""" Creates users on the system """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Colum... | mit | Python |
01099fc95bbce7119e71fe65d608a809e819552e | update domain model | apipanda/openssl,apipanda/openssl,apipanda/openssl,apipanda/openssl | apps/domain/models.py | apps/domain/models.py | from __future__ import unicode_literals, absolute_import
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from apps.certificate.models import Certificate
# Create your models here.
class Domain(models.Model):
domain_name = models.CharField(max_length=200... | from __future__ import unicode_literals, absolute_import
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from apps.certificate.models import Certificate
# Create your models here.
class Domain(models.Model):
domain_name = models.CharField(max_length=200... | mit | Python |
80710617b0dbfb862aa2e7367785c9be3e4cbd3d | Use external exceptions | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/modules/node.py | salt/modules/node.py | # -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | apache-2.0 | Python |
38e349f04257d1d35d431a2754c6c249a7b4650c | Allow runner to update_ca_bundle | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/runners/http.py | salt/runners/http.py | # -*- coding: utf-8 -*-
'''
Module for making various web calls. Primarily designed for webhooks and the
like, but also useful for basic http testing.
'''
from __future__ import absolute_import
# Import Python libs
import logging
# Import salt libs
import salt.utils.http
log = logging.getLogger(__name__)
def query(... | # -*- coding: utf-8 -*-
'''
Module for making various web calls. Primarily designed for webhooks and the
like, but also useful for basic http testing.
'''
from __future__ import absolute_import
# Import Python libs
import logging
# Import salt libs
import salt.utils.http
log = logging.getLogger(__name__)
def query(... | apache-2.0 | Python |
6c096bdd89b2e276eafe019b90c9088c49e1d6f2 | Update version number | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | saltcloud/version.py | saltcloud/version.py | import sys
__version_info__ = (0, 8, 6)
__version__ = '.'.join(map(str, __version_info__))
def versions_report():
libs = (
("Salt", "salt", "__version__"),
("Apache Libcloud", "libcloud", "__version__"),
("PyYAML", "yaml", "__version__"),
)
padding = len(max([lib[0] for lib in li... | import sys
__version_info__ = (0, 8, 5)
__version__ = '.'.join(map(str, __version_info__))
def versions_report():
libs = (
("Salt", "salt", "__version__"),
("Apache Libcloud", "libcloud", "__version__"),
("PyYAML", "yaml", "__version__"),
)
padding = len(max([lib[0] for lib in li... | apache-2.0 | Python |
e5d30636c29cde0c4fa9e81f213b1fc008237229 | Update libchromiumcontent for linking with msvcrt dll | joaomoreno/atom-shell,bbondy/electron,noikiy/electron,GoooIce/electron,jannishuebl/electron,Jacobichou/electron,michaelchiche/electron,tinydew4/electron,arturts/electron,vaginessa/electron,electron/electron,soulteary/electron,natgolov/electron,aliib/electron,sshiting/electron,roadev/electron,shockone/electron,arusakov/... | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import errno
import os
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '90a5b9c3792645067ad9517e60cf5eb99730e0f9'
PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',... | #!/usr/bin/env python
import errno
import os
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '07a73a610496e4a1b4f3abc3c2fb0516187ec460'
PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',... | mit | Python |
64c3a1df70907d857f2eff5cf6a010075eba797f | Update version to 20160713 | pidydx/artifacts,pidydx/artifacts,destijl/artifacts,destijl/artifacts | artifacts/__init__.py | artifacts/__init__.py | # -*- coding: utf-8 -*-
__version__ = '20160713'
| # -*- coding: utf-8 -*-
__version__ = '20160114'
| apache-2.0 | Python |
fabe0a071ce6e0e3d92098669dac33c2c9bc9b62 | add folder docs | MarineLasbleis/GrowYourIC | GrowYourIC/__init__.py | GrowYourIC/__init__.py | """
GrowYourIC
====
GrowYourIC is a tool to model seismic observation through inner core geodynamical modelisation.
"""
from __future__ import absolute_import
__version__ = "0.1.1"
from . import data
from . import geodyn
from . import intersection
from . import positions
from . import plot_data
from . import miner... | """
GrowYourIC
====
GrowYourIC is a tool to model seismic observation through inner core geodynamical modelisation.
"""
from __future__ import absolute_import
__version__ = "0.1.0"
from . import data
from . import geodyn
from . import intersection
from . import positions
from . import plot_data
from . import miner... | mit | Python |
9d46df1680e3d799971e73ec73043c2a6c0590ce | Fix building tar in deployment | vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,Infinidat/lanister,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,getslash/mailboxer | scripts/build_tar.py | scripts/build_tar.py | #! /usr/bin/python
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
if _... | #! /usr/bin/python
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for ... | bsd-3-clause | Python |
6b0746b82d7a085655a0f594201a7efb471dc3c5 | Fix attachment representation | Hackfmi/Diaphanum,Hackfmi/Diaphanum | attachments/models.py | attachments/models.py | from django.db import models
from datetime import datetime
class Attachment(models.Model):
file_name = models.FileField(upload_to='attachments')
def __unicode__(self):
return unicode(self.file_name)
| from django.db import models
class Attachment(models.Model):
file_name = models.FileField(upload_to='attachments')
def __unicode__(self):
return self.file_name
| mit | Python |
494f497b4aee2189bffd6f916fb3d9ec4090fc6a | Update task_9_21.py | Mariaanisimova/pythonintask | IVTp/2014/task_9_21.py | IVTp/2014/task_9_21.py | #Задача 9. Вариант 21.
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет".
#Вслед за тем игрок должен попробов... | #Задача 9. Вариант 21.
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет".
#Вслед за тем игрок должен попробов... | apache-2.0 | Python |
bc5e9ab68cfc3ad4372a5dd37cff768f3008f6e8 | Test Change 2 | iambillal/inf1340_2015_asst1 | exercise1.py | exercise1.py | #!/usr/bin/env python
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion
This module prints the amount of money that Lakshmi has remaining
after the stock transactions
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
... | #!/usr/bin/env python
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion
This module prints the amount of money that Lakshmi has remaining
after the stock transactions
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
... | mit | Python |
dc59fd211e7881706ea2629dd34bcaeac4260d1a | Fix typo | lowRISC/fusesoc,lowRISC/fusesoc,olofk/fusesoc,olofk/fusesoc | orpsoc/utils.py | orpsoc/utils.py | import subprocess
class Launcher:
def __init__(self, cmd, args=[], shell=False, cwd=None, stderr=None, errormsg=None):
self.cmd = cmd
self.args = args
self.shell = shell
self.cwd = cwd
self.stderr = stderr
self.errormsg = errormsg
def run(self... | import subprocess
class Launcher:
def __init__(self, cmd, args=[], shell=False, cwd=None, stderr=None, errormsg=None):
self.cmd = cmd
self.args = args
self.shell = shell
self.cwd = cwd
self.stderr = stderr
self.errormsg = errormsg
def run(self... | bsd-2-clause | Python |
aa43737b06ccdff8fd4d60be67d09ba4a05bbc65 | Add Asciinema for GofmtBear | horczech/coala-bears,LWJensen/coala-bears,horczech/coala-bears,seblat/coala-bears,srisankethu/coala-bears,kaustubhhiware/coala-bears,kaustubhhiware/coala-bears,sounak98/coala-bears,Shade5/coala-bears,meetmangukiya/coala-bears,madhukar01/coala-bears,ankit01ojha/coala-bears,shreyans800755/coala-bears,coala-analyzer/coala... | bears/go/GofmtBear.py | bears/go/GofmtBear.py | from coalib.bearlib.abstractions.Linter import linter
from coalib.bears.requirements.GoRequirement import GoRequirement
@linter(executable='gofmt',
use_stdin=True,
output_format='corrected',
result_message='Formatting can be improved.')
class GofmtBear:
"""
Suggest better formatting op... | from coalib.bearlib.abstractions.Linter import linter
from coalib.bears.requirements.GoRequirement import GoRequirement
@linter(executable='gofmt',
use_stdin=True,
output_format='corrected',
result_message='Formatting can be improved.')
class GofmtBear:
"""
Suggest better formatting op... | agpl-3.0 | Python |
00d87e000c2abcc772c40e5c0d9faaf1e3cd5758 | Bump version | slash-testing/backslash-python,vmalloc/backslash-python | backslash/__version__.py | backslash/__version__.py | __version__ = '2.25.3'
| __version__ = '2.25.2'
| bsd-3-clause | Python |
a1390619619a364b9fab13504fb5c2464491d449 | Refactor Largest Palindrome Product for range of n is [1,8] | Kunal57/Python_Algorithms | Largest_Palindrome_Product.py | Largest_Palindrome_Product.py | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
from itertools import product... | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
def largestPalindrome(n):
"... | mit | Python |
de4af7935c1c8d6751c5a71ad90dd5f531f7a1b0 | Fix the script function args | fedora-infra/fedimg,fedora-infra/fedimg | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | agpl-3.0 | Python |
166bff52496bfb47c5a3a03585bd10fb449b8d77 | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/curses/__init__.py | Lib/curses/__init__.py | """curses
The main package for curses support for Python. Normally used by importing
the package, and perhaps a particular module inside it.
import curses
from curses import textpad
curses.initwin()
...
"""
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
# Some const... | """curses
The main package for curses support for Python. Normally used by importing
the package, and perhaps a particular module inside it.
import curses
from curses import textpad
curses.initwin()
...
"""
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
| mit | Python |
1e3e0ee1f2966a121027eda405325e9cf627c147 | use original 'path' when printing errors if os.path.relpath fails | googlefonts/fontmake,googlei18n/fontmake,googlefonts/fontmake,googlei18n/fontmake | Lib/fontmake/errors.py | Lib/fontmake/errors.py | import os
def _try_relative_path(path):
# Try to return 'path' relative to the current working directory, or
# return input 'path' if we can't make a relative path.
# E.g. on Windows, os.path.relpath fails when path and "." are on
# different mount points, C: or D: etc.
try:
return os.path... | import os
class FontmakeError(Exception):
"""Base class for all fontmake exceptions.
This exception is intended to be chained to the original exception. The
main purpose is to provide a source file trail that points to where the
explosion came from.
"""
def __init__(self, msg, source_file):
... | apache-2.0 | Python |
727c266d123d7c6afdd4697e72d79a7e3659f9a1 | Update basic-calculator-ii.py | yiwen-luo/LeetCode,kamyu104/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,githubut... | Python/basic-calculator-ii.py | Python/basic-calculator-ii.py | # Time: O(n)
# Space: O(n)
#
# Implement a basic calculator to evaluate a simple expression string.
#
# The expression string contains only non-negative integers, +, -, *, /
# operators and empty spaces . The integer division should truncate toward zero.
#
# You may assume that the given expression is always valid.
#... | # Time: O(n)
# Space: O(n)
#
# Implement a basic calculator to evaluate a simple expression string.
#
# The expression string contains only non-negative integers, +, -, *, /
# operators and empty spaces . The integer division should truncate toward zero.
#
# You may assume that the given expression is always valid.
#... | mit | Python |
dec61efc0259c94186d5f704ac272dbb646bd824 | Make the "monitor" a positional argument that is not automatically converted to a monitor object | enthought/pikos,enthought/pikos,enthought/pikos | pikos/runner.py | pikos/runner.py | import argparse
import os
import sys
from pikos.monitors.api import (FunctionMonitor, LineMonitor,
FunctionMemoryMonitor,
LineMemoryMonitor)
from pikos.recorders.api import TextStreamRecorder
MONITORS = {'functio... | import argparse
from pikos.monitors.api import (FunctionMonitor, LineMonitor, FunctionMemoryMonitor,
LineMemoryMonitor)
MONITORS = {'functions': FunctionMonitor,
'lines': LineMonitor,
'function_memory': FunctionMemoryMonitor,
'line_memory': LineMemory... | bsd-3-clause | Python |
ad480bd4707771a416f474997225a55d92cf676a | Bump version number. | smarkets/smk_python_sdk | smarkets/__init__.py | smarkets/__init__.py | "Smarkets API package"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
import inspect
import os
if 'READTHEDOCS' in os.environ:
from mock import Mock
import sys
eto = seto = \
sys.m... | "Smarkets API package"
# Copyright (C) 2011 Smarkets Limited <support@smarkets.com>
#
# This module is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
import inspect
import os
if 'READTHEDOCS' in os.environ:
from mock import Mock
import sys
eto = seto = \
sys.m... | mit | Python |
7c12b5fe6ee5a5cd9761482cc2d3e3363cab7cd3 | Save the figure | eggplantbren/TwinPeaks3,eggplantbren/TwinPeaks3,eggplantbren/TwinPeaks3 | Paper/figures/joint.py | Paper/figures/joint.py | import numpy as np
import numpy.random as rng
from matplotlib import rc
import matplotlib.pyplot as plt
"""
Make a plot of \pi(L1, L2)
Based on a similar plot from ABCNS
"""
rng.seed(0)
rc("font", size=18, family="serif", serif="Computer Sans")
rc("text", usetex=True)
# Resolution
N = 256
[x, y] = np.meshgrid(np.lin... | import numpy as np
import numpy.random as rng
from matplotlib import rc
import matplotlib.pyplot as plt
"""
Make a plot of \pi(L1, L2)
Based on a similar plot from ABCNS
"""
rng.seed(0)
rc("font", size=18, family="serif", serif="Computer Sans")
rc("text", usetex=True)
# Resolution
N = 256
[x, y] = np.meshgrid(np.lin... | mit | Python |
af1b840c17febd851785c95b872faa99ededd184 | Remove repeated argument | adw0rd/django-social-auth,VishvajitP/django-social-auth,duoduo369/django-social-auth,qas612820704/django-social-auth,vxvinh1511/django-social-auth,michael-borisov/django-social-auth,qas612820704/django-social-auth,gustavoam/django-social-auth,caktus/django-social-auth,beswarm/django-social-auth,dongguangming/django-soc... | social_auth/views.py | social_auth/views.py | from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from social.utils import setting_name
from social.actio... | from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from social.utils import setting_name
from social.actio... | bsd-3-clause | Python |
17faea99343e37036b7ee35e5d3273f98a52dba9 | Fix numpy related errors on Mavericks. | cryos/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,cryos/tomviz,Hovden/tomviz,Hovden/tomviz,yijiang1/tomviz,cjh1/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,yijiang1/tomviz,cjh1/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz | Python/tomviz/utils.py | Python/tomviz/utils.py | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
import vtk.util.numpy_support as np_s
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association =... | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association = dsa.ArrayAssociation.POINT
return... | bsd-3-clause | Python |
5a305a9063f20eacdcce255b650b0246286a54bc | add gender filter | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | gem/admin.py | gem/admin.py | from django.contrib import admin
from django.contrib.auth.models import User
from gem.models import GemUserProfile, GemCommentReport
from molo.commenting.admin import MoloCommentAdmin
from molo.commenting.models import MoloComment
from molo.profiles.admin import ProfileUserAdmin
from django.http import HttpResponse
imp... | from django.contrib import admin
from django.contrib.auth.models import User
from gem.models import GemUserProfile, GemCommentReport
from molo.commenting.admin import MoloCommentAdmin
from molo.commenting.models import MoloComment
from molo.profiles.admin import ProfileUserAdmin
from django.http import HttpResponse
imp... | bsd-2-clause | Python |
edb4bfb06882dfe4c9ec6690ab6825c802514981 | set svn:propset | landryb/psutil,landryb/psutil,tomprince/psutil,mindw/psutil,packages/psutil,packages/psutil,msarahan/psutil,cloudbase/psutil,0-wiz-0/psutil,mindw/psutil,giampaolo/psutil,msarahan/psutil,jamesblunt/psutil,mindw/psutil,qbit/psutil,msarahan/psutil,jorik041/psutil,cloudbase/psutil,Q-Leap-Networks/psutil,landryb/psutil,mrje... | psutil/error.py | psutil/error.py | # $Id
# this exception get overriden by the platform specific modules if necessary
class Error(Exception):
pass
class NoSuchProcess(Error):
"""No process was found for the given parameters."""
def __init__(self, pid=None, msg=None):
self.pid = pid
self.msg = msg
def __str__(self):
... | # $Id$
# this exception get overriden by the platform specific modules if necessary
class Error(Exception):
pass
class NoSuchProcess(Error):
"""No process was found for the given parameters."""
def __init__(self, pid=None, msg=None):
self.pid = pid
self.msg = msg
def __str__(self):
... | bsd-3-clause | Python |
e7c1b294f5c3fb825a301e89365de7f19b3ddf3b | Add config file reading | peterfpeterson/finddata | publish_plot.py | publish_plot.py | #!/usr/bin/env python
import json
import os
CONFIG_FILE = '/etc/autoreduce/post_processing.conf'
class Configuration(object):
"""
Read and process configuration file and provide an easy way to create a configured Client object
"""
def __init__(self, config_file):
if os.access(config_file, os.R... | #!/usr/bin/env python
import os
import json
def loadDiv(filename):
if not os.path.exists(filename):
raise RuntimeError('\'%s\' does not exist' % filename)
print 'loading \'%s\'' % filename
with file(filename, 'r') as handle:
div = handle.read()
return div
def getURL(instrument, run_nu... | mit | Python |
311c8db11c984cc9a8ed21ae42b85b1d5a8cdc59 | index views | anselmobd/fo2,anselmobd/fo2,anselmobd/fo2,anselmobd/fo2 | src/fo2/views/views.py | src/fo2/views/views.py | from pprint import pprint
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.generic import TemplateView, View
from base.models import Co... | from pprint import pprint
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.generic import TemplateView, View
from base.models import Co... | mit | Python |
f24b80a7f8804560c8703da4e31321411b609611 | Bump to 0.7.0 and add Python 3 classifiers | web-push-libs/vapid,jrconlin/vapid,jrconlin/vapid,web-push-libs/vapid,jrconlin/vapid,jrconlin/vapid,web-push-libs/vapid,web-push-libs/vapid,web-push-libs/vapid | python/setup.py | python/setup.py | import io
import os
from setuptools import setup, find_packages
__version__ = "0.7.0"
def read_from(file):
reply = []
with io.open(os.path.join(here, file), encoding='utf8') as f:
for l in f:
l = l.strip()
if not l:
break
if l[0] != '#' or l[:2] !=... | import io
import os
from setuptools import setup, find_packages
__version__ = "0.6.0"
def read_from(file):
reply = []
with io.open(os.path.join(here, file), encoding='utf8') as f:
for l in f:
l = l.strip()
if not l:
break
if l[0] != '#' or l[:2] !=... | mpl-2.0 | Python |
edd74c12aa04e9d28fbcea9d8df21885abeab890 | Add a #! thingy and make executable. This is easier for me to get the right Python (i.e. not Cygwin) to execute the script on Windows. | zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb | python/setup.py | python/setup.py | #!/usr/bin/env python
# The contents of this file are subject to the MonetDB Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://monetdb.cwi.nl/Legal/MonetDBLicense-1.1.html
#
# Software distributed under the ... | # The contents of this file are subject to the MonetDB Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://monetdb.cwi.nl/Legal/MonetDBLicense-1.1.html
#
# Software distributed under the License is distributed ... | mpl-2.0 | Python |
9d8a299db591fadd729fc4ec78a1de1fe2cca869 | Fix delete_selected KeyError in locations admin | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign | src/locations/admin.py | src/locations/admin.py | from django.contrib import admin
from django.db.models import F, Sum, IntegerField
from django.utils.translation import ugettext_lazy as _
import nested_admin
from .models import District, Location
from campaigns.models import CampaignLocationShift
from coordinators.models import filter_by_district
from campaigns.ad... | from django.contrib import admin
from django.db.models import F, Sum, IntegerField
from django.utils.translation import ugettext_lazy as _
import nested_admin
from .models import District, Location
from campaigns.models import CampaignLocationShift
from coordinators.models import filter_by_district
from campaigns.ad... | mit | Python |
3bc097096c97fbf8936bea9c61f55c67cb0dd34e | Update cnn_functions.py | AlperenAydin/GenreRecognition,AlperenAydin/GenreRecognition | src/cnn_functions.py | src/cnn_functions.py | import numpy as np
import tensorflow as tf
# Weight variable
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# Bias variable
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# These two for the basis for most... | import numpy as np
import tensorflow as tf
# Weight variable
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# Bias variable
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# These two for the basis for most... | mit | Python |
85264809758c173280ffd0e2fbc0978b66c59f57 | Fix mod_wsgi queue time stats. | ENCODE-DCC/encoded,kidaa/encoded,ClinGen/clincoded,philiptzou/clincoded,4dn-dcic/fourfront,ENCODE-DCC/encoded,hms-dbmi/fourfront,ClinGen/clincoded,philiptzou/clincoded,ClinGen/clincoded,ENCODE-DCC/snovault,ClinGen/clincoded,T2DREAM/t2dream-portal,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/snovault,T2DREAM/t2dream... | src/encoded/stats.py | src/encoded/stats.py | import pyramid.tweens
import time
from pyramid.settings import asbool
from pyramid.threadlocal import manager as threadlocal_manager
from sqlalchemy import event
from sqlalchemy.engine import Engine
from urllib import urlencode
def includeme(config):
config.add_tween('.stats.stats_tween_factory',
under=py... | import pyramid.tweens
import time
from pyramid.settings import asbool
from pyramid.threadlocal import manager as threadlocal_manager
from sqlalchemy import event
from sqlalchemy.engine import Engine
from urllib import urlencode
def includeme(config):
config.add_tween('.stats.stats_tween_factory',
under=py... | mit | Python |
ca962b6994314ac3d3a5a5bcbf9044d52cd88ad9 | Remove unnecessary TODO | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 | adhocracy4/actions/signals.py | adhocracy4/actions/signals.py | from itertools import chain
from django.apps import apps
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_delete, post_save
from .models import Action
from .verbs import Verbs
# Actions resulting from the create_system_actions manage... | from itertools import chain
from django.apps import apps
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_delete, post_save
from .models import Action
from .verbs import Verbs
# Actions resulting from the create_system_actions manage... | agpl-3.0 | Python |
abd428583d73d7c34025ab28428922473de219d3 | Improve sanitize_html test | alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph,pudo/aleph | aleph/tests/test_view_util.py | aleph/tests/test_view_util.py | from lxml.html import document_fromstring
from aleph.views.util import get_best_next_url, sanitize_html
from aleph.tests.util import TestCase, UI_URL
class ViewUtilTest(TestCase):
def setUp(self):
super(ViewUtilTest, self).setUp()
def test_get_best_next_url_blank(self):
self.assertEqual(UI_... | from aleph.views.util import get_best_next_url, sanitize_html
from aleph.tests.util import TestCase, UI_URL
class ViewUtilTest(TestCase):
def setUp(self):
super(ViewUtilTest, self).setUp()
def test_get_best_next_url_blank(self):
self.assertEqual(UI_URL, get_best_next_url(''))
def test_g... | mit | Python |
b5f840ad02d96714721f0558409f770161f4a8e0 | add test for update notebook | aligot-project/aligot,skitoo/aligot,aligot-project/aligot,aligot-project/aligot | aligot/tests/test_notebook.py | aligot/tests/test_notebook.py | # coding: utf-8
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from rest_framework import status
from ..models import NoteBook, User
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
class TestNoteBookAp... | # coding: utf-8
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from rest_framework import status
from ..models import NoteBook, User
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
class TestNoteBookAp... | mit | Python |
05c509cb2c298425f141e11f9af1d20962f2bb7e | Update __init__.py | linkedin/iris,linkedin/iris,linkedin/iris,linkedin/iris | src/iris/__init__.py | src/iris/__init__.py | __version__ = "1.0.15"
| __version__ = "1.0.14"
| bsd-2-clause | Python |
7d1dc9bcdaf0a533b0b52ae9fb6e2d37940fad3c | Update email check regex to be more thorough | charlesthk/python-mailchimp | mailchimp3/helpers.py | mailchimp3/helpers.py | # coding=utf-8
"""
Helper functions to perform simple tasks for multiple areas of the API
"""
import hashlib
import re
HTTP_METHOD_ACTION_MATCHING = {
'get': 'GET',
'create': 'POST',
'update': 'PATCH',
'create_or_update': 'PUT',
'delete': 'DELETE'
}
def get_subscriber_hash(member_email):
"""
... | # coding=utf-8
"""
Helper functions to perform simple tasks for multiple areas of the API
"""
import hashlib
import re
HTTP_METHOD_ACTION_MATCHING = {
'get': 'GET',
'create': 'POST',
'update': 'PATCH',
'create_or_update': 'PUT',
'delete': 'DELETE'
}
def get_subscriber_hash(member_email):
"""
... | mit | Python |
1b89b0e6fe89cff56736ba88edc6422ce6078979 | Bump version to 0.2.0 | opendxl/opendxl-epo-service-python | dxleposervice/_version.py | dxleposervice/_version.py | __version__ = "0.2.0"
| __version__ = "0.1.4"
| apache-2.0 | Python |
6f14527aaa18ca3f707523535d596acc1c8fb847 | update version to 0.9.6 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/version.py | salt/version.py | __version_info__ = (0, 9, 6)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (0, 9, 5)
__version__ = '.'.join(map(str, __version_info__))
| apache-2.0 | Python |
1c434432977f0e3e126ec4d22be0bdccd4c44463 | Remove request processor. | serathius/sanic-sentry | sanic_sentry.py | sanic_sentry.py | import logging
import sanic
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
self.init_app(app)
def init_... | import logging
import sanic
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
from raven.processors import Processor
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
... | mit | Python |
62df776433ccb4b5de1e586f03381bbfe0c56817 | Remove unneccessary iteration | janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system | src/webapp/public.py | src/webapp/public.py | import json
from flask import Blueprint, render_template
import database as db
from database.model import Team
bp = Blueprint('public', __name__)
@bp.route("/map")
def map_page():
return render_template("public/map.html")
@bp.route("/map_teams")
def map_teams():
qry = db.session.query(Team).filter_by(conf... | import json
from flask import Blueprint, render_template
import database as db
from database.model import Team
bp = Blueprint('public', __name__)
@bp.route("/map")
def map_page():
return render_template("public/map.html")
@bp.route("/map_teams")
def map_teams():
qry = db.session.query(Team).filter_by(conf... | bsd-3-clause | Python |
91e107e209f2c4ce1341cc0dc3ec45055c2c3d27 | Fix deprecation warning | springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail | core/tests/test_template_tags.py | core/tests/test_template_tags.py | from django.template import Context, Template
from bs4 import BeautifulSoup
from core.tests.utils import *
from core.models import *
class TemplateTagsTestCase(WagtailTest):
def setUp(self):
super(TemplateTagsTestCase, self).setUp()
self.home_page = HomePage.objects.all()[0]
def test_set_v... | from django.template import Context, Template
from bs4 import BeautifulSoup
from core.tests.utils import *
from core.models import *
class TemplateTagsTestCase(WagtailTest):
def setUp(self):
super(TemplateTagsTestCase, self).setUp()
self.home_page = HomePage.objects.all()[0]
def test_set_v... | mit | Python |
8e5892e2fd5d3560ed4ffe3e8f11cfdb393865bf | Make it easier to see what the error was on failed module load. | mininet/mininet,mininet/mininet,mininet/mininet | mininet/moduledeps.py | mininet/moduledeps.py | "Module dependency utility functions for Mininet."
from mininet.util import quietRun
from mininet.log import info, error, debug
from os import environ
def lsmod():
"Return output of lsmod."
return quietRun( 'lsmod' )
def rmmod( mod ):
"""Return output of lsmod.
mod: module string"""
return qui... | "Module dependency utility functions for Mininet."
from mininet.util import quietRun
from mininet.log import info, error, debug
from os import environ
def lsmod():
"Return output of lsmod."
return quietRun( 'lsmod' )
def rmmod( mod ):
"""Return output of lsmod.
mod: module string"""
return qui... | bsd-3-clause | Python |
98649d486b9e2eb2c83e594e73cf6bbaa29213e5 | Make the server example listen on 0.0.0.0 by default. | mwicat/python2-osc,attwad/python-osc,ragnarula/python-osc,emlyn/python-osc | examples/simple_server.py | examples/simple_server.py | import argparse
import math
from pythonosc import dispatcher
from pythonosc import osc_server
def print_volume_handler(args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
def print_compute_handler(args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
except ValueError: pass
if ... | import argparse
import math
from pythonosc import dispatcher
from pythonosc import osc_server
def print_volume_handler(args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
def print_compute_handler(args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
except ValueError: pass
if ... | unlicense | Python |
1988798c80a123572c3fa19873b3b028504575dc | Improve error message when drmaa cannot be loaded. | galaxyproject/pulsar,natefoo/pulsar,galaxyproject/pulsar,natefoo/pulsar | pulsar/managers/util/drmaa/__init__.py | pulsar/managers/util/drmaa/__init__.py | try:
from drmaa import Session, JobControlAction
except OSError as e:
LOAD_ERROR_MESSAGE = "OSError - problem loading shared library [%s]." % e
Session = None
except ImportError as e:
LOAD_ERROR_MESSAGE = "ImportError - problem importing library (`pip install drmaa` may fix this) [%s]." % e
# Will n... | try:
from drmaa import Session, JobControlAction
except ImportError as e:
# Will not be able to use DRMAA
Session = None
NO_DRMAA_MESSAGE = "Attempt to use DRMAA, but DRMAA Python library cannot be loaded."
class DrmaaSessionFactory(object):
"""
Abstraction used to production DrmaaSession wrapper... | apache-2.0 | Python |
e56764c6e3393c105fd5acb439323b89f8775161 | Update __openerp__.py | Elico-Corp/openerp-7.0,Elico-Corp/openerp-7.0,Elico-Corp/openerp-7.0 | purchase_double_confirm/__openerp__.py | purchase_double_confirm/__openerp__.py | # -*- encoding: utf-8 -*-
# © 2014 Elico corp(www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
{
'name': 'Purchase Order Approvement',
'version': '7.0.1.0.0',
'category': 'Purchases',
'description': """
Button on PO will pop a question, give the operator a... | # -*- encoding: utf-8 -*-
# © 2014 Elico corp(www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
{
'name': 'Purchase Order Approvement',
'version': '7.0.1.0.0',
'category': 'Purchases',
'description': """
Button on PO will pop a question, give the operator a... | agpl-3.0 | Python |
e173868deff0672b2f5540d6409f4c87d1fe1827 | fix couchdb json encoding | wangjun/pyspider,wangjun/pyspider,binux/pyspider,luoq/pyspider,binux/pyspider,wangjun/pyspider,luoq/pyspider,binux/pyspider,luoq/pyspider | pyspider/database/couchdb/projectdb.py | pyspider/database/couchdb/projectdb.py | import time, requests, json
from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB
class ProjectDB(BaseProjectDB):
__collection_name__ = 'projectdb'
def __init__(self, url, database='projectdb'):
self.url = url
self.database = database
self.insert('', {})
def _de... | import time, requests, json
from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB
class ProjectDB(BaseProjectDB):
__collection_name__ = 'projectdb'
def __init__(self, url, database='projectdb'):
self.url = url
self.database = database
self.insert('', {})
def _de... | apache-2.0 | Python |
e55d04760daaefb6dda7f26d1ebcd66d7af45abc | Fix docstring in projection.py | 1024jp/LensCalibrator | modules/projection.py | modules/projection.py | #!/usr/bin/env python
"""
(C) 2007-2018 1024jp
"""
import numpy as np
import cv2
class Projector:
def __init__(self, image_points, ideal_points):
self.homography = self._estimate_homography(image_points, ideal_points)
@staticmethod
def _estimate_homography(image_points, ideal_points):
... | #!/usr/bin/env python
"""
(C) 2007-2017 1024jp
"""
import numpy as np
import cv2
class Projector:
def __init__(self, image_points, ideal_points):
self.homography = self._estimate_homography(image_points, ideal_points)
@staticmethod
def _estimate_homography(image_points, ideal_points):
... | mit | Python |
1cdf903ef028be519a6d3eee1b30b53234de51f2 | Fix valueerrors on pyquery. | mhils/readthedocs.org,sils1297/readthedocs.org,fujita-shintaro/readthedocs.org,d0ugal/readthedocs.org,safwanrahman/readthedocs.org,fujita-shintaro/readthedocs.org,GovReady/readthedocs.org,takluyver/readthedocs.org,atsuyim/readthedocs.org,istresearch/readthedocs.org,LukasBoersma/readthedocs.org,CedarLogic/readthedocs.or... | readthedocs/projects/search_indexes.py | readthedocs/projects/search_indexes.py | # -*- coding: utf-8-*-
import codecs
import os
from django.utils.html import strip_tags
from haystack import site
from haystack.indexes import *
from celery_haystack.indexes import CelerySearchIndex
from pyquery import PyQuery
from projects.models import File, ImportedFile, Project
import logging
log = logging.g... | # -*- coding: utf-8-*-
import codecs
import os
from django.utils.html import strip_tags
from haystack import site
from haystack.indexes import *
from celery_haystack.indexes import CelerySearchIndex
from pyquery import PyQuery
from projects.models import File, ImportedFile, Project
import logging
log = logging.g... | mit | Python |
6e06e335257e4a370d815b733ccce184a3541f81 | fix unhandled calls | mylokin/servy | servy/server.py | servy/server.py | from __future__ import absolute_import
import webob.exc
import webob.dec
import webob.response
import pickle
class Server(object):
def __init__(self, **services):
self.services = services
@webob.dec.wsgify
def __call__(self, request):
if request.method == 'POST':
return self... | from __future__ import absolute_import
import webob.exc
import webob.dec
import webob.response
import pickle
class Server(object):
def __init__(self, **services):
self.services = services
@webob.dec.wsgify
def __call__(self, request):
if request.method == 'POST':
return self... | mit | Python |
a1406c93c2cbdc0da73c8bc5412f695a0ab18d53 | add session keys file source code UTF-8 encoding | unStatiK/TorrentBOX,unStatiK/TorrentBOX,unStatiK/TorrentBOX | session_keys.py | session_keys.py | # -*- coding: utf-8 -*-
USER_TOKEN = 'user'
USER_ID_TOKEN = 'id_user'
|
USER_TOKEN = 'user'
USER_ID_TOKEN = 'id_user' | mit | Python |
8b77e1e865d72720a602b7b7cc5912cb852d68cf | Revert back to original settings for Celery Broker | pythonindia/junction,pythonindia/junction,pythonindia/junction,pythonindia/junction | settings/dev.py | settings/dev.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_H... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_H... | mit | Python |
e753038de039fd23f0d59bb0094f59fc73efe22b | Set a custom JSON Encoder to serialize date class. | viniciuschiele/flask-apscheduler | flask_apscheduler/json.py | flask_apscheduler/json.py | import datetime
import flask
import json
from apscheduler.job import Job
from .utils import job_to_dict
loads = json.loads
def dumps(obj, indent=None):
return json.dumps(obj, indent=indent, cls=JSONEncoder)
def jsonify(data, status=None):
indent = None
if flask.current_app.config['JSONIFY_PRETTYPRINT_... | import flask
import json
from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Job):
return job_to_d... | apache-2.0 | Python |
edcfe2b156af23943478bc86592b4c8d5dc07e10 | Support older versions of MongoEngine | gerasim13/flask-mongoengine-1,rochacbruno/flask-mongoengine,quokkaproject/flask-mongoengine,quokkaproject/flask-mongoengine,gerasim13/flask-mongoengine-1,losintikfos/flask-mongoengine,rochacbruno/flask-mongoengine,losintikfos/flask-mongoengine | flask_mongoengine/json.py | flask_mongoengine/json.py | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
try:
from mongoengine.base import BaseQuerySet
except ImportError as ie: # support mongoengine < 0.7
from mongoengine.queryset import QuerySet as BaseQuerySet
def _make_encoder(superclass):
class MongoEn... | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
from mongoengine import QuerySet
def _make_encoder(superclass):
class MongoEngineJSONEncoder(superclass):
'''
A JSONEncoder which provides serialization of MongoEngine
documents and quer... | bsd-3-clause | Python |
6f31cb8cad05f1713fbdef861c194385bc875ad9 | Clean up comment | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents | mozcal/events/urls.py | mozcal/events/urls.py | from django.conf.urls.defaults import url, patterns
from . import views
urlpatterns = patterns('',
url(r'^(?P<slug>[a-z0-9-]+)$', views.one, name='event_one'),
url(r'^', views.all, name='event_all'),
)
| from django.conf.urls.defaults import url, patterns
from . import views
urlpatterns = patterns('',
# Match
url(r'^(?P<slug>[a-z0-9-]+)$', views.one, name='event_one'),
url(r'^', views.all, name='event_all'),
)
| bsd-3-clause | Python |
7e5672e6527ad2fce8b1cb97b07228b4db8770e2 | Update to version 0.1.1 | Anthony25/mpd_muspy | mpd_muspy/__init__.py | mpd_muspy/__init__.py | #!/usr/bin/python
# Author: Anthony Ruhier
import __main__
import os
import sys
# Check that the configuration exists
try:
_current_dir = os.path.dirname(__main__.__file__)
except AttributeError:
_current_dir = os.getcwd()
if not os.path.exists(os.path.join(_current_dir, "config.py")):
print("Configuratio... | #!/usr/bin/python
# Author: Anthony Ruhier
import __main__
import os
import sys
# Check that the configuration exists
try:
_current_dir = os.path.dirname(__main__.__file__)
except AttributeError:
_current_dir = os.getcwd()
if not os.path.exists(os.path.join(_current_dir, "config.py")):
print("Configuratio... | bsd-2-clause | Python |
6cd3e3128be2308bf13029b01b7ac6cc0a4cd7be | Fix setupcluster.py script. | ymap/aioredis | setupcluster.py | setupcluster.py | import argparse
import os
import sys
from aioredis.cluster.testcluster import TestCluster
assert sys.version >= '3.5', 'Please use Python 3.5 or higher.'
START_PORT = 7001
REDIS_COUNT = 6
def parse_arguments():
parser = argparse.ArgumentParser(
description="Set up a Redis cluster to run the examples.")... | import argparse
import os
import sys
from aioredis.cluster import testcluster
assert sys.version >= '3.3', 'Please use Python 3.3 or higher.'
START_PORT = 7001
REDIS_COUNT = 6
def parse_arguments():
parser = argparse.ArgumentParser(
description="Set up a Redis cluster for the unittests.")
parser.ad... | mit | Python |
abfcf0bdee7183ee46d784fb53918e95b477554e | fix pages/admin.py for InterestedForm | raccoongang/socraticqs2,cjlee112/socraticqs2,raccoongang/socraticqs2,raccoongang/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2,cjlee112/socraticqs2,cjlee112/socraticqs2 | mysite/pages/admin.py | mysite/pages/admin.py | from django.contrib import admin
from models import InterestedForm
class InterestedFormAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email', 'timezone')
admin.site.register(InterestedForm, InterestedFormAdmin)
| from django.contrib import admin
from models import InterestedForm
class InterestedFormAdmin(admin.ModelAdmin):
pass
admin.register(InterestedFormAdmin, InterestedForm)
# Register your models here.
| apache-2.0 | Python |
6607258b78002637372f67ee238bdb35aba7ce61 | check both /v0/ and /v0/legacy | NCI-GDC/gdc-client,NCI-GDC/gdc-client | gdc_client/query/index.py | gdc_client/query/index.py | import requests
from urlparse import urljoin
from ..log import get_logger
# Logging
log = get_logger('query')
class GDCIndexClient(object):
def __init__(self, uri):
self.uri = uri if uri.endswith('/') else uri + '/'
def get_related_files(self, file_id):
"""Query the GDC api for related fil... | import requests
from urlparse import urljoin
from ..log import get_logger
# Logging
log = get_logger('query')
class GDCIndexClient(object):
def __init__(self, uri):
self.uri = uri if uri.endswith('/') else uri + '/'
def get_related_files(self, file_id):
"""Query the GDC api for related fil... | apache-2.0 | Python |
8fec68740ab7f8467f952f478a971a8418d48108 | Add run_cmd logging statement | sjktje/sjkscan,sjktje/sjkscan | sjkscan/scan.py | sjkscan/scan.py | #!/usr/bin/env python
# encoding: utf-8
import logging
import os
from datetime import datetime
from .config import config, load_config
from .utils import run_cmd
from .logging import init_logging
def run_scan(output_directory):
"""Run scanimage in batch mode.
:param string output_directory: directory to wr... | #!/usr/bin/env python
# encoding: utf-8
import os
from datetime import datetime
from .config import config, load_config
from .utils import run_cmd
def run_scan(output_directory):
"""Run scanimage in batch mode.
:param string output_directory: directory to write scanned images to
"""
command = [
... | bsd-2-clause | Python |
f22267a1bed6520a1531f33b30130da556dd1348 | Fix gunicorn.http.__all__. | mvaled/gunicorn,malept/gunicorn,gtrdotmcs/gunicorn,WSDC-NITWarangal/gunicorn,zhoucen/gunicorn,harrisonfeng/gunicorn,elelianghh/gunicorn,GitHublong/gunicorn,malept/gunicorn,MrKiven/gunicorn,tejasmanohar/gunicorn,mvaled/gunicorn,keakon/gunicorn,zhoucen/gunicorn,ccl0326/gunicorn,ephes/gunicorn,mvaled/gunicorn,gtrdotmcs/gu... | gunicorn/http/__init__.py | gunicorn/http/__init__.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.message import Message, Request
from gunicorn.http.parser import RequestParser
__all__ = ['Message', 'Request', 'RequestParser']
| # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.message import Message, Request
from gunicorn.http.parser import RequestParser
__all__ = [Message, Request, RequestParser]
| mit | Python |
62bb9d7785e3ba9241b6a8531685e7f3266db7cd | Revert "Add initial notification's target #19" | nnsnodnb/django-ios-notifications,nnsnodnb/django-ios-notifications | notification/forms.py | notification/forms.py | from django import forms
from .models import DeviceToken
class CertFileUploadForm(forms.Form):
cert_file = forms.FileField()
target = forms.ChoiceField(choices=((0, 'Develop'), (1, 'Distribute')), required=True, widget=forms.RadioSelect)
class NotificationSendForm(forms.Form):
target = forms.ChoiceFiel... | from django import forms
from .models import DeviceToken
class CertFileUploadForm(forms.Form):
cert_file = forms.FileField()
target = forms.ChoiceField(choices=((0, 'Develop'), (1, 'Distribute')), required=True, widget=forms.RadioSelect)
class NotificationSendForm(forms.Form):
target = forms.ChoiceFiel... | mit | Python |
c095525de6f28feb3cb34ca63c4c13091a10a726 | Fix error caused by missing "-static" libraries defines for some platform e.g. OSX and BSD | cpcloud/numba,gmarkall/numba,cpcloud/numba,gmarkall/numba,gmarkall/numba,stuartarchibald/numba,IntelLabs/numba,stonebig/numba,gmarkall/numba,numba/numba,cpcloud/numba,numba/numba,IntelLabs/numba,IntelLabs/numba,stonebig/numba,stonebig/numba,cpcloud/numba,IntelLabs/numba,numba/numba,stuartarchibald/numba,gmarkall/numba,... | numba/misc/findlib.py | numba/misc/findlib.py | import sys
import os
import re
def get_lib_dirs():
"""
Anaconda specific
"""
if sys.platform == 'win32':
# on windows, historically `DLLs` has been used for CUDA libraries,
# since approximately CUDA 9.2, `Library\bin` has been used.
dirnames = ['DLLs', os.path.join('Library', ... | import sys
import os
import re
def get_lib_dirs():
"""
Anaconda specific
"""
if sys.platform == 'win32':
# on windows, historically `DLLs` has been used for CUDA libraries,
# since approximately CUDA 9.2, `Library\bin` has been used.
dirnames = ['DLLs', os.path.join('Library', ... | bsd-2-clause | Python |
4e080dc896737d9bd60fe0f02004489bbfecedd4 | Fix article admin. | opps/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps | opps/article/admin.py | opps/article/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from opps.article.models import Post, PostImage, PostSource
from redactor.widgets import RedactorEditor
class PostImageInline(admin.T... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from opps.article.models import Post, PostImage, PostSource
from redactor.widgets import RedactorEditor
class PostImageInline(admin.TabularInline):
model = PostImage
fk_name = 'post... | mit | Python |
c63cf3972ecd26438c3825bdf67ebd0e8b4751f1 | update docstring formatting | incuna/django-orderable,incuna/django-orderable | orderable/managers.py | orderable/managers.py | from django.db import models
class OrderableManager(models.Manager):
"""
Adds additional functionality to `Orderable.objects`.
Provides access to the next and previous ordered object within the queryset.
"""
def before(self, orderable):
return self.filter(sort_order__lt=orderable.sort_ord... | from django.db import models
class OrderableManager(models.Manager):
'''
Adds additional functionality to `Orderable.objects` providing access to the next and
previous ordered object within the queryset.
'''
def before(self, orderable):
return self.filter(sort_order__lt=orderable.sort_orde... | bsd-2-clause | Python |
ab4ba6e453b68fd084dc4cafdc193a17557fcf1d | Update WitForJBMC.py | ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec | benchexec/tools/WitForJBMC.py | benchexec/tools/WitForJBMC.py | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2021 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
ht... | import benchexec.tools.template
import benchexec.result as result
class Tool(benchexec.tools.template.BaseTool2):
def executable(self, tool_locator):
return tool_locator.find_executable("Wit4JBMC.py")
def name(self):
return "Wit4JBMC"
def cmdline(self, executable, options, task, rlimits):
return [executable]... | apache-2.0 | Python |
42988dc093c688ad1975116fc0c0e85e943e70b5 | Complete a test case | biothings/biothings.api,biothings/biothings.api | biothings/tests/test_query.py | biothings/tests/test_query.py | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by def... | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by def... | apache-2.0 | Python |
9f09f21c592bc2a0da6a4f56bcf4b971411474b1 | increase min processing threshold | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/form_processor/management/commands/run_submission_reprocessing_queue.py | corehq/form_processor/management/commands/run_submission_reprocessing_queue.py | from datetime import timedelta, datetime
from time import sleep
from django.core.management import BaseCommand
from django.db.models import F
from django.db.models import Q
from corehq.form_processor.tasks import reprocess_submission
from corehq.util.metrics import metrics_gauge
from couchforms.models import Unfinish... | from datetime import timedelta, datetime
from time import sleep
from django.core.management import BaseCommand
from django.db.models import F
from django.db.models import Q
from corehq.form_processor.tasks import reprocess_submission
from corehq.util.metrics import metrics_gauge
from couchforms.models import Unfinish... | bsd-3-clause | Python |
3d7b5d61b7e985d409cd50c98d4bcbdc8ab9c723 | Use current user as email author | 2mv/raapija | mailer.py | mailer.py | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
import os
import pwd
import socket
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' + socket.getfqdn()
@stat... | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
@staticmethod
def send(message):
Mailer.MAILER.send(message)
@staticmethod
def start():
Mailer.MAILER.s... | isc | Python |
169bd20e0b0158b67d0dce226730c48dd4f2763b | Update the deploy code | tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website | manage.py | manage.py | #!/usr/bin/env python3
import os
from getpass import getpass
from flask_frozen import Freezer
from manager import Manager
from personal_website.endpoint_freezer import freeze_endpoints
from personal_website.flask_app import app, process_static
from personal_website.routes import attach_routes
css_file = process_stat... | #!/usr/bin/env python3
import os
from getpass import getpass
from flask_frozen import Freezer
from manager import Manager
from personal_website.endpoint_freezer import freeze_endpoints
from personal_website.flask_app import app, process_static
from personal_website.routes import attach_routes
css_file = process_stat... | mit | Python |
516c84d3b13262e59e9be59580ac5f8959d2e650 | Add back the Django seamless virtualenv snippet to provide update_ve command #33 | tovmeod/anaf,thiagof/treeio,Sofcom/treeio,thiagof/treeio,Sofcom/treeio,thiagof/treeio,treeio/treeio,treeio/treeio,nuwainfo/treeio,treeio/treeio,nuwainfo/treeio,treeio/treeio,Sofcom/treeio,Sofcom/treeio,tovmeod/anaf,nuwainfo/treeio,treeio/treeio,nuwainfo/treeio,Sofcom/treeio,thiagof/treeio,tovmeod/anaf,tovmeod/anaf,tovm... | manage.py | manage.py | # encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
#!/usr/bin/env python
import sys
import shutil
try:
import virtualenv
except ImportError:
print 'Error: virtualenv module not found. Please install virtualenv (e.g. pip install virtualenv)'
import su... | # encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stde... | bsd-3-clause | Python |
7337c3ab453347e8b70804dc2b5b1dd3797c0102 | fix test | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | bustimes/management/tests/test_tnds.py | bustimes/management/tests/test_tnds.py | import mock
import time_machine
from datetime import timedelta
from tempfile import TemporaryDirectory
from pathlib import Path
from django.test import TestCase, override_settings
from django.core.management import call_command
class TNDSTest(TestCase):
@mock.patch('bustimes.management.commands.import_tnds.call_c... | import mock
import time_machine
from datetime import timedelta
from django.test import TestCase
from django.core.management import call_command
class TNDSTest(TestCase):
@mock.patch('bustimes.management.commands.import_tnds.call_command')
@mock.patch('ftplib.FTP', autospec=True)
@mock.patch('boto3.client'... | mpl-2.0 | Python |
d5a1acbae91431ca781b659243013a5928ece5b9 | fix args splitting in next cmd | Djiit/err-meetup | meetup.py | meetup.py | # coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from datetime import datetime
import json
try:
from http import client
except ImportError:
import httplib as client
from jinja2 import Environment
from errbot import BotPlugin, botcmd
... | # coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from datetime import datetime
import json
try:
from http import client
except ImportError:
import httplib as client
from jinja2 import Environment
from errbot import BotPlugin, botcmd
... | mit | Python |
0a2b548f4c637f803ddbd19ac899fcc7ecf54caf | make the version information available to "piped -v" | alexbrasetvik/Piped,foundit/Piped,foundit/Piped,alexbrasetvik/Piped | contrib/cyclone/piped/plugins/cyclone_provider.py | contrib/cyclone/piped/plugins/cyclone_provider.py | from piped_cyclone import version
from piped_cyclone.providers import * | from piped_cyclone.providers import * | mit | Python |
696a2b19e70fdbefc416cb6b519589e404708f92 | Add www.censusreporter.org to allowed_hosts | censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter | censusreporter/config/prod/settings.py | censusreporter/config/prod/settings.py | from config.base.settings import *
DEBUG = False
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'censusreporter.org',
'www.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.a... | from config.base.settings import *
DEBUG = False
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.amazonaws.com', # from the lo... | mit | Python |
27a54a2545100cbc755721275441a7cf4b93a306 | make sure we get the right service **before** closing the connection. | shenhequnying/ceph-deploy,osynge/ceph-deploy,ceph/ceph-deploy,shenhequnying/ceph-deploy,zhouyuan/ceph-deploy,imzhulei/ceph-deploy,Vicente-Cheng/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,trhoden/ceph-deploy,SUSE/ceph-deploy,ghxandsky/ceph-deploy,alfredodeza/ceph-deploy,rtulke/ceph-deploy,ddiss/ceph-deploy,rtulke/ceph-d... | ceph_deploy/hosts/debian/mon/create.py | ceph_deploy/hosts/debian/mon/create.py | from ceph_deploy.hosts import common
from ceph_deploy.misc import remote_shortname
from ceph_deploy.lib.remoto import process
from ceph_deploy.connection import get_connection
def create(distro, logger, args, monitor_keyring):
hostname = remote_shortname(distro.sudo_conn.modules.socket)
common.mon_create(dist... | from ceph_deploy.hosts import common
from ceph_deploy.misc import remote_shortname
from ceph_deploy.lib.remoto import process
from ceph_deploy.connection import get_connection
def create(distro, logger, args, monitor_keyring):
hostname = remote_shortname(distro.sudo_conn.modules.socket)
common.mon_create(dist... | mit | Python |
b07d46dd5c20bbf98d867595c138ec95b3e17f2b | Update mo_sms.py | darkpioneer/aaisp | mo_sms.py | mo_sms.py | #!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi, sys
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
# Parse the form data posted
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST','CONTENT_TYPE':self.hea... | #!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi, sys
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
# Parse the form data posted
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST','CONTENT_TYPE':self.hea... | agpl-3.0 | Python |
3023f630fd615dffb44ac75d593d9c2677b8a0b6 | Add rest to import | hydroshare/hydroshare,hydroshare/hydroshare,FescueFungiShare/hydroshare,RENCI/xDCIShare,RENCI/xDCIShare,hydroshare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,FescueFungiSh... | hs_core/tests/__init__.py | hs_core/tests/__init__.py | from .api.native import *
from .api.rest import *
| __author__ = 'jeffersonheard'
from .api.native import *
#from .api.http import *
| bsd-3-clause | Python |
21ec2389f430b67b0380ef43c05e3c82de24cd23 | Check for mariadb file descriptor limit | coolsvap/clapper,coolsvap/clapper,rthallisey/clapper,coolsvap/clapper,rthallisey/clapper | check_overcloud_controller_settings.py | check_overcloud_controller_settings.py | #!/usr/bin/env python
import os
import ConfigParser
MARIADB_MAX_CONNECTIONS_MIN = 4096
MARIADB_OPEN_FILES_LIMIT_MIN = 16384
def find_mariadb_config_file():
potential_locations = [
'/etc/my.cnf.d/galera.cnf',
'/etc/my.cnf.d/server.cnf',
'/etc/my.cnf',
]
for filepath in potential_lo... | #!/usr/bin/env python
import os
import ConfigParser
MARIADB_MAX_CONNECTIONS_MIN = 4096
def find_mariadb_config_file():
potential_locations = [
'/etc/my.cnf.d/galera.cnf',
'/etc/my.cnf.d/server.cnf',
'/etc/my.cnf',
]
for filepath in potential_locations:
if os.access(filepat... | apache-2.0 | Python |
aa8fb0d70a6fcbee4f5bd3ddfd940c7093abd0de | delete image file on deletion of Image object | allo-/django-imagehoster | models.py | models.py | from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
import settings
assert hasattr(settings, "UPLOAD_DIR"), "you need to set UPLOAD_DIR (relative to MEDIA_URL) in settings"
assert len(settings.UPLOAD_DIR) and settings.UPLOAD_DIR[-1] == "/", "UPLOAD_DIR must... | from django.db import models
import settings
assert hasattr(settings, "UPLOAD_DIR"), "you need to set UPLOAD_DIR (relative to MEDIA_URL) in settings"
assert len(settings.UPLOAD_DIR) and settings.UPLOAD_DIR[-1] == "/", "UPLOAD_DIR must have a trailing slash"
class Image(models.Model):
date=models.DateTimeField(aut... | agpl-3.0 | Python |
65973802a3e68e23f9a903937ef94f8afa277013 | Create documentation of DataSource Settings | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | apache-2.0 | Python |
0016c305f872ae63e5bb2126630f0742b9221113 | change module iface by environment variable GDPY3_IFACE | shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3 | src/__main__.py | src/__main__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2020 shmilee
if __name__ == "__main__":
import os
iface = os.getenv('GDPY3_IFACE', default='gui')
if iface == 'gui':
from .GUI import gui_script as i_script
else:
from .cli import cli_script as i_script
i_script()
| # -*- coding: utf-8 -*-
# Copyright (c) 2020 shmilee
if __name__ == "__main__":
iface = 'cli'
if iface == 'gui':
from .GUI import gui_script as i_script
else:
from .cli import cli_script as i_script
i_script()
| mit | Python |
b19f86e13d0fca2f2ea5dbbc99e4cf8b08a3a81d | add validate for store view | Go-In/go-coup,Go-In/go-coup,Go-In/go-coup,Go-In/go-coup,Go-In/go-coup | storemanage/views.py | storemanage/views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from .models import Currency, Ticket
from django.utils.dateparse import parse_date
@login_required()
@permission_required('usermanage.store_rights',ra... | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from .models import Currency, Ticket
from django.utils.dateparse import parse_date
@login_required()
@permission_required('usermanage.store_rights',ra... | mit | Python |
7cf05ec8b45e2f50f2e45ef13354f2b54a02c712 | support stormlocal -t in streamparse.cmdln | eric7j/streamparse,scrapinghub/streamparse,eric7j/streamparse,petchat/streamparse,phanib4u/streamparse,msmakhlouf/streamparse,msmakhlouf/streamparse,scrapinghub/streamparse,hodgesds/streamparse,msmakhlouf/streamparse,Parsely/streamparse,codywilbourn/streamparse,crohling/streamparse,phanib4u/streamparse,scrapinghub/stre... | streamparse/cmdln.py | streamparse/cmdln.py | from docopt import docopt
from invoke import run
def main():
"""sparse: manage streamparse clusters.
sparse provides a front-end to streamparse, a framework for creating Python
projects for running, debugging, and submitting computation topologies against
real-time streams, using Apache Storm.
It... | from docopt import docopt
from invoke import run
def main():
"""sparse: manage StreamParse clusters.
sparse provides a front-end to StreamParse, a framework for creating Python
projects for running, debugging, and submitting Storm topologies for data
processing.
It requires the lein (Clojure buil... | apache-2.0 | Python |
d6fd0ee9e38ccc4391eea4e73dfdda45a365621f | Fix errors in tasks | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | studygroups/tasks.py | studygroups/tasks.py | from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from django.utils import translation
from django.contrib.auth.models import User
from studygroups.models import StudyGroup
from studygroups.models import StudyGroupMeeting
from stu... | from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from django.utils import translation
from django.contrib.auth.models import User
from studygroups.models import StudyGroup
from studygroups.models import StudyGroupMeeting
from stu... | mit | Python |
99ce8dedeec67b46c7e7f90709bedaf132d9fcd5 | Fix syntax error | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | studygroups/tasks.py | studygroups/tasks.py | from django.utils import timezone
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_group_message
import datetime
def send_reminders():
now = timezone.now()
for reminder in Reminder.objects.fi... | from django.utils import timezone
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.generate_reminder
from studygroups.models import send_group_message
import datetime
def send_reminders():
now = timezone.now()
for reminder in Reminder.objects.filter(sent_at__... | mit | Python |
5c180b5048df69f9ae37289c5ae49cb266ba10cf | Replace use of deprecated Pillow constant `Image.ANTIALIAS` | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | byceps/util/image/__init__.py | byceps/util/image/__init__.py | """
byceps.util.image
~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from io import BytesIO
from typing import BinaryIO, Union
from PIL import Image, ImageFile
from .models import Dimensions
FilenameOrStream = Union[str, BinaryIO]
def read... | """
byceps.util.image
~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from io import BytesIO
from typing import BinaryIO, Union
from PIL import Image, ImageFile
from .models import Dimensions
FilenameOrStream = Union[str, BinaryIO]
def read... | bsd-3-clause | Python |
b5f9f36daf680eb1873558dcd853b99ccf85d1a7 | change path to stored re data | the-it/WS_THEbotIT,the-it/WS_THEbotIT | scripts/service/ws_re/download/base.py | scripts/service/ws_re/download/base.py | import os
from abc import ABC, abstractmethod
from pathlib import Path
BASE_PATH = Path("/mnt/temp_erik/re")
if not os.path.isdir(BASE_PATH):
os.mkdir(BASE_PATH)
class DownloadTarget(ABC):
@abstractmethod
def get_source(self):
pass
@abstractmethod
def get_target(self):
pass
| import os
from abc import ABC, abstractmethod
from pathlib import Path
BASE_PATH = Path.home().joinpath("re")
if not os.path.isdir(BASE_PATH):
os.mkdir(BASE_PATH)
class DownloadTarget(ABC):
@abstractmethod
def get_source(self):
pass
@abstractmethod
def get_target(self):
pass
| mit | Python |
f9c198194d8fd64b7e5c43eaf252edf79a16e07f | Update setup.py for new pip package release (#262) | google/osv.dev,google/osv.dev,google/osv.dev,google/osv.dev,google/osv.dev | lib/setup.py | lib/setup.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | apache-2.0 | Python |
1d0800c2fada6d88a9650c85bfd5b4e78c3b9973 | Fix Flake8 violation | Commonists/pageview-api | pageviewapi/period.py | pageviewapi/period.py | """Helper functions on period."""
import datetime
import pageviewapi.client
def sum_last(project, page, last=30, agent='all-agents', access='all-access'):
"""Page views during last days."""
views = pageviewapi.client.per_article(project, page,
__days_ago__(last),
... | """Helper functions on period."""
import datetime
import pageviewapi.client
def sum_last(project, page, last=30, agent='all-agents', access='all-access'):
"""Page views during last days."""
views = pageviewapi.client.per_article(project, page,
__days_ago__(last),
... | mit | Python |
6ae5d15c00ce6bd1aa21f522db5a6b423e772bff | add note about assumption re: energy | mattjj/pybasicbayes,fivejjs/pybasicbayes,michaelpacer/pybasicbayes | parallel_tempering.py | parallel_tempering.py | from __future__ import division
import numpy as np
from collections import defaultdict
from util.text import progprint_xrange
class ParallelTempering(object):
def __init__(self,model,temperatures):
temperatures = [1.] + list(sorted(temperatures))
self.models = [model.copy_sample() for T in tempera... | from __future__ import division
import numpy as np
from collections import defaultdict
from util.text import progprint_xrange
class ParallelTempering(object):
def __init__(self,model,temperatures):
temperatures = [1.] + list(sorted(temperatures))
self.models = [model.copy_sample() for T in tempera... | mit | Python |
b6fa47b0a2195c754c0770316af5130cdad4f8af | Test for `Every` | jscott1989/django-periodically,hzdg/django-periodically | periodically/tests.py | periodically/tests.py | from django.test import TestCase
from . import schedules
from datetime import datetime
now = datetime(1983, 7, 1, 3, 41)
class ScheduleTest(TestCase):
def test_hourly(self):
sched = schedules.Hourly(20, 2, 4)
self.assertEqual(sched.time_before(now), datetime(1983, 7, 1, 3, 20, 2, 4))
sel... | from django.test import TestCase
from . import schedules
from datetime import datetime
now = datetime(1983, 7, 1, 3, 41)
class ScheduleTest(TestCase):
def test_hourly(self):
sched = schedules.Hourly(20, 2, 4)
self.assertEqual(sched.time_before(now), datetime(1983, 7, 1, 3, 20, 2, 4))
sel... | mit | Python |
3943a81a96dbed18ac14a85420a1094c6ea2f8d1 | Fix dumb typo | twneale/tater,twneale/tater | tater/core/config.py | tater/core/config.py | import os
import logging
LOG_MSG_MAXWIDTH = 300
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
'datefmt': '%H:%M:%S'
}
},
'handlers': {
'd... | import os
import logging
LOG_MSG_MAXWIDTH = 300
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'form at': "%(asctime)s %(levelname)s %(name)s: %(message)s",
'datefmt': '%H:%M:%S'
}
},
'handlers': {
'... | bsd-3-clause | Python |
860215950666e283126b934011b79e23e88ed16b | Fix filter not being optional, display job offers count | esabouraud/scripts,esabouraud/scripts | jsonjobs/jobs/__main__.py | jsonjobs/jobs/__main__.py | """Get jobs offer from json stream"""
import re
import argparse
import json
import urllib3
urllib3.disable_warnings()
def get_jobs_json(url):
"""Get jobs json payload"""
http = urllib3.PoolManager()
req = http.request("GET", url)
return req.data
def display_jobs(jobs_json, joburl_prefix, filter_r... | """Get jobs offer from json stream"""
import re
import argparse
import json
import urllib3
urllib3.disable_warnings()
def get_jobs_json(url):
"""Get jobs json payload"""
http = urllib3.PoolManager()
req = http.request("GET", url)
return req.data
def display_jobs(jobs_json, joburl_prefix, filter_r... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.