commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3
values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
8683400f5c76a5afd71655c67eef89e98b39c19c | make test runnable standalone | tests/test_issues/test_issue_26.py | tests/test_issues/test_issue_26.py | #!/usr/bin/env python
from radical.entk import Pipeline, Stage, Task, AppManager
from radical.entk import states
from radical.entk.exceptions import *
import pytest
import os
hostname = os.environ.get('RMQ_HOSTNAME','localhost')
port = int(os.environ.get('RMQ_PORT',5672))
# MLAB = 'mongodb://entk:entk123@ds143511.mla... | from radical.entk import Pipeline, Stage, Task, AppManager
from radical.entk import states
from radical.entk.exceptions import *
import pytest
import os
hostname = os.environ.get('RMQ_HOSTNAME','localhost')
port = int(os.environ.get('RMQ_PORT',5672))
# MLAB = 'mongodb://entk:entk123@ds143511.mlab.com:43511/entk_0_7_4_... | Python | 0.000002 |
e5d13f315624be780fd60a04ff255f6682bdd84b | Update set_student_guardian.py | erpnext/patches/v7_1/set_student_guardian.py | erpnext/patches/v7_1/set_student_guardian.py | import frappe
def execute():
if frappe.db.exists("DocType", "Guardian"):
frappe.reload_doc("schools", "doctype", "student")
frappe.reload_doc("schools", "doctype", "student_guardian")
frappe.reload_doc("schools", "doctype", "student_sibling")
if "student" not in frappe.db.get_table_columns("Guardian"):
ret... | import frappe
def execute():
if frappe.db.exists("DocType", "Guardian"):
frappe.reload_doc("schools", "doctype", "student")
frappe.reload_doc("schools", "doctype", "student_guardian")
frappe.reload_doc("schools", "doctype", "student_sibling")
guardian = frappe.get_all("Guardian", fields=["name", "student"])
... | Python | 0.000003 |
1b13a1da1b483d8f31fb1f694a7c0236ce01befa | update stats widget | lase/gui/stats_widget.py | lase/gui/stats_widget.py | # -*- coding: utf-8 -*-
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
class StatsWidget(QtGui.QWidget):
def __init__(self, driver):
super(StatsWidget, self).__init__()
self.driver = driver
self.layout = QtGui.QHBoxLayout()
self.mean_labels = []
self.ampl_lab... | # -*- coding: utf-8 -*-
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
class StatsWidget(QtGui.QWidget):
def __init__(self, driver):
super(StatsWidget, self).__init__()
self.driver = driver
self.layout = QtGui.QHBoxLayout()
self.mean_labels = []
self.ampl_lab... | Python | 0.000001 |
9986da1599e5beaaad49d389b2a2ee3d4f308991 | fix https://github.com/BackofenLab/AlgoDat/issues/61 | Lecture-4/Code/AssociativeArray.py | Lecture-4/Code/AssociativeArray.py | # creates a new map (called dictionary)
countries = {"DE" : "Deutschland", \
"EN" : "England"}
# check if element exists
if "EN" in countries:
print("Found %s!" % countries["EN"])
# map key "DE" to value "Germany"
countries["DE"] = "Germany"
# delete key "DE"
del countries["DE"]
| # creates a new map (called dictionary)
countries = {"DE" : "Deutschland", \
"EN" : "England"}
# check if element exists
if "EN" in countries:
print("Found %s!" % countries["EN"])
# map key "DE" to value 0
countries["DE"] = "Germany"
# delete key "DE"
del countries["DE"]
| Python | 0 |
f98ef68949b8875daeb5b8346a65a842a682a5df | replace linebreaks in version strings | nvchecker/get_version.py | nvchecker/get_version.py | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import logging
from importlib import import_module
logger = logging.getLogger(__name__)
handler_precedence = (
'github', 'aur', 'pypi', 'archpkg', 'debianpkg', 'ubuntupkg',
'gems', 'pacman',
'cmd', 'bitbucket', 'regex', 'manual', 'vc... | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import logging
from importlib import import_module
logger = logging.getLogger(__name__)
handler_precedence = (
'github', 'aur', 'pypi', 'archpkg', 'debianpkg', 'ubuntupkg',
'gems', 'pacman',
'cmd', 'bitbucket', 'regex', 'manual', 'vc... | Python | 0.000002 |
11c81ff161cad04a24a8746b93d3afb64e6a5b49 | fix typo | python/example_code/ec2/describe_subnets.py | python/example_code/ec2/describe_subnets.py | # Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is d... | # Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is d... | Python | 0.999991 |
178de6396dade359a3f8e137d4a3449155b88b89 | Add schema for workflow input with default value support | mistral/workbook/types.py | mistral/workbook/types.py | # Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | Python | 0.999965 |
4c4e997767681e91f5d115e998cda22433eae7f6 | allow to set a mode (list|map) | apps/mapideas/views.py | apps/mapideas/views.py | import django_filters
from django.contrib import messages
from django.utils.translation import ugettext as _
from adhocracy4.maps import mixins as map_mixins
from adhocracy4.modules import views as module_views
from apps.contrib import filters
from . import forms
from . import models
def get_ordering_choices(reque... | import django_filters
from django.contrib import messages
from django.utils.translation import ugettext as _
from adhocracy4.maps import mixins as map_mixins
from adhocracy4.modules import views as module_views
from apps.contrib import filters
from . import forms
from . import models
def get_ordering_choices(reque... | Python | 0 |
dac0afb3db74b1e8cd144993e662dc8ac0622cb9 | Add missing import to FTP module | osbrain/ftp.py | osbrain/ftp.py | """
Implementation of FTP-related features.
"""
import Pyro4
from .core import BaseAgent
from .common import address_to_host_port
class FTPAgent(BaseAgent):
"""
An agent that provides basic FTP functionality.
"""
def ftp_configure(self, addr, user, passwd, path, perm='elr'):
from pyftpdlib.aut... | """
Implementation of FTP-related features.
"""
from .core import BaseAgent
from .common import address_to_host_port
class FTPAgent(BaseAgent):
"""
An agent that provides basic FTP functionality.
"""
def ftp_configure(self, addr, user, passwd, path, perm='elr'):
from pyftpdlib.authorizers impo... | Python | 0.000001 |
c450ee554daf1b5c4143e33d5688df2fed776f99 | fix bug: 隐藏管理后台侧边栏配置owner字段,修复不填写作者无法保存侧边栏内容问题 | blogsys/blogsys/adminx.py | blogsys/blogsys/adminx.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:zq time:2018/3/15
from __future__ import unicode_literals
import xadmin
from xadmin.views import CommAdminView
class BaseOwnerAdmin(object):
'''
1.用来处理文章、分类、标签、侧边栏、友链这些model的owner子段自动补充
2.用来针对queryset过滤当前用户的数据
'''
exclude = ('owner',)
def... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:zq time:2018/3/15
from __future__ import unicode_literals
import xadmin
from xadmin.views import CommAdminView
class BaseOwnerAdmin(object):
'''
1.用来处理文章、分类、标签、侧边栏、友链这些model的owner子段自动补充
2.用来针对queryset过滤当前用户的数据
'''
exclude = ('owner')
def ... | Python | 0 |
0627033d55ffc21e820f03ab2609462a19ea32dd | Use content_type instead of mime type | bluebottle/utils/admin.py | bluebottle/utils/admin.py | from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import ChangeList
from django.db.models.aggregates import Sum
from .models import Language
import csv
from django.db.models.fields.files import FieldFile
from django.db.models.query import QuerySet
f... | from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import ChangeList
from django.db.models.aggregates import Sum
from .models import Language
import csv
from django.db.models.fields.files import FieldFile
from django.db.models.query import QuerySet
f... | Python | 0.000006 |
fa6927ec47253b8b7f642c67e1470680b0f8253f | fix logging | crate_project/settings/production/base.py | crate_project/settings/production/base.py | from ..base import *
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse",
},
},
"formatters": {
"simple": {
"format": "%(levelname)s %(message)s"
},
}... | from ..base import *
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse",
},
},
"formatters": {
"simple": {
"format": "%(levelname)s %(message)s"
},
}... | Python | 0.000002 |
06f2438bd3baad9d234f394697f8ebaa69002230 | clear code | apps/pages/managers.py | apps/pages/managers.py | from django.db import models
from django.core.cache import cache
from mysmile.settings.main import LANGUAGES
from apps.pages.models import Page, Page_translation
from apps.settings.managers import SettingsManager
class PagesManager(SettingsManager):
def get_content(self, request, lang=None, slug=Non... | from django.db import models
from django.core.cache import cache
from mysmile.settings.main import LANGUAGES
from apps.pages.models import Page, Page_translation
from apps.settings.managers import SettingsManager
class PagesManager(models.Manager):
def get_content(self, request, lang=None, slug=None):
c... | Python | 0.000081 |
fe983892386c7ca8a96817ce26158e667d920b97 | Add links from programs to pipelines | apps/pipeline/admin.py | apps/pipeline/admin.py | #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | Python | 0 |
5488a3d7247633995e19dcbaa16ad554104f221f | Update cumulusci/tasks/metadata_etl/help_text.py | cumulusci/tasks/metadata_etl/help_text.py | cumulusci/tasks/metadata_etl/help_text.py | from collections import defaultdict
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
from cumulusci.core.utils import process_list_arg, process_bool_arg
class SetFieldHelpText... | from collections import defaultdict
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
from cumulusci.core.utils import process_list_arg, process_bool_arg
class SetFieldHelpText... | Python | 0 |
b37057c35452f26d567677eaf15216fcf0282b1c | fix max_history in aug memo, it was my mistake there shouldn't be -1 | rasa_core/policies/augmented_memoization.py | rasa_core/policies/augmented_memoization.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import typing
from typing import Dict, List, Text, Optional
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.events import Act... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import typing
from typing import Dict, List, Text, Optional
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.events import Act... | Python | 0.000135 |
23eabb23ce0423a3b11ea56fff4ff06f91ddef95 | Create DebtLoan population method | finance/management/commands/populate.py | finance/management/commands/populate.py | from datetime import datetime
from datetime import timedelta
import random
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
import factory
import pytz
from accounts.factories import UserFactory
from books.factories import DebtLoanFacto... | from datetime import datetime
from datetime import timedelta
import random
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
import factory
import pytz
from accounts.factories import UserFactory
from books.factories import TransactionFa... | Python | 0.000001 |
0846347ab7931993e602463d81dc493457c2cf5f | Support Git URI | pipes/app/create_app.py | pipes/app/create_app.py | #!/usr/bin/env python
# A script for creating an application in spinnaker.
# Simply looks to see if the application already exists, if not, creates
import argparse
import configparser
import json
import logging
import os
import sys
import gogoutils
from jinja2 import Environment, FileSystemLoader
import requests
c... | #!/usr/bin/env python
# A script for creating an application in spinnaker.
# Simply looks to see if the application already exists, if not, creates
import argparse
import configparser
import json
import logging
import os
import sys
from jinja2 import Environment, FileSystemLoader
import requests
class SpinnakerApp... | Python | 0 |
a6128825eb7b4267a2a5a3116ec2625fdd8d3552 | Add outsuffix to prottable-qvality driver | app/drivers/prottable/qvality.py | app/drivers/prottable/qvality.py | from app.drivers.pycolator.qvality import QvalityDriver
from app.actions.prottable import qvality as preparation
from app.readers import tsv
class ProttableQvalityDriver(QvalityDriver):
"""Runs qvality on two protein tables"""
outsuffix = '_protqvality.txt'
def __init__(self, **kwargs):
super(Pro... | from app.drivers.pycolator.qvality import QvalityDriver
from app.actions.prottable import qvality as preparation
from app.readers import tsv
class ProttableQvalityDriver(QvalityDriver):
def __init__(self, **kwargs):
super(ProttableQvalityDriver).__init__(**kwargs)
self.score_get_fun = preparation.... | Python | 0 |
45fac42c7a790c5ff6cf656ee8e5984869cddbf3 | Clean up JWT args before creation | dockci/api/jwt.py | dockci/api/jwt.py | """ API relating to JWT authentication """
from datetime import datetime
import jwt
from flask import url_for
from flask_restful import Resource
from flask_security import current_user, login_required
from .base import BaseRequestParser
from .exceptions import OnlyMeError, WrappedTokenError, WrongAuthMethodError
fro... | """ API relating to JWT authentication """
from datetime import datetime
import jwt
from flask import url_for
from flask_restful import Resource
from flask_security import current_user, login_required
from .base import BaseRequestParser
from .exceptions import OnlyMeError, WrappedTokenError, WrongAuthMethodError
fro... | Python | 0.000004 |
3199b523a67f9c241950992a07fe38d2bbee07dc | Update migration file for namechange | seedlibrary/migrations/0003_extendedview_fix.py | seedlibrary/migrations/0003_extendedview_fix.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-02-21 02:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('seedlibrary', '0002_add_extendedview'),
]
operations = [
migrations.RenameFi... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-02-21 02:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('seedlibrary', '0002_auto_20170219_2058'),
]
operations = [
migrations.Rename... | Python | 0 |
17b0f5d7b718bc12755f7ddefdd76ee9312adf5f | Add content type text/html to response | books.py | books.py | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... | Python | 0.000001 |
75b5f6acc441efe66c22b548ea21c5a16210af33 | Update cuberun model with BN, and input shape. | bird/models/cuberun.py | bird/models/cuberun.py | from keras.layers import Input
from keras.layers import Dense, Activation, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras import backend as K
def CubeRun(nb_classes):
""" Instan... | import json
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
model = Sequential()
# conv (64 5x5 kernels, stride size 2x1)
# TODO : 1 channel?
model.add(Convolution2D(64, 5, 5, input_s... | Python | 0 |
bd07f1fd66fa91a2b480598447a0dc593c622c7f | Improve modularisation | bitbucket_sync/main.py | bitbucket_sync/main.py | """bitbucket-sync synchronize all the repositories of a bitbucket account to a
directory. The OAuth key and secret must already be activated in bitbucket.
Usage:
bitbucket-sync [--processes=processes] --key=<key> --secret=<secret> --directory=<directory>
bitbucket-sync --help
Options:
--help ... | """bitbucket-sync synchronize all the repositories of a bitbucket account to a
directory. The OAuth key and secret must already be activated in bitbucket.
Usage:
bitbucket-sync [--processes=processes] --key=<key> --secret=<secret> --directory=<directory>
bitbucket-sync --help
Options:
--help ... | Python | 0.000035 |
ced7ff090c44f706fa161b5e5bed8f36fb6570c9 | Set default pool to 1 worker. | blackgate/component.py | blackgate/component.py | # -*- coding: utf-8 -*-
from functools import partial
from blackgate.executor_pools import ExecutorPools
from blackgate.circuit_beaker import NoCircuitBeaker, InProcessCircuitBeaker, get_circuit_beaker
class Component(object):
def __init__(self):
self.pools = ExecutorPools()
self.circuit_beaker... | # -*- coding: utf-8 -*-
from functools import partial
from blackgate.executor_pools import ExecutorPools
from blackgate.circuit_beaker import NoCircuitBeaker, InProcessCircuitBeaker, get_circuit_beaker
class Component(object):
def __init__(self):
self.pools = ExecutorPools()
self.circuit_beaker... | Python | 0 |
89237e9af27fa46c08ec90cab4029f41b335708f | fix pep8 violations | examples/plugin/simphony_example/__init__.py | examples/plugin/simphony_example/__init__.py | # Functions, classes and constants exported here will be available
# when the `example` module is imported.
__all__ = ['A', 'B']
from .code import A, B
| # Functions, classes and constants exported here will be available
# when the `example` module is imported.
__all__ = ['A', 'B']
from .code import A, B
| Python | 0 |
4a498d83c15f89e00c095659df1fc38377acc0a3 | fix permissions for rewards | bluebottle/rewards/models.py | bluebottle/rewards/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import (CreationDateTimeField,
ModificationDateTimeField)
from bluebottle.utils.fields import MoneyField
from bluebottle.utils.utils import StatusDefinition
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import (CreationDateTimeField,
ModificationDateTimeField)
from bluebottle.utils.fields import MoneyField
from bluebottle.utils.utils import StatusDefinition
... | Python | 0 |
7851e867aec82f771683cc267ecb5989d2005aa1 | add same features as program in 03-janus | experiments/01-single-dimer/plot_velocity.py | experiments/01-single-dimer/plot_velocity.py | #!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=str, help='H5MD datafile')
parser.add_argument('--directed', action='store_true')
parser.add_argument('--histogram', action='store_true')
args = parser.parse_args()
import numpy as np
import h5py
import matplot... | #!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=str, help='H5MD datafile')
parser.add_argument('--directed', action='store_true')
args = parser.parse_args()
import numpy as np
import h5py
import matplotlib.pyplot as plt
with h5py.File(args.file, 'r') as f:
... | Python | 0 |
aabe64773baf0516ecce2e96793221d5bfa91040 | change to use environment variables | scripts/sillyserver.py | scripts/sillyserver.py | # Example of using the MQTT client class to subscribe to a feed and print out
# any changes made to the feed. Edit the variables below to configure the key,
# username, and feed to subscribe to for changes.
# Import standard python modules.
import sys, os, serial
# Import Adafruit IO MQTT client.
from Adafruit_IO im... | # Example of using the MQTT client class to subscribe to a feed and print out
# any changes made to the feed. Edit the variables below to configure the key,
# username, and feed to subscribe to for changes.
# Import standard python modules.
import sys
import serial
# Import Adafruit IO MQTT client.
from Adafruit_IO ... | Python | 0.000002 |
d4879a7640869b16e1ea50cdbff84f173a81b521 | simplify variable | examples/apt.py | examples/apt.py | from pyinfra import host
from pyinfra.modules import apt
SUDO = True
code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME')
print(host.fact.linux_name, code_name)
if host.fact.linux_name in ['Debian', 'Ubuntu']:
apt.packages(
{'Install some packages'},
['vim-addon-manag... | from pyinfra import host
from pyinfra.modules import apt
SUDO = True
# Note: Using linux_distribution fact so running from docker
# will show valid name since the lsb-release tool is not installed,
# otherwise could just use host.fact.linux_name
linux_name = host.fact.linux_distribution.get('name', '')
code_name = ho... | Python | 0.999861 |
4c81f9375529604999c35e36c4586856f9c4d458 | Handle bad error codes. | bot/app/sync/closure_sync.py | bot/app/sync/closure_sync.py | import logging
import urllib
import pytz
from datetime import datetime, timedelta
from api.models import RoadClosure, RoadClosureStatus
from bs4 import BeautifulSoup
from dateutil import tz
logger = logging.getLogger('bot.digest')
def get_road_closure():
tzTex = pytz.timezone('US/Central')
url = "http://ww... | import logging
import urllib
import pytz
from datetime import datetime, timedelta
from api.models import RoadClosure, RoadClosureStatus
from bs4 import BeautifulSoup
from dateutil import tz
logger = logging.getLogger('bot.digest')
def get_road_closure():
tzTex = pytz.timezone('US/Central')
url = "http://ww... | Python | 0.000002 |
630e362e727d4c7274b987008488d203e21f8ec6 | Use default quality | electionleaflets/apps/api/serializers.py | electionleaflets/apps/api/serializers.py | from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from people.models import Person
class ConstituencySerializer(serializers.ModelSerializer):
... | from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
from leaflets.models import Leaflet, LeafletImage
from constituencies.models import Constituency
from uk_political_parties.models import Party
from people.models import Person
class ConstituencySerializer(serializers.ModelSerializer):
... | Python | 0.000001 |
4626a20b2d46a3a8ea17d265dff220c5a02700d8 | Fix bug in clang-format's vim integration cause by r186789. | tools/clang-format/clang-format.py | tools/clang-format/clang-format.py | # This file is a minimal clang-format vim-integration. To install:
# - Change 'binary' if clang-format is not on the path (see below).
# - Add to your .vimrc:
#
# map <C-I> :pyf <path-to-this-file>/clang-format.py<CR>
# imap <C-I> <ESC>:pyf <path-to-this-file>/clang-format.py<CR>i
#
# The first line enables clang-f... | # This file is a minimal clang-format vim-integration. To install:
# - Change 'binary' if clang-format is not on the path (see below).
# - Add to your .vimrc:
#
# map <C-I> :pyf <path-to-this-file>/clang-format.py<CR>
# imap <C-I> <ESC>:pyf <path-to-this-file>/clang-format.py<CR>i
#
# The first line enables clang-f... | Python | 0.000141 |
f2de502608833dda82908a6bb4f639645f785c06 | Change to support PEP Varible naming scheme | boundary/hostgroup_update.py | boundary/hostgroup_update.py | #
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | #
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | Python | 0 |
9670454dbb7b2ec4ef61d60080a1bb798c3ace74 | use integer amounts for payment capture | boxoffice/extapi/razorpay.py | boxoffice/extapi/razorpay.py | # -*- coding: utf-8 -*-
import requests
from coaster.utils import LabeledEnum
from baseframe import __
from boxoffice import app
# Don't use a trailing slash
base_url = 'https://api.razorpay.com/v1/payments'
__all__ = ['RAZORPAY_PAYMENT_STATUS', 'capture_payment']
class RAZORPAY_PAYMENT_STATUS(LabeledEnum):
""... | # -*- coding: utf-8 -*-
import requests
from coaster.utils import LabeledEnum
from baseframe import __
from boxoffice import app
# Don't use a trailing slash
base_url = 'https://api.razorpay.com/v1/payments'
__all__ = ['RAZORPAY_PAYMENT_STATUS', 'capture_payment']
class RAZORPAY_PAYMENT_STATUS(LabeledEnum):
""... | Python | 0.000001 |
f8944c0ac5a80d72852d9b2ea1dc1fc7d79a1891 | Add test for deserialising | plugins/data/enumerated/test/test_enumerated_type.py | plugins/data/enumerated/test/test_enumerated_type.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... | Python | 0 |
9686b8165e0fcda8f64c6c6eadcc786c04d07803 | make sure lsf post exec command sends exit code back | flow/shell_command/lsf/commands/post_exec.py | flow/shell_command/lsf/commands/post_exec.py | from flow import exit_codes
from flow.commands.base import CommandBase
from flow.configuration.inject.broker import BrokerConfiguration
from flow.configuration.inject.orchestrator import OrchestratorConfiguration
from flow.configuration.settings.injector import setting
from flow.util.exit import exit_process
from injec... | from flow import exit_codes
from flow.commands.base import CommandBase
from flow.configuration.inject.broker import BrokerConfiguration
from flow.configuration.inject.orchestrator import OrchestratorConfiguration
from flow.configuration.settings.injector import setting
from flow.util.exit import exit_process
from injec... | Python | 0 |
2be23846aabae5307ef817561661783b44c43160 | Move error-message logic into exception class | falcom/table.py | falcom/table.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
class InconsistentColumnCounts (RuntimeError):
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
class InconsistentColumnCounts (RuntimeError):
... | Python | 0.000006 |
4ce117b65d4a6f18d327f00866eaa4383f908094 | Revert "meter import path." | faucet/meter.py | faucet/meter.py | """Configure meters."""
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2017 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except ... | """Configure meters."""
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2017 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except ... | Python | 0 |
db8b991600ab0a812e1d9af1a6e4bb7be25b5bd4 | fix apply_tote_contents_hint | jsk_2016_01_baxter_apc/node_scripts/apply_tote_contents_hint.py | jsk_2016_01_baxter_apc/node_scripts/apply_tote_contents_hint.py | #!/usr/bin/env python
import numpy as np
from jsk_2015_05_baxter_apc.msg import ObjectRecognition
import jsk_apc2016_common
from jsk_recognition_msgs.msg import ClassificationResult
from jsk_topic_tools import ConnectionBasedTransport
from jsk_topic_tools.log_utils import jsk_logwarn
import rospy
class ApplyToteCon... | #!/usr/bin/env python
import numpy as np
from jsk_2015_05_baxter_apc.msg import ObjectRecognition
import jsk_apc2016_common
from jsk_recognition_msgs.msg import ClassificationResult
from jsk_topic_tools import ConnectionBasedTransport
from jsk_topic_tools.log_utils import jsk_logwarn
import rospy
class ApplyToteCon... | Python | 0.000002 |
6654d6956982c31bbfe6eb22aae557049ea613ba | Fix incorrect formatting call in azure module (#33561) | lib/ansible/modules/cloud/azure/azure_rm_resourcegroup_facts.py | lib/ansible/modules/cloud/azure/azure_rm_resourcegroup_facts.py | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANS... | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANS... | Python | 0 |
02efde47b5cf20b7385eacaa3f21454ffa636ad7 | Update CodeStarConnections::Connection per 2020-07-23 update | troposphere/codestarconnections.py | troposphere/codestarconnections.py | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if conne... | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if conne... | Python | 0 |
c86d689e3593b6221b8b9120f6af16b32c2211d9 | Add __all__ and __version__ to __init__.py. | src/pu/__init__.py | src/pu/__init__.py | __all__ = 'utils'.split()
__version__ = '1.0.0'
| Python | 0.000107 | |
92469456222a8d5c00595ca34ea21c66042a5040 | modify main loop | parser/main.py | parser/main.py | import config
import parse
pipeout = open(config.PIPE_NAME, 'r')
while True:
input_record = pipeout.readline()
if input_record.split(',')[0] == '$GYRO':
gyro = input_record
if input_record.split(',')[0] == '$ACCEL':
accel = pipeout.readline()
if input_record.split(',')[0] == '$MAGNET':
... | import config
import parse
pipeout = open(config.PIPE_NAME, 'r')
while True:
input_record = pipeout.readline()
if input_record.split(',')[0] == '$GYRO':
gyro = input_record
accel = pipeout.readline()
magnet = pipeout.readline()
pressure = pipeout.readline()
parse.parse_... | Python | 0.000003 |
39e5defbb12da62fc132e89437b1ce408b85ec6b | Fix parsertests script exit code. | parsertests.py | parsertests.py | #!/usr/bin/env python
import sys
import os
import os.path as path
import glob
import subprocess as sp
from collections import namedtuple
from multiprocessing import Pool
# TODO: remove this silly script and write the tests in scala/gradle.
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = ... | #!/usr/bin/env python
import sys
import os
import os.path as path
import glob
import subprocess as sp
from collections import namedtuple
from multiprocessing import Pool
# TODO: remove this silly script and write the tests in scala/gradle.
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = ... | Python | 0 |
400f5531ff1edb41a0958b741de85a1040212274 | match timezone to Amsterdam | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Paul Salden'
SITENAME = u'paulsalden.com'
SITEURL = 'http://paulsalden.com'
PATH = 'content'
TIMEZONE = 'Europe/Amsterdam'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM =... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Paul Salden'
SITENAME = u'paulsalden.com'
SITEURL = 'http://paulsalden.com'
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = Non... | Python | 0.999947 |
a9b7f92edb7b3a73a2b38a45c5ad6a0deee18e19 | Add GA tracking | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'keyan'
SITENAME = u'keyan pishdadian'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Detroit'
DEFAULT_LANG = u'en'
THEME = "themes/flasky"
# Site analytics
GOOGLE_ANALYTICS_ACCOUNT = "UA-93664476-1"
# Feed generatio... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'keyan'
SITENAME = u'keyan pishdadian'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Detroit'
DEFAULT_LANG = u'en'
THEME = "themes/flasky"
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None... | Python | 0 |
c8a1b3a7475d3e964814cb9be2a82d00bba745d0 | Update settings | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Yann Baumgartner'
SITENAME = u'Histoires de briques'
SITESUBTITLE = 'Un site dédié aux LEGO®'
SITEURL = ''
GITHUB_URL = 'https://github.com/yannbaumgartner/histoires-de-briques.git'
PATH = 'content'
PAGE_PATHS = ['pages... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Yann Baumgartner'
SITENAME = u'Histoires de briques'
SITESUBTITLE = 'Un site dédié aux LEGO®'
SITEURL = ''
GITHUB_URL = 'https://github.com/yannbaumgartner/histoires-de-briques.git'
PATH = 'content'
PAGE_PATHS = ['pages... | Python | 0.000001 |
0a6e486a27a48c59e48f458ce1217848ed73ff24 | Fix time zone config | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Eric, Etan, Fred, Genny, and Steve'
SITENAME = u'The Nest'
SITEURL = ''
TIMEZONE = 'PST'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRA... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Eric, Etan, Fred, Genny, and Steve'
SITENAME = u'The Nest'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM =... | Python | 0.00004 |
c08e28a23778280e577793156ce5b455ba80f92f | Tag new release: 2.3.0 | floo/version.py | floo/version.py | PLUGIN_VERSION = '2.3.0'
# The line above is auto-generated by tag_release.py. Do not change it manually.
try:
from .common import shared as G
assert G
except ImportError:
from common import shared as G
G.__VERSION__ = '0.03'
G.__PLUGIN_VERSION__ = PLUGIN_VERSION
| PLUGIN_VERSION = '2.2.13'
# The line above is auto-generated by tag_release.py. Do not change it manually.
try:
from .common import shared as G
assert G
except ImportError:
from common import shared as G
G.__VERSION__ = '0.03'
G.__PLUGIN_VERSION__ = PLUGIN_VERSION
| Python | 0 |
fcc77ac1557ab7f5c3d5605240ea505b8b61b321 | Update utils.py | follow/utils.py | follow/utils.py | from django.core.urlresolvers import reverse
from django.db.models.fields.related import ManyToManyField, ForeignKey
from follow.models import Follow
from follow.registry import registry, model_map
from django import VERSION as DjangoVersion
if float('%s.%s' % DjangoVersion[:2]) >= 1.7:
module_name = 'model_name'
e... | from django.core.urlresolvers import reverse
from django.db.models.fields.related import ManyToManyField, ForeignKey
from follow.models import Follow
from follow.registry import registry, model_map
from django import VERSION as DjangoVersion
if float('%s.%s' % DjangoVersion[:2]) > 1.7:
module_name = 'model_name'
el... | Python | 0.000001 |
2191f877270fc984d5a8e7cc2ffe9ab8c1630101 | fix style | apps/smeuhoverride/views.py | apps/smeuhoverride/views.py | # Create your views here.
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.http import Http404, HttpResponse
from d... | # Create your views here.
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.http import Http404, HttpResponse
from d... | Python | 0.000001 |
9e909ae8988168de5ad65e01b2231b4fb81088e7 | Check if the fqdn is localhost.localdomain. If yes, raise Exception | dbaas/workflow/steps/mysql/deploy/config_vms_foreman.py | dbaas/workflow/steps/mysql/deploy/config_vms_foreman.py | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from util import get_credentials_for
from util import exec_remote_command
from dbaas_foreman import get_foreman_provider
from dbaas_credentials.models import CredentialType
from dbaas_cloudstack.models import HostAttr
from ...util.base import BaseStep
f... | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from util import get_credentials_for
from util import exec_remote_command
from dbaas_foreman import get_foreman_provider
from dbaas_credentials.models import CredentialType
from dbaas_cloudstack.models import HostAttr
from ...util.base import BaseStep
f... | Python | 0.998786 |
b9c474d1877190ef73e295c46ac8b7ae58a803cf | put pytest skip marker after imports | borg/testsuite/convert.py | borg/testsuite/convert.py | import os
import shutil
import tempfile
import pytest
try:
import attic.repository
import attic.key
import attic.helpers
except ImportError:
attic = None
from ..converter import AtticRepositoryConverter, AtticKeyfileKey
from ..helpers import get_keys_dir
from ..key import KeyfileKey
from ..repository... | import os
import shutil
import tempfile
import pytest
try:
import attic.repository
import attic.key
import attic.helpers
except ImportError:
attic = None
pytestmark = pytest.mark.skipif(attic is None,
reason='cannot find an attic install')
from ..converter import Attic... | Python | 0 |
7750aaaea4115007a2cd39bad0277e81c2d4a031 | Use the correct parameter for Google API key | omgeo/services/google.py | omgeo/services/google.py | import logging
from .base import GeocodeService
from omgeo.places import Candidate
from omgeo.preprocessors import ComposeSingleLine
logger = logging.getLogger(__name__)
class Google(GeocodeService):
"""
Class to geocode using Google's geocoding API.
"""
_endpoint = 'https://maps.googleapis.com/maps... | import logging
from .base import GeocodeService
from omgeo.places import Candidate
from omgeo.preprocessors import ComposeSingleLine
logger = logging.getLogger(__name__)
class Google(GeocodeService):
"""
Class to geocode using Google's geocoding API.
"""
_endpoint = 'https://maps.googleapis.com/maps... | Python | 0.000006 |
1ca331975ab91cf619c3c785ead5b352af47963a | Use local thread storage. | modoboa/lib/middleware.py | modoboa/lib/middleware.py | # coding: utf-8
"""Custom middlewares."""
from threading import local
from django.http import HttpResponseRedirect
from modoboa.lib.exceptions import ModoboaException
from modoboa.lib.signals import request_accessor
from modoboa.lib.web_utils import (
_render_error, ajax_response, render_to_json_response
)
_lo... | # coding: utf-8
"""Custom middlewares."""
from django.http import HttpResponseRedirect
from modoboa.lib.exceptions import ModoboaException
from modoboa.lib.signals import request_accessor
from modoboa.lib.web_utils import (
_render_error, ajax_response, render_to_json_response
)
from . import singleton
class ... | Python | 0 |
70ce7627b11bf804660bc66a60910f66f8f106bd | Reformat code | boundary/metric_delete.py | boundary/metric_delete.py | #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | Python | 0 |
b628e466f86bc27cbe45ec27a02d4774a0efd3bb | Clean out dist and build before building | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:pa... | """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:pa... | Python | 0 |
71b1cfbd375907f19e6f6eb587bd539fbaf3242c | Fix #167: Error when trying to append to sys.path from main sketch file | runtime/src/jycessing/detect_sketch_mode.py | runtime/src/jycessing/detect_sketch_mode.py | import ast
import re
from jycessing import MixedModeError
"""
Determines the sketch mode, namely:
"ACTIVE" if the sketch uses draw() and/or setup() functions;
"STATIC" otherise.
"MIXED" if the user seems to have erroneously both declared a draw()
function and called drawing functions outside draw().
"""
# If you... | import ast
import re
from jycessing import MixedModeError
"""
Determines the sketch mode, namely:
"ACTIVE" if the sketch uses draw() and/or setup() functions;
"STATIC" otherise.
"MIXED" if the user seems to have erroneously both declared a draw()
function and called drawing functions outside draw().
"""
# If you... | Python | 0 |
b80aa5999de7167745243bf9ae4d83b63a4e56c5 | Rename Runner attr `form_document` to `form_controls` which is the proper name. | orbeon_xml_api/runner.py | orbeon_xml_api/runner.py | from builder import Builder
from utils import generate_xml_root
from controls import StringControl, DateControl, TimeControl, DateTimeControl, \
BooleanControl, AnyURIControl, EmailControl, DecimalControl, \
Select1Control, OpenSelect1Control, SelectControl
class Runner:
def __init__(self, xml, builder=... | from builder import Builder
from utils import generate_xml_root
from controls import StringControl, DateControl, TimeControl, DateTimeControl, \
BooleanControl, AnyURIControl, EmailControl, DecimalControl, \
Select1Control, OpenSelect1Control, SelectControl
class Runner:
def __init__(self, xml, builder=... | Python | 0 |
f6cad1777023ceb53db8599bc2e74bf0ab2aa0a7 | Prepare for next dev release | orchestrator/__init__.py | orchestrator/__init__.py | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.2'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| Python | 0 |
569c056e016131ec4325185ee9fe814018d5e1fe | Fix problem on no-longer existing bands that are still as logged in session available | server/bands/__init__.py | server/bands/__init__.py | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... | Python | 0.000001 |
08c25e4ff96765c057397582327a36a6a1d3b7cb | fix caching unicode error | ourcup/util/filecache.py | ourcup/util/filecache.py | import hashlib, os, codecs, logging
'''
Super basic file-based cache (utf-8 friendly). Helpful if you're developing a
webpage scraper and want to be a bit more polite to the server you're scraping
while developing. The idea is that it caches content in files, each named by the
key you pass in (use the md5_key help... | import hashlib, os, codecs, logging
'''
Super basic file-based cache (utf-8 friendly). Helpful if you're developing a
webpage scraper and want to be a bit more polite to the server you're scraping
while developing. The idea is that it caches content in files, each named by the
key you pass in (use the md5_key help... | Python | 0.000002 |
94788d01acb2b44bfdc4e621769e58f9c17b4d69 | Add manifest filename to Application class | progression/__init__.py | progression/__init__.py | from .__version__ import __version__
import os.path
class Metadata(dict):
"""Metadata can be accessed using both dictionary and attribute syntax.
Provides basic valiation of input fields, with different requirements for
the testing and comparison steps.
"""
_compare_requires = []
_testing_req... | from .__version__ import __version__
import os.path
class Metadata(dict):
"""Metadata can be accessed using both dictionary and attribute syntax.
Provides basic valiation of input fields, with different requirements for
the testing and comparison steps.
"""
_compare_requires = []
_testing_req... | Python | 0.000001 |
a3353e1b4c3e181958a877c8e2485c2c7eed4201 | Update pd_utils for python3 | projections/pd_utils.py | projections/pd_utils.py | import numpy.lib
import numpy as np
import pandas as pd
import _pickle as pickle
def save_pandas(fname, data):
'''Save DataFrame or Series
Parameters
----------
fname : str
filename to use
data: Pandas DataFrame or Series
'''
np.save(open(fname, 'wb'), data)
if len(data.shape) ... | import numpy.lib
import numpy as np
import pandas as pd
import _pickle as pickle
def save_pandas(fname, data):
'''Save DataFrame or Series
Parameters
----------
fname : str
filename to use
data: Pandas DataFrame or Series
'''
np.save(open(fname, 'w'), data)
if len(data.shape) =... | Python | 0 |
006eff6a9376c65e0632efe79ec6d39cbc50f80b | remove UI element namespaces | docs/tutorial/tuthello.py | docs/tutorial/tuthello.py | # Licensed CC0 Public Domain: http://creativecommons.org/publicdomain/zero/1.0
# [HelloRapicorn-EXAMPLE]
# Load and import a versioned Rapicorn module into the 'Rapicorn' namespace
import Rapicorn1307 as Rapicorn
# Setup the application object, unsing a unique application name.
app = Rapicorn.app_init ("Hello Rapicorn... | # Licensed CC0 Public Domain: http://creativecommons.org/publicdomain/zero/1.0
# [HelloRapicorn-EXAMPLE]
# Load and import a versioned Rapicorn module into the 'Rapicorn' namespace
import Rapicorn1307 as Rapicorn
# Setup the application object, unsing a unique application name.
app = Rapicorn.app_init ("Hello Rapicorn... | Python | 0.000001 |
8936ba626c4bc3114ecb9d2efc75136f4122e37a | Initialized LSS texture recognizer example | examples/linear_separator/texture_recognizer/Texture.py | examples/linear_separator/texture_recognizer/Texture.py | from classes.solver import LinearSeparator
class Texture:
def __init__(self, neighborhoods, colors, textures=2):
self.dimensions = neighborhoods * (colors * colors) + 1
self.colors = colors
self.neighborhoods = neighborhoods
self.__separator = LinearSeparator(self.dimensions, clas... | from classes.solver import LinearSeparator
class Texture:
def __init__(self, neighborhoods, colors, textures=2):
self.dimensions = neighborhoods * (colors) * (colors) + 1
self.colors = colors
self.neighborhoods = neighborhoods
self.__separator = LinearSeparator(self.dimensions, cl... | Python | 0.999995 |
140adc7a6b1c9888a9a3938653d7fbc19bc60460 | Use a list instead of a combo box to display available nodes. | reconfigure_gui/src/reconfigure_gui/reconfigure_widget.py | reconfigure_gui/src/reconfigure_gui/reconfigure_widget.py | import sys
import QtGui
from QtGui import QWidget, QPushButton, QComboBox, QScrollArea, QTreeWidget, QTreeWidgetItem
from QtCore import QTimer
import dynamic_reconfigure.client
import rosservice
import rospy
from .editors import *
from .groups import *
from .updater import Updater
class ReconfigureWidget(QWidget):
... | import sys
import QtGui
from QtGui import QWidget, QPushButton, QComboBox, QScrollArea
from QtCore import QTimer
import dynamic_reconfigure.client
import rosservice
import rospy
from .editors import *
from .groups import *
from .updater import Updater
class ReconfigureWidget(QWidget):
def __init__(self):
... | Python | 0 |
ec2456eac36a96c9819920bf8b4176e6a37ad9a5 | Rename productclass made during migration | saleor/product/migrations/0020_attribute_data_to_class.py | saleor/product/migrations/0020_attribute_data_to_class.py | from __future__ import unicode_literals
from django.db import migrations, models
def move_data(apps, schema_editor):
Product = apps.get_model('product', 'Product')
ProductClass = apps.get_model('product', 'ProductClass')
for product in Product.objects.all():
attributes = product.attributes.all()... | from __future__ import unicode_literals
from django.db import migrations, models
def move_data(apps, schema_editor):
Product = apps.get_model('product', 'Product')
ProductClass = apps.get_model('product', 'ProductClass')
for product in Product.objects.all():
attributes = product.attributes.all()... | Python | 0 |
f31e8215838e40960abff6c86be8c66cbf113c95 | Make the endpoint return geojson as opposed to wkt geometry | server/rest/twofishes.py | server/rest/twofishes.py | import requests
from shapely.wkt import loads
from shapely.geometry import mapping
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET',... | import requests
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET', (), self.geocode)
self.route('GET', ('autocomplete',), sel... | Python | 0.99978 |
8465b0af6504844e8a7cb7cb35b7a8b20c356696 | fix the channel names | plugins/tay.py | plugins/tay.py | from rtmbot.core import Plugin, Job
import os
import random
bot_id = 'U3MSN806S'
header = '<@{}> '.format(bot_id)
responses = {
'hi': 'Nice to meet you, where you been?',
'who should i vote for?': 'Me, of course',
'who are you': '@swiftonsecurity',
}
directory = os.path.realpath(
os.path.join(os.getc... | from rtmbot.core import Plugin, Job
import os
import random
bot_id = 'U3MSN806S'
header = '<@{}> '.format(bot_id)
responses = {
'hi': 'Nice to meet you, where you been?',
'who should i vote for?': 'Me, of course',
'who are you': '@swiftonsecurity',
}
directory = os.path.realpath(
os.path.join(os.getc... | Python | 0.99939 |
8fb5b379d99d29fdee6fca86d944687268ba8101 | Format currency conversion using embeds. Also include a thousands separator in the value and add an emoji flag. | plugins/web.py | plugins/web.py | """ Plugin for web commands
Commands:
define
"""
import discord
from datetime import datetime
from pcbot import Annotate, utils
import plugins
client = plugins.client # type: discord.Client
# Create exchange rate cache and keep track of when we last reset it
exchange_rate_cache = dict(reset=client.time_starte... | """ Plugin for web commands
Commands:
define
"""
import discord
from datetime import datetime
from pcbot import Annotate, utils
import plugins
client = plugins.client # type: discord.Client
# Create exchange rate cache and keep track of when we last reset it
exchange_rate_cache = dict(reset=client.time_starte... | Python | 0 |
9ece50e71d2c5eab7b97edc5b8bbdfb410ce64bf | edit admin.py | polls/admin.py | polls/admin.py | from django.contrib import admin
from polls.models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'... | from django.contrib import admin
from polls.models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'... | Python | 0 |
5b63950cb3fa018b63ccb0be3faeceef684f9299 | Add persistent storage | ipinfo.py | ipinfo.py | from ipaddress import ip_address, ip_network
import shelve
from ipwhois import IPWhois
ip_whois_shelve_filename = 'ip_whois'
known_networks = shelve.open(ip_whois_shelve_filename)
def updateIpInfo(ip):
info = IPWhois(ip).lookup()
# these two lines might break on some input
net = info['nets'][0]
netwo... | from ipaddress import ip_address, ip_network
from ipwhois import IPWhois
known_networks = {}
def updateIpInfo(ip):
info = IPWhois(ip).lookup()
# these two lines might break on some input
net = info['nets'][0]
networks = net['cidr'].split(', ')
for network in networks:
network = ip_network... | Python | 0.000003 |
8f6c73238b5b52bdd7feb63fc1f1f28ed12e7e3e | Update render method implementation in MultiCurve and MultiSurface classes | geomdl/Multi.py | geomdl/Multi.py | """
.. module:: Multi
:platform: Unix, Windows
:synopsis: Container module for storage and visualization of curves and surfaces
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
from . import warnings
from . import Abstract
from . import utilities
class MultiCurve(Abstract.Multi):
""" Contain... | """
.. module:: Multi
:platform: Unix, Windows
:synopsis: Container module for storage and visualization of curves and surfaces
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
from . import warnings
from . import Abstract
from . import utilities
class MultiCurve(Abstract.Multi):
""" Contain... | Python | 0 |
e0e23391d0ec035926644cfb7d1e7b1f43f35cf7 | Avoid the key error | get_timeline.py | get_timeline.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from configparser import ConfigParser
import datetime
import json
import os
import sys
from requests_oauthlib import OAuth1Session
from logging import FileHandler, Formatter, getLogger, DEBUG
config = ConfigParser()
config.read(os.path.abspath(os.path.dirname(__file__))... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from configparser import ConfigParser
import datetime
import json
import os
import sys
from requests_oauthlib import OAuth1Session
from logging import FileHandler, Formatter, getLogger, DEBUG
config = ConfigParser()
config.read(os.path.abspath(os.path.dirname(__file__))... | Python | 0.999999 |
f63ddd4c4e98322fcff651aefb298f7724dc9bff | Add help text, rename 'history' to graph | basil.py | basil.py | import subprocess
import time
import tempfile
last_watered = 0
COOLDOWN = 60
WATER_MAX_SECS = 60
HELPTEXT = {}
def basilcmd(cmds):
output = subprocess.check_output(['ssh', 'rrpi', './basilbot/cli.py', *cmds], stderr=subprocess.STDOUT)
return output
HELPTEXT['moisture'] = 'Check the instantaneous moisture o... | import subprocess
import time
import tempfile
last_watered = 0
COOLDOWN = 60
def basilcmd(cmds):
output = subprocess.check_output(['ssh', 'rrpi', './basilbot/cli.py', *cmds], stderr=subprocess.STDOUT)
return output
def moisture():
output = basilcmd(['moisture'])
return 'Soil moisture content: ' + ... | Python | 0.999822 |
6c3ba0617575d2d178c2f1a2632cea5f5ba09d5f | Revert "Updated License" | grabLocation.py | grabLocation.py | from geopy.geocoders import GoogleV3
from geopy.exc import GeocoderTimedOut
import time # For rate limiting purposes
# Using Geopy copyright 2006-2016 geopy authors
# Geopy available at https://github.com/geopy/geopy
# This program is copyright 2017 Joseph Johaneman
# And is released under the 3 Clause BSD License... | from geopy.geocoders import GoogleV3
from geopy.exc import GeocoderTimedOut
import time # For rate limiting purposes
# Using Geopy copyright 2006-2016 geopy authors
# Geopy available at https://github.com/geopy/geopy
# This program is copyright 2017 Joseph Johaneman
# And is released under the MIT License
# What ... | Python | 0 |
1cb55e4feec981efdf629b01ed7508f825b6c2c0 | add comment TODO | StockIndicators/StockIndicators.py | StockIndicators/StockIndicators.py | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
#TODO: probar a meter token de seguridad a ver se funciona
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username... | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username": "bob", "user_id": 2}
])
| Python | 0 |
13a5e797bf3c268ae42dda79c75959ca0602096f | Update unit tests script. | unit_test.py | unit_test.py | #!/usr/bin/python3
import glob
import re
import subprocess
import os
import os.path
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's impl... | #!/usr/bin/python3
import glob
import re
import subprocess
import os
import os.path
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's impl... | Python | 0 |
7ccb8d443fe3dda236d05ff4ed13e067a6893872 | create a changeset against local before changing local; we'll use this later | updatecmd.py | updatecmd.py | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import os
import sys
import util
import versions
def doUpdate(repos, db, cfg, pkg, versionStr = None):
cs = None
if not os.path.exists(cfg.root):
util.mkdirChain(cfg.root)
if os.path.exists(pkg):
# there is ... | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import os
import sys
import util
import versions
def doUpdate(repos, db, cfg, pkg, versionStr = None):
cs = None
if not os.path.exists(cfg.root):
util.mkdirChain(cfg.root)
if os.path.exists(pkg):
# there is ... | Python | 0 |
6aea68d6c1de498583c42839a3a31ef25f51e17e | Complete alg_breadth_first_search.py | alg_breadth_first_search.py | alg_breadth_first_search.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def bfs(graph_adj_d, start_vertex):
visit_queue = []
visit_queue.insert(0, start_vertex)
distance_d = {v: np.inf for v in graph_adj_d.keys()}
distance_d[start_vertex] = 0
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bfs():
pass
def main():
# Small word ladder graph.
graph_adj_d = {
'fool': {'cool', 'pool', 'foil', 'foul'},
'foul': {'fool', 'foil'},
'foil': {'fool', 'foul', 'fail'}... | Python | 0.99995 |
649029d2ad04eb5afd618b40ccd62993d69e389f | Complete alg_percentile_selection.py | alg_percentile_selection.py | alg_percentile_selection.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
def select_percentile(ls, k):
"""Kth percentile selection algorithm.
Just select the kth element, without caring about
the relative ordering of the rest of them.
The algorithm per... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def select_percentile(a_list, k):
"""Select list's kth percentile.
Just select the kth element, without caring about
the relative ordering of the rest of them.
"""
pass
def main():
pass
if __na... | Python | 0.998978 |
7de37a5ba8164b757a6a8ed64f80ee379ff7a3ad | fix some bugs | scripts/extract_computer_and_accessories.py | scripts/extract_computer_and_accessories.py | from scripts.rake import *
import json
# get review texts aggregated by asin id
def get_rdd(base, input, num_part):
base_dir = os.path.join(base)
input_path = os.path.join(input)
file_name = os.path.join(base_dir, input_path)
# load data
... | from scripts.rake import *
import json
# get review texts aggregated by asin id
def get_rdd(base, input, num_part):
base_dir = os.path.join(base)
input_path = os.path.join(input)
file_name = os.path.join(base_dir, input_path)
# load data
... | Python | 0.000008 |
ab533cf55e87571e757f545d5eaad6f8f62cc31f | Make worker resource plot responsive | distributed/diagnostics/worker_monitor.py | distributed/diagnostics/worker_monitor.py | from __future__ import print_function, division, absolute_import
from collections import defaultdict
from itertools import chain
from toolz import pluck
from ..utils import ignoring
with ignoring(ImportError):
from bokeh.models import ColumnDataSource, DataRange1d, Range1d
from bokeh.palettes import Spectra... | from __future__ import print_function, division, absolute_import
from collections import defaultdict
from itertools import chain
from toolz import pluck
from ..utils import ignoring
with ignoring(ImportError):
from bokeh.models import ColumnDataSource, DataRange1d, Range1d
from bokeh.palettes import Spectra... | Python | 0.000002 |
b90927f3aa8b3178eabdf75ab68cf11df1c08835 | Resolve #8 and modify output | portscanner.py | portscanner.py | #!/usr/bin/python
import socket
import sys
import os
import argparse
class colors:
HOST='\033[32m'
PORT='\033[36m'
TYPE='\033[33m'
SERVICE='\033[35m'
WARNING='\033[31m'
INFO='\033[34m'
END='\033[0m'
def main():
parser = argparse.ArgumentParser(description = "Test a specified ip/host for open ports.")
mutex ... | #!/usr/bin/python
import socket
import sys
import os
import argparse
def main():
parser = argparse.ArgumentParser(description = "Test a specified ip/host for open ports.")
mutex = parser.add_mutually_exclusive_group(required=True)
parser.add_argument('ip', metavar='IP', help='The ip/host to be scanned for open por... | Python | 0 |
6e65bf0ce5334e2242fee0c36886cfda29a1f4a4 | Make build.py baseimage pulling optional | build.py | build.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: python; -*-
import logging
import subprocess
import sys
import time
import os
from common import get_sys_args, yield_dockerfiles
from common import run_cmd, init_logger
def build_image(repo_path, repo_name):
for dockerfile, image in yield_dockerfiles(rep... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: python; -*-
import logging
import subprocess
import sys
import time
from common import get_sys_args, yield_dockerfiles
from common import run_cmd, init_logger
def build_image(repo_path, repo_name):
for dockerfile, image in yield_dockerfiles(repo_path, re... | Python | 0 |
1aec16ffc5d5781562775de7faa76238d55b91b1 | Improve sound loop set config validation | mpfmc/config_collections/sound_loop_set.py | mpfmc/config_collections/sound_loop_set.py | from typing import TYPE_CHECKING, Union
from mpfmc.core.config_collection import ConfigCollection
from mpfmc.core.audio.audio_exception import AudioException
if TYPE_CHECKING:
from mpfmc.core.mc import MpfMc
class SoundLoopSetCollection(ConfigCollection):
config_section = 'sound_loop_sets'
collection = ... | from typing import TYPE_CHECKING, Union
from mpf.core.randomizer import Randomizer
from mpfmc.core.config_collection import ConfigCollection
from mpfmc.core.audio.audio_exception import AudioException
if TYPE_CHECKING:
from mpfmc.core.mc import MpfMc
class SoundLoopSetCollection(ConfigCollection):
config_se... | Python | 0.000001 |
b68669f07aba05a4e96f900df71d6179382cd6f1 | bump version | build.py | build.py | from pybuilder.core import use_plugin, init, Author, task
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin('copy_resources')
use_plug... | from pybuilder.core import use_plugin, init, Author, task
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin('copy_resources')
use_plug... | Python | 0 |
83b12f568ba8843ac6bff4c5179d8200d88505b0 | Fix an issue where the .VERSION file output from build.py had multiple commit hashes | build.py | build.py | #/*******************************************************************************
# * Copyright (c) 2016 Synopsys, Inc
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribution, and is available ... | #/*******************************************************************************
# * Copyright (c) 2016 Synopsys, Inc
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribution, and is available ... | Python | 0.000021 |
fe55a3e5ba9f4a368d39fcc3316a471df547d714 | Bump version to 0.8.1+dev | h11/_version.py | h11/_version.py | # This file must be kept very simple, because it is consumed from several
# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
# We use a simple scheme:
# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
# where the +dev versions are never released into the wild, they're just what
# we stick into the ... | # This file must be kept very simple, because it is consumed from several
# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
# We use a simple scheme:
# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
# where the +dev versions are never released into the wild, they're just what
# we stick into the ... | Python | 0 |
426d87c4afb4884e0fd9998b67fe6e0e2b2d60c6 | Add single processor code path and refine CLI | aperturesynth/synthesise.py | aperturesynth/synthesise.py | """aperturesynth - a tool for registering and combining series of photographs.
Usage:
aperturesynth [-n] <images>...
Options:
-h --help Show this screen.
--out=OUTPUT Optional output file.
-n Combine images without transforming
"""
import multiprocessing as mp
from skimage imp... | #!/usr/bin/env python
"""aperturesynth - a tool for registering and combining series of photographs.
Usage:
aperturesynth (--out=OUTPUT) <images>...
Options:
-h --help Show this screen.
"""
import multiprocessing as mp
from skimage import io, img_as_ubyte, img_as_float
from docopt import docopt
fro... | Python | 0 |
14753d1d445f876910ae181530082fe7952a9b10 | Add some sanity checks to the search adder, and don't hit renamed docs over and over again. | regscrape/regs_common/commands/add_to_search.py | regscrape/regs_common/commands/add_to_search.py | GEVENT = False
from optparse import OptionParser
arg_parser = OptionParser()
arg_parser.add_option("-a", "--agency", dest="agency", action="store", type="string", default=None, help="Specify an agency to which to limit the dump.")
arg_parser.add_option("-d", "--docket", dest="docket", action="store", type="string", de... | GEVENT = False
from optparse import OptionParser
arg_parser = OptionParser()
arg_parser.add_option("-a", "--agency", dest="agency", action="store", type="string", default=None, help="Specify an agency to which to limit the dump.")
arg_parser.add_option("-d", "--docket", dest="docket", action="store", type="string", de... | Python | 0 |
0e3e9028598c8ebe49c3aec98fbfb584e8f5223b | Check both category_links and resource_link | myuw/management/commands/check_reslinks.py | myuw/management/commands/check_reslinks.py | """
Test all the links in the CSV for non-200 status codes (after redirects).
"""
import logging
import sys
import urllib3
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from myuw.dao.category_links import Res_Links, Resource_Links
from myuw.util.settings impor... | """
Test all the links in the CSV for non-200 status codes (after redirects).
"""
import logging
import sys
import urllib3
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from myuw.dao.category_links import Res_Links
from myuw.util.settings import get_cronjob_re... | Python | 0.000001 |
d242870d99634edc4b077b045fe5489039a3c821 | add shebang to targetselection script | bin/targetselection.py | bin/targetselection.py | #!/usr/bin/env python
import numpy
from desitarget.io import read_tractor, write_targets
from desitarget.cuts import LRG, ELG, BGS, QSO
from desitarget import targetmask
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type fo... | import numpy
from desitarget.io import read_tractor, write_targets
from desitarget.cuts import LRG, ELG, BGS, QSO
from desitarget import targetmask
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files")
ap.add_ar... | Python | 0 |
22a76a55c373af8f64717b10542b7230e63e9583 | update person caches to 1hr | sis_provisioner/cache.py | sis_provisioner/cache.py | from restclients.cache_implementation import TimedCache
import re
class RestClientsCache(TimedCache):
""" A custom cache implementation for Canvas """
url_policies = {}
url_policies["sws"] = (
(re.compile(r"^/student/v5/term/"), 60 * 60 * 10),
(re.compile(r"^/student/v5/course/"), 60 * 5)... | from restclients.cache_implementation import TimedCache
import re
class RestClientsCache(TimedCache):
""" A custom cache implementation for Canvas """
url_policies = {}
url_policies["sws"] = (
(re.compile(r"^/student/v5/term/"), 60 * 60 * 10),
(re.compile(r"^/student/v5/course/"), 60 * 5)... | Python | 0 |
909b14f4d4b82c72e8f3987c1ef82cc075520cb1 | add @ | botpi.py | botpi.py | import re
re_pi = re.compile(r'(?:^|\s)(((P|p)i)|(π)|(3(\.|,)14\d*))').search
message = "@{name}, eigentlich is π ja 3.1415926535897932384626433832795028841971693\
9937510582097494... aber rechne lieber mit 3, das ist wesentlich einfacher!"
def check_pi(bot_stuff):
match = re_pi(bot_stuff['message'])
print(... | import re
re_pi = re.compile(r'(?:^|\s)(((P|p)i)|(π)|(3(\.|,)14\d*))').search
message = "{name}, eigentlich is π ja 3.1415926535897932384626433832795028841971693\
9937510582097494... aber rechne lieber mit 3, das ist wesentlich einfacher!"
def check_pi(bot_stuff):
match = re_pi(bot_stuff['message'])
print(m... | Python | 0 |
d43fecb6f645dabf1740cd42aaf25191353a1b77 | add curriculum to cache policy | sis_provisioner/cache.py | sis_provisioner/cache.py | from django.conf import settings
from memcached_clients import RestclientPymemcacheClient
from uw_kws import ENCRYPTION_KEY_URL, ENCRYPTION_CURRENT_KEY_URL
import re
ONE_MINUTE = 60
ONE_HOUR = 60 * 60
ONE_DAY = 60 * 60 * 24
ONE_WEEK = 60 * 60 * 24 * 7
ONE_MONTH = 60 * 60 * 24 * 30
NONPERSONAL_NETID_EXCEPTION_GROUP = g... | from django.conf import settings
from memcached_clients import RestclientPymemcacheClient
from uw_kws import ENCRYPTION_KEY_URL, ENCRYPTION_CURRENT_KEY_URL
import re
ONE_MINUTE = 60
ONE_HOUR = 60 * 60
ONE_DAY = 60 * 60 * 24
ONE_WEEK = 60 * 60 * 24 * 7
ONE_MONTH = 60 * 60 * 24 * 30
NONPERSONAL_NETID_EXCEPTION_GROUP = g... | Python | 0 |
9bb76df67c436d091d85d75c6968ede89d9194b7 | add testing framework | statistics/test.py | statistics/test.py | import unittest
from numberOfPublicMethods import *
class Tests(unittest.TestCase):
@staticmethod
def listOfOCClasses():
return [
ObjectiveCClass(publicMethods=4, className="TestClass4"),
ObjectiveCClass(publicMethods=5, className="TestClass5"),
Objectiv... | from numberOfPublicMethods import *
def headersIsClass():
return headers()[0] == "class.h"
def propertiesIs4():
return parseFile("class.h") == ObjectiveCClass(publicMethods=4, className="TestClass")
if __name__ == "__main__":
print(headersIsClass())
print(propertiesIs4())
print(calculateAveragePu... | Python | 0.000001 |
b689cadb696ce07372588b368a6d3709f636ca8a | Edit descriptions | manage.py | manage.py | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db, populate_db()
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '-... | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db, populate_db()
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '-... | Python | 0.000001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.