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 |
|---|---|---|---|---|---|---|---|---|
a8fcb89fecac12cec656ab240799161c3103eb47 | check shapes of train images and labels | autodrive/tensor_flow_practice,autodrive/tensor_flow_practice | download_mnist.py | download_mnist.py | # from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.examples.tutorials.mnist import input_data
def load_data():
global mnist
success = False
while not success:
try:
print("trying download")
mnist = input_data.read_data_sets("MNIST_data/", one_hot=T... | # from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.examples.tutorials.mnist import input_data
def load_data():
global mnist
success = False
while not success:
try:
print("trying download")
mnist = input_data.read_data_sets("MNIST_data/", one_hot=T... | apache-2.0 | Python |
837ff37d08f1a9f8275e2666b8ddeba1a2fa3147 | Add reptiles bucket to test bearer tokens | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | backdrop/write/config/test.py | backdrop/write/config/test.py | DATABASE_NAME = "backdrop_test"
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
LOG_LEVEL = "ERROR"
TOKENS = {
'_bucket': '_bucket-bearer-token',
'_status': '_status-bearer-token', # not expected to be here
'data-with-times': 'data-with-times-bearer-token',
'flavour_events': 'flavour_events-bearer-token',
... | DATABASE_NAME = "backdrop_test"
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
LOG_LEVEL = "ERROR"
TOKENS = {
'_bucket': '_bucket-bearer-token',
'_status': '_status-bearer-token', # not expected to be here
'data-with-times': 'data-with-times-bearer-token',
'flavour_events': 'flavour_events-bearer-token',
... | mit | Python |
005483f6e7e65e45964cd355d205eb7abac60e6e | Update eidos_api.py to be compatible with Python 3 | johnbachman/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,sorgerlab/indra | indra/sources/eidos/eidos_api.py | indra/sources/eidos/eidos_api.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str, bytes
from past.builtins import basestring
import json
from .processor import EidosProcessor
def process_json_file(file_name):
"""Return an EidosProcessor by processing the given Eidos json file.
The outpu... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str, bytes
import json
from .processor import EidosProcessor
def process_json_file(file_name):
"""Return an EidosProcessor by processing the given Eidos json file.
The output from the Eidos reader is in json fo... | bsd-2-clause | Python |
81983e8ae745177f1589cae76cd3eb9195c7cb49 | use python3 for shebang | pombredanne/bitsets,xflr6/bitsets | visualize-examples.py | visualize-examples.py | #!/usr/bin/env python3
# visualize-examples.py
import bitsets
import bitsets.visualize
ARGS = {'directory': 'visualize-output', 'format': 'pdf'}
Four = bitsets.bitset('Four', (1, 2, 3, 4))
bitsets.visualize.bitset(Four, render=True, **ARGS)
bitsets.visualize.bitset(Four, member_label=True, render=True, **ARGS)
Si... | #!/usr/bin/env python
# visualize-examples.py
import bitsets
import bitsets.visualize
ARGS = {'directory': 'visualize-output', 'format': 'pdf'}
Four = bitsets.bitset('Four', (1, 2, 3, 4))
bitsets.visualize.bitset(Four, render=True, **ARGS)
bitsets.visualize.bitset(Four, member_label=True, render=True, **ARGS)
Six... | mit | Python |
34a3bf209c1bb09e2057eb4dd91ef426e3107c11 | Monitor temperature script as used for heating measurement | beercanlah/ardumashtun,beercanlah/ardumashtun | monitor_temperature.py | monitor_temperature.py | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
csv_writer.writerow(["Time [s]", "Temperature [C]"])
kettle = bre... | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
kettle = brewkettle.BrewKettle()
kettle.turn_pump_on()
start = t... | mit | Python |
c45ffd490df434fff9f691ee616a17ddf02f74db | Add option to ignore character casing | rolfmichelsen/Just4Fun | crypto/frequency-analysis.py | crypto/frequency-analysis.py | #!/usr/bin/env python3
"""
Performs simple frequency analysis of input text.
"""
import sys
from argparse import ArgumentParser
def frequencyAnalysis(text, alpha=False):
"""
Return a frequency analysis of characters in the input text. Returns a map where the key is the character
and the value is the o... | #!/usr/bin/env python3
"""
Performs simple frequency analysis of input text.
"""
import sys
from argparse import ArgumentParser
def frequencyAnalysis(text, alpha=False):
"""
Return a frequency analysis of characters in the input text. Returns a map where the key is the character
and the value is the o... | bsd-3-clause | Python |
128593bcf58bd4c66fe14e05205c3458ccd290cd | Add search to autosummary. | SunDwarf/curious | curious/dataclasses/__init__.py | curious/dataclasses/__init__.py | """
Classes that wrap objects returned by Discord.
A **dataclass** is a class that contains data and allows the user to edit classes. These classes are stateful,
as in they store state which allows the user to edit them as appropriate.
.. currentmodule:: curious.dataclasses
.. autosummary::
:toctree: dataclasse... | """
Classes that wrap objects returned by Discord.
A **dataclass** is a class that contains data and allows the user to edit classes. These classes are stateful,
as in they store state which allows the user to edit them as appropriate.
.. currentmodule:: curious.dataclasses
.. autosummary::
:toctree: dataclasse... | mit | Python |
ec9d8910616b5d3807b86209f9a50a88db8a4ecf | improve flakey test test_mark_success_no_kill (#6959) | owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow | tests/dags/test_mark_success.py | tests/dags/test_mark_success.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | apache-2.0 | Python |
8cef7892fa2bf2ef1b2b4fe86b675d777925706a | Remove unneeded paranthesis in the url definition | GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng | moocng/courses/urls.py | moocng/courses/urls.py | # Copyright 2012 Rooter Analysis S.L.
#
# 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 w... | # Copyright 2012 Rooter Analysis S.L.
#
# 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 w... | apache-2.0 | Python |
60c0f2b74d7459b955da28ff16f67db1e81f5789 | Fix a issue when a provider has not been added | nimiq/moogle-project | moogle/search/views.py | moogle/search/views.py | # Stdlib imports
# E.g.: from math import sqrt
# Core Django imports
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
# Third-party app imports
# E.g.: from django_extensions.db.models import TimeStampedModel
# Imports from local apps
from tokens.models import B... | # Stdlib imports
# E.g.: from math import sqrt
# Core Django imports
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
# Third-party app imports
# E.g.: from django_extensions.db.models import TimeStampedModel
# Imports from local apps
from tokens.models import B... | apache-2.0 | Python |
c2b1870f5253b9b101c345153addb72f6c77c13d | bump version: 2.1.0 | oberstet/txaio,crossbario/txaio,crossbario/txaio,tavendo/txaio,oberstet/txaio,meejah/txaio | txaio/_version.py | txaio/_version.py | __version__ = u'2.1.0'
| __version__ = u'2.0.4'
| mit | Python |
d93cc1b44dcd35255cd95e848b7f99ac314a8288 | Remove unnecessary array initialzation | jcass77/mopidy,adamcik/mopidy,kingosticks/mopidy,adamcik/mopidy,mopidy/mopidy,jodal/mopidy,jodal/mopidy,kingosticks/mopidy,jodal/mopidy,mopidy/mopidy,adamcik/mopidy,kingosticks/mopidy,jcass77/mopidy,jcass77/mopidy,mopidy/mopidy | mopidy/core/history.py | mopidy/core/history.py | from __future__ import absolute_import, unicode_literals
import copy
import logging
import time
from mopidy import models
from mopidy.internal.models import HistoryState, HistoryTrack
logger = logging.getLogger(__name__)
class HistoryController(object):
pykka_traversable = True
def __init__(self):
... | from __future__ import absolute_import, unicode_literals
import copy
import logging
import time
from mopidy import models
from mopidy.internal.models import HistoryState, HistoryTrack
logger = logging.getLogger(__name__)
class HistoryController(object):
pykka_traversable = True
def __init__(self):
... | apache-2.0 | Python |
2f04e8dfcf6790dca13dd82df0a832532487c3b2 | move icds reports task to 9:30pm IST | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | custom/icds_reports/tasks.py | custom/icds_reports/tasks.py | import logging
import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
celery_task_logger = logging.getLogger('celery.task')
@periodic_task(run_every=crontab(minute=0, hour=16), acks_late=True, queue='background_queue')... | import logging
import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connections
celery_task_logger = logging.getLogger('celery.task')
@periodic_task(run_every=crontab(minute=0, hour=12), acks_late=True, queue='background_queue')... | bsd-3-clause | Python |
ab8cf90d2d6bead71094676e5efdd39eda71548d | Fix #2 again | NickVolynkin/SmokeDetector,Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector,ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,ArtOfCode-/SmokeDetector | findspam.py | findspam.py | import re
class FindSpam:
rules = [
{'regex': "\\b(baba(ji)?|vashikaran|fashion|here is|porn)\\b", 'all': True,
'sites': [], 'reason': "Bad keyword detected"},
{'regex': "\\+\\d{10}|\\+?\\d{2}\\s?\\d{8}", 'all': True,
'sites': ["patents.stackexchange.com"], 'reason': "Phone number detected"},
{'re... | import re
class FindSpam:
rules = [
{'regex': "\\b(baba(ji)?|vashikaran|fashion|here is|porn)\\b", 'all': True,
'sites': [], 'reason': "Bad keyword detected"},
{'regex': "\\+\\d{10}|\\+?\\d{2}\\s?\\d{8}", 'all': True,
'sites': ["patents.stackexchange.com"], 'reason': "Phone number detected"},
{'re... | apache-2.0 | Python |
b355a78801d056bde9696c4b787b369dc8c8414c | remove voice related stuff | sunlightlabs/calloncongress | calloncongress/web.py | calloncongress/web.py | # This Python file uses the following encoding: utf-8
from flask import Blueprint, render_template
web = Blueprint('web', __name__, template_folder='templates')
@web.route('/')
def index():
return render_template('index.html')
| # This Python file uses the following encoding: utf-8
from flask import Blueprint, render_template, request
from twilio import twiml
from calloncongress.utils import twilioify
web = Blueprint('web', __name__, template_folder='templates')
@web.route('/')
def index():
return render_template('index.html')
@web.r... | bsd-3-clause | Python |
d3d05784c77c3f76157934e994c9e717082e4a2d | Refactor land forms (ref #141) | johan--/Geotrek,mabhub/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek,johan--/Geotrek,m... | caminae/land/forms.py | caminae/land/forms.py | from caminae.core.forms import TopologyMixinForm
from .models import (PhysicalEdge, LandEdge, CompetenceEdge, WorkManagementEdge,
SignageManagementEdge)
class PhysicalEdgeForm(TopologyMixinForm):
modelfields = ('physical_type',)
class Meta(TopologyMixinForm.Meta):
model = Physica... | from caminae.core.forms import TopologyMixinForm
from .models import (PhysicalEdge, LandEdge, CompetenceEdge, WorkManagementEdge,
SignageManagementEdge)
class PhysicalEdgeForm(TopologyMixinForm):
modelfields = (
'physical_type',
)
geomfields = ('geom', )
c... | bsd-2-clause | Python |
a4aa2dc8685417b4ad06ee439db34a663f8f1cff | Correct time complexity | bowen0701/algorithms_data_structures | lc720_longest_word_in_dictionary.py | lc720_longest_word_in_dictionary.py | """Leetcode 720. Longest Word in Dictionary
Easy
URL: https://leetcode.com/problems/longest-word-in-dictionary/
Given a list of strings words representing an English Dictionary,
find the longest word in words that can be built one character at a time by
other words in words. If there is more than one possible answe... | """Leetcode 720. Longest Word in Dictionary
Easy
URL: https://leetcode.com/problems/longest-word-in-dictionary/
Given a list of strings words representing an English Dictionary,
find the longest word in words that can be built one character at a time by
other words in words. If there is more than one possible answe... | bsd-2-clause | Python |
f748ed437bb37e10433d0ca1e695122b2c799a15 | Use simple_tag instead of assignment_tag. | pydata/conf_site,pydata/conf_site,pydata/conf_site | symposion/reviews/templatetags/review_tags.py | symposion/reviews/templatetags/review_tags.py | from django import template
from symposion.reviews.models import ReviewAssignment
register = template.Library()
@register.simple_tag(takes_context=True)
def review_assignments(context):
request = context["request"]
assignments = ReviewAssignment.objects.filter(user=request.user)
return assignments
| from django import template
from symposion.reviews.models import ReviewAssignment
register = template.Library()
@register.assignment_tag(takes_context=True)
def review_assignments(context):
request = context["request"]
assignments = ReviewAssignment.objects.filter(user=request.user)
return assignments
| mit | Python |
38233bf808dbab66ff1e5de774cf45ff66698301 | Use pickle to save output | Eigenstate/msmbuilder,rmcgibbo/msmbuilder,brookehus/msmbuilder,rmcgibbo/msmbuilder,mpharrigan/mixtape,msmbuilder/msmbuilder,mpharrigan/mixtape,rafwiewiora/msmbuilder,peastman/msmbuilder,dotsdl/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,msultan/msmbuilder,dotsdl/msmbuilder,rafwiewiora/msmbuilder,msmbuilder/msm... | msmbuilder/utils/io.py | msmbuilder/utils/io.py | from __future__ import print_function, division, absolute_import
import contextlib
import numpy as np
import warnings
import pickle
from sklearn.externals.joblib import load as jl_load
__all__ = ['printoptions', 'verbosedump', 'verboseload', 'dump', 'load']
@contextlib.contextmanager
def printoptions(*args, **kwargs... | from __future__ import print_function, division, absolute_import
import contextlib
import numpy as np
from sklearn.externals.joblib import load
from sklearn.externals.joblib import dump as _dump
__all__ = ['printoptions', 'verbosedump', 'verboseload', 'dump', 'load']
@contextlib.contextmanager
def printoptions(*args... | lgpl-2.1 | Python |
c187cb4cf32f1281b6f86b8aa5b5c7cf2ad3c18a | update cefpython: block context-menu | allestuetsmerweh/garden.cefpython,allestuetsmerweh/garden.cefpython | cefbrowser/version.py | cefbrowser/version.py | # Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '0.5.5'
| # Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '0.5.4'
| mit | Python |
5cac65b5dd55af1433ea70bc8c6a2e426895d33a | Add tools to create XML files from a list of files in a directory with sidecars (.info files) alongside. | burnpanck/traits,burnpanck/traits | enthought/util/updates/tools.py | enthought/util/updates/tools.py | """ A collection of command-line tools for building encoded update.xml
files.
"""
#Requires Python 2.6 (for format string notation)
import os
import re
import md5
_version_in_name = re.compile("(\S*)[-](\d+\.\d+\.*\d*)\S*")
def _get_name(filename):
match = _version_in_name.search(filename)
if match is None:... | """ A collection of command-line tools for building encoded update.xml
files.
"""
class InfoFile:
update_file = ""
version = None
checksum = None
# A multi-line HTML document describing the changes between
# this version and the previous version
description = ""
@classmethod
def from... | bsd-3-clause | Python |
d5aeae9d4892e073ac4d2367ac6b14954148cfb1 | fix import error for the https_x509_bundle example | espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf | examples/protocols/https_x509_bundle/example_test.py | examples/protocols/https_x509_bundle/example_test.py | import os
import re
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag="Example_WIFI", ignore=True)
def test_examples_protocol_https_x509_bundle(env, extra_data):
"""
steps: |
1. join AP
2. connect to multiple URLs
3. send http request
"""
dut1 = env.get_dut("https_x509_bundle", "exa... | import re
import os
import sys
try:
import IDF
except ImportError:
# this is a test case write with tiny-test-fw.
# to run test cases outside tiny-test-fw,
# we need to set environment variable `TEST_FW_PATH`,
# then get and insert `TEST_FW_PATH` to sys path before import FW module
test_fw_path... | apache-2.0 | Python |
46399d328cbf35547b3d7bc02a70ed21a5995f26 | Fix OS path | andreineustroev/zabbix-email-extra | zbx_sender.py | zbx_sender.py | # -*- coding: utf-8 -*-
import smtplib
import os
from jinja2 import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class SendEmail(object):
"""docstring for SendEmail"""
def __init__(self):
super(SendEmail, self).__init__()
self.mail_from = 'zabbix@zabbix'
self.m... | # -*- coding: utf-8 -*-
import smtplib
from jinja2 import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class SendEmail(object):
"""docstring for SendEmail"""
def __init__(self):
super(SendEmail, self).__init__()
self.mail_from = 'zabbix@zabbix'
self.mail_user =... | mit | Python |
2a8042ab5e1a96f143eab57b1a8def6179f93a17 | Update reset_account.py | googlecodelabs/gcp-marketplace-integrated-saas,googlecodelabs/gcp-marketplace-integrated-saas | tools/reset_account.py | tools/reset_account.py | # Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | # Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | apache-2.0 | Python |
b934fc1e06ab1f34a91aa8996ca7b22052592db3 | Bump version | Floobits/floobits-emacs | floobits.py | floobits.py | #!/usr/bin/env python
# coding: utf-8
import os
import sys
from floo import emacs_handler
from floo.common import migrations
from floo.common import reactor
from floo.common import utils
from floo.common import shared as G
def cb(port):
print('Now listening on %s' % port)
sys.stdout.flush()
def main():
... | #!/usr/bin/env python
# coding: utf-8
import os
import sys
from floo import emacs_handler
from floo.common import migrations
from floo.common import reactor
from floo.common import utils
from floo.common import shared as G
def cb(port):
print('Now listening on %s' % port)
sys.stdout.flush()
def main():
... | apache-2.0 | Python |
bba5ea4fd90d46057dc61fade9770d4e5a058384 | Add simple validation mixin | marcosgabarda/django-belt | belt/rest_framework/mixins.py | belt/rest_framework/mixins.py | from rest_framework.serializers import Serializer
from django.db.models import QuerySet
from rest_framework.response import Response
class ActionSerializersMixin:
"""
Mixin for ViewSets that allows to have a dict with a serializer for
each action.
"""
action_serializers = {}
def get_serializ... | from rest_framework.serializers import Serializer
from django.db.models import QuerySet
from rest_framework.response import Response
class ActionSerializersMixin:
"""
Mixin for ViewSets that allows to have a dict with a serializer for
each action.
"""
action_serializers = {}
def get_serializ... | mit | Python |
d5baa4e124de66d045d5305eb12c09b92c919352 | Update question4.py | pythonzhichan/DailyQuestion,pythonzhichan/DailyQuestion | chengjun/question4.py | chengjun/question4.py | import math
def fibo(index):
if index >2:
return fibo(index-1)+fibo(index-2)
elif index ==2:
return 1
elif index ==1:
return 0
if __name__=="__main__":
temp = int(input('please input a num(num>2):'))
print fibo(index)
| import math
| mit | Python |
eff01e031e7087d7957eab5c5f4df2e3c63f8a5f | Fix typo in comment. | aarpon/obit_microscopy_core_technology,aarpon/obit_microscopy_core_technology,aarpon/obit_microscopy_core_technology | core-plugins/microscopy/1/dss/drop-boxes/MicroscopyDropbox/MicroscopyDropbox.py | core-plugins/microscopy/1/dss/drop-boxes/MicroscopyDropbox/MicroscopyDropbox.py | # -*- coding: utf-8 -*-
"""
@author: Aaron Ponti
"""
import os
import logging
from Processor import Processor
def process(transaction):
"""Dropbox entry point.
@param transaction, the transaction object
"""
# Get path to containing folder
# __file__ does not work (reliably) in Jython
dbPa... | # -*- coding: utf-8 -*-
"""
@author: Aaron Ponti
"""
import os
import logging
from Processor import Processor
def process(transaction):
"""Dropbox entry point.
@param transaction, the transaction object
"""
# Get path to containing folder
# __file__ does not work (reliably) in Jython
dbPa... | apache-2.0 | Python |
c9e42d2dfc2f3780c2d284a2c0622f1e25040293 | Test HeaderRegexp against re.Pattern objects. | sanjioh/django-header-filter | tests/test_matcher_header_re.py | tests/test_matcher_header_re.py | import re
from header_filter.matchers import HeaderRegexp
def test_header_name_and_value_match_re_pattern(rf):
matcher = HeaderRegexp(r'^HTTP_X_A.*$', r'^val_.$')
request = rf.get('/', **{'HTTP_X_A_XYZ': 'val_x'})
assert matcher.match(request) is True
def test_header_name_and_value_match_re_object(rf):... | from header_filter.matchers import HeaderRegexp
def test_header_re_name_and_value_match(rf):
matcher = HeaderRegexp(r'^HTTP_X_A.*$', r'^val_.$')
request = rf.get('/', **{'HTTP_X_A_XYZ': 'val_x'})
assert matcher.match(request) is True
def test_header_re_name_doesnt_match(rf):
matcher = HeaderRegexp(r... | mit | Python |
e5b45060d28371aac1b7abd16d4a977e9d2f2403 | Update __version__.py | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | mythril/__version__.py | mythril/__version__.py | """This file contains the current Mythril version.
This file is suitable for sourcing inside POSIX shell, e.g. bash as well
as for importing into Python.
"""
__version__ = "v0.21.3"
| """This file contains the current Mythril version.
This file is suitable for sourcing inside POSIX shell, e.g. bash as well
as for importing into Python.
"""
__version__ = "v0.21.2"
| mit | Python |
02e017a2a38a73f9a20ec0fab1ae7a9b9ff3cc1d | make the template.py generate the MakeFile | hwchiu/USACO,hwchiu/USACO,hwchiu/USACO | template.py | template.py | #!/usr/local/bin/python
import sys
import os
if len(sys.argv) <=2:
print "Usage: DirectoryName progName"
sys.exit(0)
#Create directory
newpath = r'src/'+sys.argv[1]
if not os.path.exists(newpath):
os.makedirs(newpath)
#Create c++ file
cppFile = open(newpath+"/"+sys.argv[2]+".cpp",'w')
content="\
/*\n\
ID: hwchiu1\... | #!/usr/local/bin/python
import sys
import os
if len(sys.argv) <=2:
print "Usage: DirectoryName progName"
sys.exit(0)
#Create directory
newpath = r'src/'+sys.argv[1]
if not os.path.exists(newpath):
os.makedirs(newpath)
#Create c++ file
cppFile = open(newpath+"/"+sys.argv[2]+".cpp",'w')
content="\
/*\n\
ID: hwchiu1\... | apache-2.0 | Python |
ed0ff5ce38d278d668767393fb5582b1f8b9e73f | Allow multirecord cancelling and fix tests. | open-synergy/event,open-synergy/event | event_registration_cancel_reason/wizard/event_registration_cancel_log_reason.py | event_registration_cancel_reason/wizard/event_registration_cancel_log_reason.py | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L.
# © 2016 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, fields, models
class EventRegistrationCancelLogReason(models.TransientModel):
_name = 'event.registration.canc... | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L.
# © 2016 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, fields, models
class EventRegistrationCancelLogReason(models.TransientModel):
_name = 'event.registration.canc... | agpl-3.0 | Python |
d91045b84bf48583c896ee4403f863b36a689837 | Fix code in `filters/publisher_columns_filter.py` to allow it to work for only one article in the input bib file | ctsit/vivo-pump,mconlon17/vivo-pump,ctsit/vivo-pump | uf_examples/publications/filters/publisher_columns_filter.py | uf_examples/publications/filters/publisher_columns_filter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
publisher_columns_filter.py -- add needed columns, remove unused columns
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2015 (c) Michael Conlon"
__license__ = "New BSD License"
__version__ = "0.01"
from utils import print_err
from vivopump import read_c... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
publisher_columns_filter.py -- add needed columns, remove unused columns
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2015 (c) Michael Conlon"
__license__ = "New BSD License"
__version__ = "0.01"
from vivopump import read_csv_fp, write_csv_fp, improve... | bsd-2-clause | Python |
a4e6c74e68ed2ccc75b482b8b0f126dca306dc8f | Update admin_probe.py | mit-ll/LL-Smartcard,mit-ll/LL-Smartcard | examples/fuzzing/admin_probe.py | examples/fuzzing/admin_probe.py | """
Copyright 2015, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
SPDX-License-Identifier: BSD-3-Clause
This is just a simple program to test all instructions in a given class
"""
# Navtive
import logging
import optparse
# LL Smartcard ... | """
This is just a simple program to test all instructions in a given class
"""
# Navtive
import logging
import optparse
# LL Smartcard
import llsmartcard.apdu as APDU
from llsmartcard.card import SmartCard, VisaCard, CAC
# Globals
log_level = logging.ERROR
def process_card(connection, options):
global log_... | bsd-3-clause | Python |
e6a3c6e7f2372a817bac68bc075645f863856665 | Update minimum import version | pybel/pybel,pybel/pybel,pybel/pybel | src/pybel/config.py | src/pybel/config.py | # -*- coding: utf-8 -*-
"""Connection configuration for PyBEL."""
import configparser
import json
import logging
import os
from .version import VERSION
__all__ = [
'config',
'connection',
'PYBEL_MINIMUM_IMPORT_VERSION',
]
logger = logging.getLogger(__name__)
#: The last PyBEL version where the graph d... | # -*- coding: utf-8 -*-
"""Connection configuration for PyBEL."""
import configparser
import json
import logging
import os
from .version import VERSION
__all__ = [
'config',
'connection',
'PYBEL_MINIMUM_IMPORT_VERSION',
]
logger = logging.getLogger(__name__)
#: The last PyBEL version where the graph d... | mit | Python |
8e93c49fd9237bd841b7dc02dda9f1ba5a930ea1 | Fix list_display_links setup error | openjck/distribution-viewer,openjck/distribution-viewer,openjck/distribution-viewer,openjck/distribution-viewer | distributionviewer/api/admin.py | distributionviewer/api/admin.py | from django.conf.urls import url
from django.contrib import admin
from django.db import models
from django.forms.widgets import Textarea
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from .forms import CSVForm
class MetricAdmin(admin.ModelAdmin):
list_display = ['id'... | from django.conf.urls import url
from django.contrib import admin
from django.db import models
from django.forms.widgets import Textarea
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from .forms import CSVForm
class MetricAdmin(admin.ModelAdmin):
list_display = ['id'... | mpl-2.0 | Python |
99433fb163820c88eb98d0156c2e4e5927fef898 | undo bad optimisation | dneiter/exabgp,benagricola/exabgp,lochiiconnectivity/exabgp,PowerDNS/exabgp,chrisy/exabgp,benagricola/exabgp,dneiter/exabgp,lochiiconnectivity/exabgp,PowerDNS/exabgp,earies/exabgp,blablacar/exabgp,dneiter/exabgp,earies/exabgp,blablacar/exabgp,blablacar/exabgp,chrisy/exabgp,fugitifduck/exabgp,benagricola/exabgp,PowerDNS... | lib/bgp/message/update/route.py | lib/bgp/message/update/route.py | #!/usr/bin/env python
# encoding: utf-8
"""
route.py
Created by Thomas Mangin on 2010-01-16.
Copyright (c) 2010-2011 Exa Networks. All rights reserved.
"""
from bgp.structure.address import Address
from bgp.message.update.attributes import Attributes
# This class must be separated from the wire representation of a R... | #!/usr/bin/env python
# encoding: utf-8
"""
route.py
Created by Thomas Mangin on 2010-01-16.
Copyright (c) 2010-2011 Exa Networks. All rights reserved.
"""
from bgp.structure.address import Address
from bgp.message.update.attributes import Attributes
# This class must be separated from the wire representation of a R... | bsd-3-clause | Python |
312a36da46a3ce3e6932fd227ed374a3c6fa987d | use execfile instead of import | andyshinn/dx-toolkit,olegnev/dx-toolkit,olegnev/dx-toolkit,dnanexus/dx-toolkit,andyshinn/dx-toolkit,dnanexus/dx-toolkit,johnwallace123/dx-toolkit,jhuttner/dx-toolkit,jhuttner/dx-toolkit,andyshinn/dx-toolkit,dnanexus/dx-toolkit,olegnev/dx-toolkit,dnanexus/dx-toolkit,johnwallace123/dx-toolkit,andyshinn/dx-toolkit,olegnev... | src/python/setup.py | src/python/setup.py | #!/usr/bin/env python
import os, sys, glob
from setuptools import setup, find_packages
if sys.version_info < (2, 7):
raise Exception("dxpy requires Python >= 2.7")
# Don't import, but use execfile.
# Importing would trigger interpretation of the dxpy entry point, which can fail if deps are not installed.
execfil... | #!/usr/bin/env python
import os, sys, glob
from setuptools import setup, find_packages
if sys.version_info < (2, 7):
raise Exception("dxpy requires Python >= 2.7")
from dxpy.toolkit_version import version
# Grab all the scripts from dxpy/scripts and install them without their .py extension.
# Replace underscore... | apache-2.0 | Python |
9cecf92b30fe7626dbdb7069298e03b9606492d9 | Add placeholder for fill_missing_paragraph_document_scores | JungeAlexander/cocoscore | cocoscore/tools/data_tools.py | cocoscore/tools/data_tools.py | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False,
allow_missing_text=False):
"""
Load a dataset as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort... | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False,
allow_missing_text=False):
"""
Load a dataset as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort... | mit | Python |
6a04a0adc0deeb106d6c654f224d536e614f5598 | Adjust placement of lines | hunkim/word-rnn-tensorflow | sample.py | sample.py | from __future__ import print_function
import numpy as np
import tensorflow as tf
import argparse
import time
import os
from six.moves import cPickle
from utils import TextLoader
from model import Model
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--save_dir', type=str, default='save',
... | from __future__ import print_function
import numpy as np
import tensorflow as tf
import argparse
import time
import os
from six.moves import cPickle
from utils import TextLoader
from model import Model
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--save_dir', type=str, default='save',
... | mit | Python |
f3e0ddced821f20bdf599675154b9d8e90a286b0 | add post_source column | RyanSquared/blag,RyanSquared/blag,ChickenNuggers/blag,RyanSquared/blag,ChickenNuggers/blag,RyanSquared/blag,ChickenNuggers/blag | lib/blag/__init__.py | lib/blag/__init__.py | from flask import Flask
import sqlite3
db = sqlite3.connect('blog.db')
db_cursor = db.cursor()
db_cursor.execute("""CREATE TABLE IF NOT EXISTS Posts (
eid INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
post TEXT NOT NULL,
post_source TEXT NOT NULL
)""")
db_cursor.execute("""CREATE TABLE IF NOT... | from flask import Flask
import sqlite3
db = sqlite3.connect('blog.db')
db_cursor = db.cursor()
db_cursor.execute("""CREATE TABLE IF NOT EXISTS Posts (
eid INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
post TEXT NOT NULL
)""")
db_cursor.execute("""CREATE TABLE IF NOT EXISTS About (
name TEXT N... | mit | Python |
94bb21d804ec4400d7cb402b042afb806c9982c4 | Fix quotes | it-projects-llc/website-addons,it-projects-llc/website-addons,it-projects-llc/website-addons | website_sale_buy_now/__openerp__.py | website_sale_buy_now/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "E-commerce \"Buy Now\"",
'summary': "Quick checkout to buy product",
'author': 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category': 'Website',
'images':['images/buy_now.png'],
'website': 'https://twitter.com/yelizariev',
'version': '1.0.0... | # -*- coding: utf-8 -*-
{
'name': "E-commerce "Buy Now"",
'summary': "Quick checkout to buy product",
'author': 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category': 'Website',
'images':['images/buy_now.png'],
'website': 'https://twitter.com/yelizariev',
'version': '1.0.0',... | mit | Python |
911d0554532253df62809025ef3e0332cf9314e7 | add some more file based test cases for api.loads with data files | ssato/python-anyconfig,ssato/python-anyconfig | tests/api/loads/common.py | tests/api/loads/common.py | #
# Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com>
# License: MIT
#
# pylint: disable=missing-docstring
import unittest
import anyconfig.api
from tests.base import TESTS_DIR, DATA_00
def list_test_data(kind: str = 'basics'):
root = TESTS_DIR / 'res' / 'loads' / kind
_ies = sorted(
(ddir, s... | #
# Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com>
# License: MIT
#
# pylint: disable=missing-docstring
from tests.base import TESTS_DIR, DATA_00
def list_test_data(kind: str = 'basics'):
root = TESTS_DIR / 'res' / 'loads' / kind
_ies = sorted(
(ddir, sorted(
(inp, DATA_00.get(st... | mit | Python |
e2d07a7c745f392b59587c9d3092a1a9e422f798 | Fix bad import | LucasRoesler/django-encrypted-json,LucasRoesler/django-encrypted-json | django_encrypted_json/fields.py | django_encrypted_json/fields.py | from django_pgjson.fields import JsonField, JsonBField, JsonAdapter
from .utils import decrypt_values, encrypt_values
class EncryptedValueJsonField(JsonField):
"""
A JSON field that will silently encrypt and decrypt the values of the
JSON value. It is based on django-pgjson's JSON field.
Example:
... | from django_pgjson.fields import JsonField, JsonBField, JsonAdapter
from .utils import encryption
class EncryptedValueJsonField(JsonField):
"""
A JSON field that will silently encrypt and decrypt the values of the
JSON value. It is based on django-pgjson's JSON field.
Example:
{
... | mit | Python |
cb9e4811247dbfc6b025db561cf34717b517df2b | Add index template | jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails | cocktails/drinks/views.py | cocktails/drinks/views.py | from drinks.models import Drink, Ingredient
from drinks.serializers import DrinkSerializer, IngredientSerializer
from drinks.permissions import IsOwnerOrReadOnly
from rest_framework import generics
from rest_framework import permissions
from django.template.response import TemplateResponse
# class based views
class... | from drinks.models import Drink, Ingredient
from drinks.serializers import DrinkSerializer, IngredientSerializer
from drinks.permissions import IsOwnerOrReadOnly
from rest_framework import generics
from rest_framework import permissions
# class based views
class DrinkList(generics.ListCreateAPIView):
permission_... | mit | Python |
774d62e6f6d6c51a4e0783369c7057d678c6ce11 | Update change_logging_key_value_store.py | wintoncode/winton-kafka-streams | winton_kafka_streams/state/change_logging_key_value_store.py | winton_kafka_streams/state/change_logging_key_value_store.py | from .store_change_logger import StoreChangeLogger
class ChangeLoggingKeyValueStore:
def __init__(self, name, inner):
self.inner = inner(name)
def initialise(self, context, root):
self.inner.initialise(context, root)
self.change_logger = StoreChangeLogger(self.inner.name, context)
... | from .store_change_logger import StoreChangeLogger
class ChangeLoggingKeyValueStore:
def __init__(self, name, inner):
self.inner = inner(name)
def initialise(self, context, root):
self.inner.initialise(context, root)
self.change_logger = StoreChangeLogger(self.inner.name, context)
... | apache-2.0 | Python |
3f6e61a87e17c9f181c83076057f13f27b181875 | normalise source between _str and _value | earies/exabgp,dneiter/exabgp,dneiter/exabgp,benagricola/exabgp,blablacar/exabgp,earies/exabgp,dneiter/exabgp,benagricola/exabgp,blablacar/exabgp,blablacar/exabgp,earies/exabgp,benagricola/exabgp | lib/exabgp/protocol/__init__.py | lib/exabgp/protocol/__init__.py | # encoding: utf-8
"""
protocol.py
Created by Thomas Mangin on 2010-01-15.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
# ===================================================================== Protocol
# http://www.iana.org/assignments/protocol-numbers/
class Protocol (int):
ICMP = 0x01
IGMP = 0... | # encoding: utf-8
"""
protocol.py
Created by Thomas Mangin on 2010-01-15.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
# ===================================================================== Protocol
# http://www.iana.org/assignments/protocol-numbers/
class Protocol (int):
ICMP = 0x01
IGMP = 0... | bsd-3-clause | Python |
09c7183566fcd2f6be77e8765a14430adcd0ad45 | Bump development version | nephila/djangocms-page-meta,nephila/djangocms-page-meta | djangocms_page_meta/__init__.py | djangocms_page_meta/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
__version__ = '0.5.10.post1'
__author__ = 'Iacopo Spalletti <i.spalletti@nephila.it>'
default_app_config = 'djangocms_page_meta.apps.PageMetaConfig'
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
__version__ = '0.5.10'
__author__ = 'Iacopo Spalletti <i.spalletti@nephila.it>'
default_app_config = 'djangocms_page_meta.apps.PageMetaConfig'
| bsd-3-clause | Python |
517e2275d5fbf59138890694420c7c582bc9cd31 | Change base url to dns.googleapis.com (#8641) | googleapis/python-dns,googleapis/python-dns | google/cloud/dns/_http.py | google/cloud/dns/_http.py | # Copyright 2015 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, s... | # Copyright 2015 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, s... | apache-2.0 | Python |
dfec85fdd047969ea04c02ec21c5b61303a893c3 | update for tweaks made in GPkit PR #513 | hoburg/gpfit,convexopt/gpfit,hoburg/gpfit,convexopt/gpfit,hoburg/gpfit,convexopt/gpfit | gpfit/tests/t_examples.py | gpfit/tests/t_examples.py | import unittest
import sys
import os
from gpkit.tests.t_examples import logged_example_testcase
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
EXAMPLE_DIR = os.path.abspath(FILE_DIR + '../../../docs/source/examples')
IMPORTED_EXAMPLES = {}
class TestExamples(unittest.TestCase):
# To test a new example, ... | import unittest
import sys
import os
from gpkit.tests.t_examples import new_test
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
EXAMPLE_DIR = os.path.abspath(FILE_DIR + '../../../docs/source/examples')
IMPORTED_EXAMPLES = {}
class TestExamples(unittest.TestCase):
# To test a new example, add a function ... | mit | Python |
ccb22bee228213a92985bfb3d718eac959d852b0 | Save each image in its own file. | martinarjovsky/WassersteinGAN | generate.py | generate.py | from __future__ import print_function
import argparse
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.util... | from __future__ import print_function
import argparse
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.util... | bsd-3-clause | Python |
3ed8d787c9dd72ac80355c9945fa64c344ceb930 | Fix #50, come on, use physcial file to avoid definite crash on pypy | chfw/pyexcel,chfw/pyexcel | tests/db.py | tests/db.py | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column , Integer, String, Float, Date
from sqlalchemy.orm import sessionmaker
import platform
engine = None
if platform.python_implementation() == 'PyPy':
engine=create_engine("sqlite:///tmp.db")
els... | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column , Integer, String, Float, Date
from sqlalchemy.orm import sessionmaker
engine=create_engine("sqlite:///tmp.db")
#engine=create_engine("sqlite://")
Base=declarative_base()
class Pyexcel(Base):
... | bsd-3-clause | Python |
5ba63898146b228303f64b5275fbed3fc6422ae7 | Complete assignment in string2.py | devendermishrajio/py-excercises,devendermishrajio/py-excercises,devendermishra/py-excercises | basic/string2.py | basic/string2.py | #!/usr/bin/python2.4 -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic string exercises
# D. verbing
# Given a string, if its length is a... | #!/usr/bin/python2.4 -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic string exercises
# D. verbing
# Given a string, if its length is a... | apache-2.0 | Python |
6a84e65db0eadf6655361129845c988a57523a05 | Fix small test mistake | fkmclane/web.py | tests/integration_test.py | tests/integration_test.py | import os
import shutil
import web
import web.file
from nose.tools import with_setup
test_message = 'This is a test sentence!'
class RootHandler(web.HTTPHandler):
def do_get(self):
return 200, test_message
str = b''
class EchoHandler(web.HTTPHandler):
def do_get(self):
global str
return 200, str
def do... | import os
import shutil
import web
import web.file
from nose.tools import with_setup
test_message = 'This is a test sentence!'
class RootHandler(web.HTTPHandler):
def do_get(self):
return 200, test_message
str = b''
class EchoHandler(web.HTTPHandler):
def do_get(self):
global str
return 200, str
def do... | mit | Python |
6712d88b16523bac33762da01ca3304249d56df6 | Revert state size randomness | sneaksnake/timeline | generate.py | generate.py | import datetime
import json
import re
import sqlite3
import markovify
import tweepy
import config
import utils
class SimulatorText(markovify.Text):
def sentence_split(self, text):
return text.split('<...>')
def get_recent_tweets():
pass
def generate_random_tweet():
db_connection = sqlite3.conne... | import datetime
import json
import random
import re
import sqlite3
import markovify
import tweepy
import config
import utils
class SimulatorText(markovify.Text):
def sentence_split(self, text):
return text.split('<...>')
def get_recent_tweets():
pass
def generate_random_tweet():
db_connection =... | mit | Python |
d93046174a45514dd5bd2e00ff9eea84ff61480a | set allowed host | ocwc/directory,ocwc/directory,ocwc/directory | directory/directory/settings.py | directory/directory/settings.py | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ALLOWED_HOSTS = ['www.oeconsortium.org']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
... | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.mes... | apache-2.0 | Python |
86fa8271b5788aadcbbde3decbcd413b9d22871c | Call super __init__ from Namespace.__init__ | embox/mybuild,abusalimov/mybuild,embox/mybuild,abusalimov/mybuild | util/namespace.py | util/namespace.py | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
super(Namespace, self).__init__()
self.__dict__.update... | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
... | unknown | Python |
d6a961a0aaa3ef823d4dba7b2111232865079a27 | Add unset_like test | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | tests/models/talk_test.py | tests/models/talk_test.py | from unittest import TestCase
from unittest.mock import patch, MagicMock
from meetup_facebook_bot.models.talk import Talk
class TalkTestCase(TestCase):
def setUp(self):
self.db_session = MagicMock()
self.user_id = 1
self.talk_id = 1
def test_is_liked_by(self):
pass
@pat... | from unittest import TestCase
from unittest.mock import patch, MagicMock
from meetup_facebook_bot.models import talk
class TalkTestCase(TestCase):
def test_is_liked_by(self):
pass
def test_set_like(self):
pass
def test_unset_like(self):
pass
def test_revert_like(self):
... | mit | Python |
1080e450ce6f9533c7d1158b920e9b02cb835546 | add functions to SocIdGetter | open-austin/data-portal-analysis | utils/NetUtils.py | utils/NetUtils.py | # This file is part of Open Austin's Data Portal Analysis project.
# For more information see README.md in the project's root directory.
import requests
import logging
class SocIdGetter:
def __init__(self):
self._views_url = "https://data.austintexas.gov/views"
self._migrations_api = "https://data... | # This file is part of Open Austin's Data Portal Analysis project.
# For more information see README.md in the project's root directory.
import requests
import logging
class SocIdGetter:
def __init__(self):
self._request_url = "http://data.austintexas.gov/search/views.json"
def get_all_ids():
... | unlicense | Python |
afc4ea056f9e3beef41b9944550df4e5da6c094c | add user agent | Lispython/pycurl,Lispython/pycurl,Lispython/pycurl | pycurl/examples/retriever.py | pycurl/examples/retriever.py | #! /usr/bin/env python
# vi:ts=4:et
# $Id$
import sys, threading, Queue
import pycurl
class WorkerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while 1:
try:
url, filename = self.queu... | #! /usr/bin/env python
# vi:ts=4:et
# $Id$
import sys, threading, Queue
import pycurl
class WorkerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while 1:
try:
url, filename = self.queu... | lgpl-2.1 | Python |
ad9ecc820f6d632aa15742e01e7469d5fddfc90a | Add tolerance on slope comparison: the difference is from a rounding issue and is not significant | e-koch/TurbuStat,Astroua/TurbuStat | turbustat/tests/test_vcs.py | turbustat/tests/test_vcs.py | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for VCS
'''
import pytest
import numpy as np
import numpy.testing as npt
import astropy.units as u
from ..statistics import VCS, VCS_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test... | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for VCS
'''
import pytest
import numpy as np
import numpy.testing as npt
import astropy.units as u
from ..statistics import VCS, VCS_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test... | mit | Python |
253daeb2e826a9fe87cd93c9bc1a2060d9b8fead | Disable South migrations for tests. | jgorset/fandjango,jgorset/fandjango | tests/project/settings.py | tests/project/settings.py | DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
}
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
]
INSTALLED_APPS = [
'fandjango',
'south',
'tests.project.app'
]
SOUTH_TESTS_MIGRATE = False
ROOT_URLCONF = 'tests.project.urls'
FACEBOOK_A... | DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
}
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
]
INSTALLED_APPS = [
'fandjango',
'south',
'tests.project.app'
]
ROOT_URLCONF = 'tests.project.urls'
FACEBOOK_APPLICATION_ID = 1812597119252... | mit | Python |
27bbc52dee3b83ae6e2c60e1c0e120c70de00d99 | Bump version to 0.19.0 | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader | pytablereader/__version__.py | pytablereader/__version__.py | # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.19.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.18.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| mit | Python |
0b5ef0fd1ce162db979a815ee0329ce7aa2fdccd | add rust for hass | ReanGD/ansible-personal,ReanGD/ansible-personal | common/files/packages_hass.py | common/files/packages_hass.py | # global host
pkgs = []
grps = []
# raspberry
pkgs += ["raspberrypi-firmware", "raspberrypi-bootloader-x", "linux-raspberrypi", "raspberrypi-bootloader"]
# system
pkgs += ["gcc", "make", "pkgconf", "unzip"]
# monitoring
pkgs += ["rsync",
"gnupg",
"iftop", # network monitor
"htop", # proc... | # global host
pkgs = []
grps = []
# raspberry
pkgs += ["raspberrypi-firmware", "raspberrypi-bootloader-x", "linux-raspberrypi", "raspberrypi-bootloader"]
# system
pkgs += ["gcc", "make", "pkgconf", "unzip"]
# monitoring
pkgs += ["rsync",
"gnupg",
"iftop", # network monitor
"htop", # proc... | apache-2.0 | Python |
e6e4e6191e90a7eaf26d573585aedeab71cc4924 | Remove unnecessary cast in test_inheritance | utter-step/exleval | tests/test_inheritance.py | tests/test_inheritance.py | import pytest
from .. import Evaler, NotSafeExpression
import _ast
class NoBinaryEvaler(Evaler):
@staticmethod
def get_allowed_nodes():
return Evaler.get_allowed_nodes() - set(
(_ast.LShift,
_ast.RShift,
_ast.BitAnd,
_ast.BitOr,
_ast.Bi... | import pytest
from .. import Evaler, NotSafeExpression
import _ast
class NoBinaryEvaler(Evaler):
@staticmethod
def get_allowed_nodes():
return set(Evaler.get_allowed_nodes()) - set(
(_ast.LShift,
_ast.RShift,
_ast.BitAnd,
_ast.BitOr,
_a... | mit | Python |
9f87fa9652f56b81ed3a2191aeb0cde1abcc4916 | Fix failing test after rebase | pipermerriam/ethereum-abi-utils | eth_abi/packed.py | eth_abi/packed.py | from typing import (
Any,
Iterable,
)
import warnings
from eth_typing.abi import (
TypeStr,
)
from eth_abi.encoding import (
TupleEncoder,
)
from eth_abi.registry import (
registry_packed,
)
warnings.warn(
"Packed mode encoding is an experimental feature. Please report any "
"problems at... | from typing import (
Any,
Iterable,
)
import warnings
from eth_typing.abi import (
TypeStr,
)
from eth_abi.encoding import (
TupleEncoder,
)
from eth_abi.registry import (
registry_packed,
)
from eth_abi.utils.parsing import (
collapse_type,
)
warnings.warn(
"Packed mode encoding is an ex... | mit | Python |
273eae39073a2cef9a4ade8d51f2353b63a8991d | Update test_mppcommands.py | jblance/mpp-solar | tests/test_mppcommands.py | tests/test_mppcommands.py | import unittest
from mppsolar import mppcommands
class test_mppcommands(unittest.TestCase):
def test_trunc_function(self):
""" Test trunc function correctly returns truncated / padded text """
self.assertEqual(mppcommands.trunc('Short test'), 'Short test ')
self.asser... | import unittest
from mppsolar import mppcommands
class test_mppcommands(unittest.TestCase):
def test_trunc_function(self):
""" Test trunc function correctly returns truncated / padded text """
self.assertEqual(mppcommands.trunc('Short test'), 'Short test ')
self.asser... | mit | Python |
4570f81e470d6f8f88e3b6bedf30bf4b30967d76 | add nginx host. | why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado | tests/test_view_module.py | tests/test_view_module.py | # -*- coding: utf-8 -*-
from . import utils
from . import consts
def pagination():
utils.expecting_text('get', '/view/module/pagination', None, 200)
def pagination_prefix():
utils.expecting_text('get', '/view/module/pagination/prefix', None, 200, host=consts.dp_testing_nginx_host)
| # -*- coding: utf-8 -*-
from . import utils
def pagination():
utils.expecting_text('get', '/view/module/pagination', None, 200)
def pagination_prefix():
utils.expecting_text('get', '/view/module/pagination/prefix', None, 200)
| mit | Python |
1d98a1f47db72fd5f56019b2cef92a6e0b0d64c1 | Add initial solution | CubicComet/exercism-python-solutions | queen-attack/queen_attack.py | queen-attack/queen_attack.py | def board(white, black):
if white == black:
raise ValueError("Pieces cannot share a position")
_board = [['_']*8 for _ in range(8)]
wx, wy = white
bx, by = black
try:
_board[wx][wy] = "W"
_board[bx][by] = "B"
except IndexError:
raise ValueError("Piece coordinates ... | def board():
pass
def can_attack():
pass
| agpl-3.0 | Python |
7ec258ece26ffb0bd560bf8be4fdad86ae618b43 | Update cmd.py | MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab | home/pedrosenarego/cmd.py | home/pedrosenarego/cmd.py | #!/usr/bin/env python
import subprocess
def runEvent(subject):
subprocess.call("cd /home/pedro/Dropbox/pastaPessoal/3Dprinter/inmoov/scripts/googlecalandar && gnome-terminal -x python event.py " + str(subject), shell=True)
runEvent("It's party time!")
| #!/usr/bin/env python
import subprocess
subprocess.call("cd /home/pedro/Dropbox/pastaPessoal/3Dprinter/inmoov/scripts/googlecalandar && gnome-terminal -x python event.py", shell=True)
| apache-2.0 | Python |
a33ca18776d3f8415179c67c9c361f1e1931ffc8 | Add calendar domain as ignored | kevinkahn/softconsole,kevinkahn/softconsole | hubs/ha/domains/ignore.py | hubs/ha/domains/ignore.py | from hubs.ha.hasshub import HAnode, RegisterDomain
from functools import partial
import hubs.ha.hasshub as hasshub
import logsupport
IgnoreThese = ('sun', 'person', 'notifications', 'persistent_notification', 'zone', 'history_graph', 'updater',
'configurator', 'weather', 'counter', 'camera', 'lock', 'alarm_contr... | from hubs.ha.hasshub import HAnode, RegisterDomain
from functools import partial
import hubs.ha.hasshub as hasshub
import logsupport
IgnoreThese = ('sun', 'person', 'notifications', 'persistent_notification', 'zone', 'history_graph', 'updater',
'configurator', 'weather', 'counter', 'camera', 'lock', 'alarm_contr... | apache-2.0 | Python |
d0e48e078b92b77b90381857fc7ed37d01af8e25 | Fix a bug in computing valid/invalid parts | ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo | web/problems/views.py | web/problems/views.py | from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, get_list_or_404, render
from problems.models import Problem, Part
from utils.views import plain_text
@login_required
def problem_list(request):
"""Show a list of all problems."""
user_attempts = request.u... | from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, get_list_or_404, render
from problems.models import Problem, Part
from utils.views import plain_text
@login_required
def problem_list(request):
"""Show a list of all problems."""
user_attempts = request.u... | agpl-3.0 | Python |
891450c220918097f20ae20a56a7cae509be8ba9 | Replace usage of pathlib.Path.__str__() with str(pathlib.Path) | arecarn/dploy | dploy/utils.py | dploy/utils.py | """
todo
"""
import os
import pathlib
import shutil
def get_directory_contents(directory):
"""
todo
"""
contents = []
for child in directory.iterdir():
contents.append(child)
return contents
def rmtree(tree):
"""
a wrapper around shutil.rmtree to recursively delete a direct... | """
todo
"""
import os
import pathlib
import shutil
def get_directory_contents(directory):
"""
todo
"""
contents = []
for child in directory.iterdir():
contents.append(child)
return contents
def rmtree(tree):
"""
a wrapper around shutil.rmtree to recursively delete a direct... | mit | Python |
4e0b9a20dbf9d44d83f6e34a704f4c6a6e2a1e17 | Make segmentation_to_hdf5 script output datasets of the proper shape. WARNING: still contains "swapaxis" to make the rest of the pipeline work for me. | chaubold/hytra,chaubold/hytra,chaubold/hytra | toolbox/segmentation_to_hdf5.py | toolbox/segmentation_to_hdf5.py | import numpy as np
import h5py
import vigra
import argparse
def segmentation_to_hdf5(options):
"""
The generated segmentation is one HDF5 dataset per timestep,
and each of these datasets has shape 1(t),x,y,z,1(c).
"""
out_h5 = h5py.File(options.hdf5Path, 'w')
for timeframe in range(len(options.... | import numpy as np
import h5py
import vigra
import argparse
def segmentation_to_hdf5(options):
out_h5 = h5py.File(options.hdf5Path, 'w')
for timeframe in range(len(options.tif_input_files)):
data = vigra.impex.readImage(options.tif_input_files[timeframe], dtype='UINT16') # sure UINT32?
internal... | mit | Python |
585db56aa5ed95d07ccaf88f78ac82fa73b1771b | Allow using either just one json file, or a specific key in a global json file. | sujaymansingh/dudebot | dudebot/__main__.py | dudebot/__main__.py | import logging
import json
import optparse
import sys
import traceback
from dudebot import jabber
from dudebot import classutil
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("--config_filename", dest="config_filename", help="The name of the json file with all the details", met... | import logging
import json
import optparse
import sys
import traceback
from dudebot import jabber
from dudebot import classutil
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("--config_filename", dest="config_filename", help="The name of the json file with all the details", met... | bsd-2-clause | Python |
596d6765f49f9fcaa0f090d340effabebdbf3730 | set registered time by paypal payment time | rdonnelly/ultimate-league-app,rdonnelly/ultimate-league-app,a2ultimate/ultimate-league-app,a2ultimate/ultimate-league-app,a2ultimate/ultimate-league-app,rdonnelly/ultimate-league-app,rdonnelly/ultimate-league-app,a2ultimate/ultimate-league-app | ultimate/leagues/signals.py | ultimate/leagues/signals.py | # index/signals.py
from datetime import datetime
from ultimate.leagues.models import League, Registrations
from paypal.standard.ipn.signals import payment_was_successful
def payment_success(sender, **kwargs):
ipn_obj = sender
print 'PayPal IPN Incoming: ' + ipn_obj.invoice
try:
registration = Registrations.o... | # index/signals.py
from datetime import datetime
from ultimate.leagues.models import League, Registrations
from paypal.standard.ipn.signals import payment_was_successful
def payment_success(sender, **kwargs):
ipn_obj = sender
print 'PayPal IPN Incoming: ' + ipn_obj.invoice
try:
registration = Registrations.o... | bsd-3-clause | Python |
6e4c42be2feb358b8aea8e73ff20d18db14b9ab7 | Fix comment in receive hook | schieb/angr,f-prettyland/angr,iamahuman/angr,iamahuman/angr,angr/angr,f-prettyland/angr,iamahuman/angr,tyb0807/angr,tyb0807/angr,tyb0807/angr,angr/angr,angr/tracer,schieb/angr,schieb/angr,f-prettyland/angr,angr/angr | tracer/simprocedures/receive.py | tracer/simprocedures/receive.py | from simuvex.procedures.cgc.receive import receive
import logging
l = logging.getLogger("tracer.simprocedures.FixedInReceive")
class FixedInReceive(receive):
# pylint:disable=arguments-differ
"""
Receive which fixes the input to file descriptor to 0.
"""
def run(self, fd, buf, count, rx_bytes):
... | from simuvex.procedures.cgc.receive import receive
import logging
l = logging.getLogger("tracer.simprocedures.FixedInReceive")
class FixedInReceive(receive):
# pylint:disable=arguments-differ
"""
Transmit which fixes the output file descriptor to 1.
"""
def run(self, fd, buf, count, rx_bytes):
... | bsd-2-clause | Python |
edda318207e7befd7a2ce69d6005939994e70084 | Remove feature | Srisai85/SciPyCentral,ksurya/SciPyCentral,ksurya/SciPyCentral,wqshi/test,scipy/SciPyCentral,scipy/SciPyCentral,Srisai85/SciPyCentral,Srisai85/SciPyCentral,ksurya/SciPyCentral,wqshi/test,scipy/SciPyCentral,wqshi/test | scipy_central/pages/views.py | scipy_central/pages/views.py | from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
from scipy_central.utils import get_IP_address
import logging
logger = logging.getLogger('scipycentral')
logger.debug('Initializing pages::vie... | from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
from scipy_central.utils import get_IP_address
import logging
logger = logging.getLogger('scipycentral')
logger.debug('Initializing pages::vie... | bsd-3-clause | Python |
88b227248e549a9fb21b8e73a73edbbe026485c7 | stop event default before changing item | jaredly/pyjamas,jaredly/pyjamas,jaredly/pyjamas,jaredly/pyjamas | library/pyjamas/ui/Hyperlink.py | library/pyjamas/ui/Hyperlink.py | # Copyright 2006 James Tauber and contributors
#
# 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 agre... | # Copyright 2006 James Tauber and contributors
#
# 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 agre... | apache-2.0 | Python |
5f2e55b005e5b87f0608fd5b7b1dc206243f31e7 | Update tests | andresmrm/CaronaSustentavel,andresmrm/CaronaSustentavel,andresmrm/CaronaSustentavel,andresmrm/CaronaSustentavel | wsgi/pyramidapp/pyramidapp/tests.py | wsgi/pyramidapp/pyramidapp/tests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright 2013 Carona Sustentavel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright 2013 Carona Sustentavel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... | agpl-3.0 | Python |
0da15aaa1f74a6c5c0d7f07d5dd1ed732c55cf04 | Fix the example again | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | sunpy/net/dataretriever/__init__.py | sunpy/net/dataretriever/__init__.py | """
This module is broken into two layers. At the bottom layer individual clients
(LightCurve clients, VSO) operate and download files.
At the top level the Factory instance decides which client/s can best serve
the query. The factory instance breaks up a query into modular pieces which could be served by
clients at th... | """
This module is broken into two layers. At the bottom layer individual clients
(LightCurve clients, VSO) operate and download files.
At the top level the Factory instance decides which client/s can best serve
the query. The factory instance breaks up a query into modular pieces which could be served by
clients at th... | bsd-2-clause | Python |
266ae8368e728a69418c6f6e801d728e3cb9f67c | Fix issue with workingDir CLI test | jalama/drupdates | drupdates/tests/behavioral/test_multiple_working_directories_working_directory_cli.py | drupdates/tests/behavioral/test_multiple_working_directories_working_directory_cli.py | """ Test passing workingDir on the CLI """
import os
from os.path import expanduser
from drupdates.tests.behavioral.behavioral_utils import BehavioralUtils
from drupdates.tests import Setup
class TestMultipleWorkingDirectoriesWorkingDirectoryCLI(object):
""" Test passing workingDir on the CLI """
@classmetho... | """ Test passing workingDir on the CLI """
import os
from os.path import expanduser
from drupdates.tests.behavioral.behavioral_utils import BehavioralUtils
from drupdates.tests import Setup
class TestMultipleWorkingDirectoriesWorkingDirectoryCLI(object):
""" Test passing workingDir on the CLI """
@classmetho... | mit | Python |
da5c6f7dbeb34667cad5abf94e354a3fcb5132de | Update dump_symbols to match new file_id code. | wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser | build/linux/dump_signature.py | build/linux/dump_signature.py | #!/usr/bin/python
#
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This generates symbol signatures with the same algorithm as
# src/breakpad/src/common/linux/file_id.cc@461
import struct
import s... | #!/usr/bin/python
#
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This generates symbol signatures with the same algorithm as
# src/breakpad/src/common/linux/file_id.cc@461
import sys
import stru... | bsd-3-clause | Python |
3dee65388eb9ff77938bd357bb239b4c83de770f | Update the basic example. | Lukasa/spdypy | examples/basic.py | examples/basic.py | # -*- coding: utf-8 -*-
"""
A basic example of how to use SPDY.
This example is currently incomplete, but should remain current to the state of
the library. This means that it enumerates the full state of everything
SPDYPy can do.
"""
import sys
sys.path.append('.')
import spdypy
conn = spdypy.SPDYConnection('www.goo... | # -*- coding: utf-8 -*-
"""
A basic example of how to use SPDY.
This example is currently incomplete, but should remain current to the state of
the library. This means that it enumerates the full state of everything
SPDYPy can do.
"""
import sys
sys.path.append('.')
import spdypy
conn = spdypy.SPDYConnection('www.goo... | mit | Python |
6667eecdd855bfcfcade281243ef896c2a819446 | Change standard architectures for avb_celebA_64 experiments for consistency. | LMescheder/AdversarialVariationalBayes | experiments/avb_celebA_64/run.py | experiments/avb_celebA_64/run.py | import os
from subprocess import call
from os import path
# Executables
executable = 'python'
# Paths
srcdir = '../..'
scriptname = 'run_avae.py'
cwd = os.path.dirname(os.path.abspath(__file__))
outdir = cwd
rootdir = srcdir
# Arguments
args = [
# Architecture
'--is-train',
'--image-size', '128',
'--output-size', '6... | import os
from subprocess import call
from os import path
# Executables
executable = 'python'
# Paths
srcdir = '../..'
scriptname = 'run_avae.py'
cwd = os.path.dirname(os.path.abspath(__file__))
outdir = cwd
rootdir = srcdir
# Arguments
args = [
# Architecture
'--is-train',
'--image-size', '128',
'--output-size', '6... | mit | Python |
0bf7e80183b8001de947576f31f28ee8e378433e | rewrite riemannian grad full in such way that it gives rank-3r lowrank matrix as a gradient | Nehoroshiy/multi_classifier,Nehoroshiy/multi_classifier | riemannian_optimization/sparse/utils/projections/riemannian_grad_full.py | riemannian_optimization/sparse/utils/projections/riemannian_grad_full.py | """
Copyright (c) 2015-2016 Constantine Belev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... | """
Copyright (c) 2015-2016 Constantine Belev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... | mit | Python |
9771381323e4eb44a13ffc8742615fba61ad2b85 | Update receive and send functions according to the new requirements | lsaffre/lino,lsaffre/lino,khchine5/lino,khchine5/lino,khchine5/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,lsaffre/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,khchine5/lino,khchine5/lino,lino-framework/lino | lino/modlib/notify/consumers.py | lino/modlib/notify/consumers.py | import json
from channels import Channel
from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
from django.utils import timezone
from lino.modlib.notify.models import Notification
# This decorator copies the user from the HTTP session (only available in
# websocket... | from channels import Group
def ws_echo(message):
Group(str(message.content['text'])).add(message.reply_channel)
message.reply_channel.send({
"text": message.content['text'],
})
| unknown | Python |
50ba0c2c576a4b9eddaa64537dadfd8684463794 | Create script to save documentation to a file | 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 |
021abcb49198358033d1cb111089f3108569585b | return temp pipe obj during enter tp context | faycheng/tpl,faycheng/tpl | tpl/path.py | tpl/path.py | # -*- coding:utf-8 -*-
import os
import uuid
class TempDir(object):
pass
class TempFile(object):
pass
class TempPipe(object):
def __init__(self):
self.pipe_path = '/tmp/{}.pipe'.format(str(uuid.uuid4()))
self.pipe = None
def __enter__(self):
os.mkfifo(self.pipe_path)
... | # -*- coding:utf-8 -*-
import os
import uuid
class TempDir(object):
pass
class TempFile(object):
pass
class TempPipe(object):
def __init__(self):
self.pipe_path = '/tmp/{}.pipe'.format(str(uuid.uuid4()))
self.pipe = None
def __enter__(self):
os.mkfifo(self.pipe_path)
... | mit | Python |
ec9d5c36affd677c63a029df066353d832276c5f | Update irrigators_phone.py | mikelambson/tcid,mikelambson/tcid,mikelambson/tcid,mikelambson/tcid | site/models/irrigators_phone.py | site/models/irrigators_phone.py | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
class Irrigators_phone(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
irrigator_id = DB.relationship(DB.Integer, DB.ForeignKey('irrigators.id), lazy='joined');
phone_id = DB.relation... | import datetime, re;
from sqlalchemy.orm import validates;
from server import DB, FlaskServer;
class Irrigators_phone(DB.Model):
id = DB.Column(DB.Integer, primary_key=True, autoincrement=True);
irrigator_id = DB.relationship(DB.Integer, DB.ForeignKey('irrigators.id), lazy='joined');
phone_id = DB.relation... | bsd-3-clause | Python |
b0d439892b12f4b2c7de4bae0051928b7c336519 | Correct the copyright year | nlfiedler/magick-rust | vagrant/ubuntu14/fabfile.py | vagrant/ubuntu14/fabfile.py | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------
#
# Copyright (c) 2016 Nathan Fiedler
#
# This file is provided to you 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 ... | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------
#
# Copyright (c) 2014-2016 Nathan Fiedler
#
# This file is provided to you 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... | apache-2.0 | Python |
7f7c249d02016b90e7d3f2849c4d98609c21ecef | Add optional category matching | keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles | lldbhelpers/function_address.py | lldbhelpers/function_address.py | import lldb
import re
SYMBOL_REGEX = re.compile("^([+-])\[([^\s\]\(]+)(\([^\s]+\))?\s+([^\s\]]+)\]$")
def output_for_command(debugger, command):
interpreter = debugger.GetCommandInterpreter()
result = lldb.SBCommandReturnObject()
interpreter.HandleCommand(command, result)
if result.GetStatus() == 2:... | import lldb
import re
SYMBOL_REGEX = re.compile("^([+-])\[([^\s\]]+)\s([^\s\]]+)\]$")
def output_for_command(debugger, command):
interpreter = debugger.GetCommandInterpreter()
result = lldb.SBCommandReturnObject()
interpreter.HandleCommand(command, result)
if result.GetStatus() == 2:
return ... | mit | Python |
6fee033524a04dd1b00265d1ad2a2d87629d7ccd | ADD NOT_RESPONSE | October-66/Traveler-Pal,October-66/Traveler-Pal,October-66/Traveler-Pal | traveler_pal/app/Utils.py | traveler_pal/app/Utils.py | from django.utils import timezone
def getCurDateTime():
return timezone.now()
def toJSON(self):
fields = []
for field in self._meta.fields:
fields.append(field.name)
d = {}
for attr in fields:
d[attr] = getattr(self, attr)
import json
return json.dumps(d)
def not_respo... | from django.utils import timezone
def getCurDateTime():
return timezone.now()
def toJSON(self):
fields = []
for field in self._meta.fields:
fields.append(field.name)
d = {}
for attr in fields:
d[attr] = getattr(self, attr)
import json
return json.dumps(d)
| mit | Python |
a0287d97a7c953456b3f06108b5276a628a118e8 | rename getoptions -> get_options | stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis | Synopsis/process.py | Synopsis/process.py | # $Id: process.py,v 1.5 2003/12/11 04:38:59 stefan Exp $
#
# Copyright (C) 2003 Stefan Seefeld
# All rights reserved.
# Licensed to the public under the terms of the GNU LGPL (>= 2),
# see the file COPYING for details.
#
from Processor import Processor
import AST
from getoptions import get_options
import sys
def err... | # $Id: process.py,v 1.5 2003/12/11 04:38:59 stefan Exp $
#
# Copyright (C) 2003 Stefan Seefeld
# All rights reserved.
# Licensed to the public under the terms of the GNU LGPL (>= 2),
# see the file COPYING for details.
#
from Processor import Processor
import AST
from getoptions import getoptions
import sys
def erro... | lgpl-2.1 | Python |
d7525594e58a3ae8fb7d50826b7e84ac50e1c273 | Fix the setup file as per the new changes | intel-ctrlsys/actsys | oobrestclient/setup.py | oobrestclient/setup.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Intel Corp.
#
"""
Installation script for the NC REST Client API Wrapper
"""
from setuptools import setup
setup(name="oobrestclient",
version="0.3.0",
packages=['oobrestclient'],
install_requires=['aiohttp', 'asyncio'],
author="Intel Corporation",... | """
Installation script for the NC REST Client API Wrapper
"""
from setuptools import setup
setup(name="oobrestclient",
version="0.3.0",
packages=['oobrestclient'],
install_requires=['requests'],
author="Jonathan Smith",
author_email="jonathan.d.smith@intel.com",
description="Mock ... | apache-2.0 | Python |
4e12ae08bbd97d152955003e7f12ab9863016139 | Add a TODO item. | google/vizier,google/vizier | vizier/pyvizier/__init__.py | vizier/pyvizier/__init__.py | """PyVizier classes for Pythia policies."""
from vizier._src.pyvizier.pythia.study import StudyDescriptor
from vizier._src.pyvizier.pythia.study import StudyState
from vizier._src.pyvizier.pythia.study import StudyStateInfo
from vizier._src.pyvizier.shared.base_study_config import MetricInformation
from vizier._src.py... | """PyVizier classes for Pythia policies."""
from vizier._src.pyvizier.pythia.study import StudyDescriptor
from vizier._src.pyvizier.pythia.study import StudyState
from vizier._src.pyvizier.pythia.study import StudyStateInfo
from vizier._src.pyvizier.shared.base_study_config import MetricInformation
from vizier._src.py... | apache-2.0 | Python |
d5d923bba6cf9fc123dbcd8c314b17b29c4c0f10 | Update for aeSecure plugin | EnableSecurity/wafw00f | wafw00f/plugins/aesecure.py | wafw00f/plugins/aesecure.py | #!/usr/bin/env python
NAME = 'aeSecure (aeSecure)'
def is_waf(self):
schemes = [
self.matchHeader(('aeSecure-code', '.+')),
self.matchContent(r'aesecure_denied.png')
]
if any(i for i in schemes):
return True
return False | #!/usr/bin/env python
NAME = 'aeSecure (aeSecure)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
if response.getheader('aeSecure-code'):
return True
if b'aesecure_denied.png' in page:
... | bsd-3-clause | Python |
a1178501a8e135248c35abaa3b6faeaa3a59eb90 | fix autor | ErickMurillo/plataforma_fadcanic,CARocha/plataforma_fadcanic,shiminasai/plataforma_fadcanic,CARocha/plataforma_fadcanic,ErickMurillo/plataforma_fadcanic,ErickMurillo/plataforma_fadcanic,shiminasai/plataforma_fadcanic,shiminasai/plataforma_fadcanic,CARocha/plataforma_fadcanic | cambiaahora/noticias/admin.py | cambiaahora/noticias/admin.py | from django.contrib import admin
from .models import Noticias, Categoria
class NoticiasAdmin(admin.ModelAdmin):
def queryset(self, request):
if request.user.is_superuser:
return Noticias.objects.all()
return Noticias.objects.filter(user=request.user)
# def save_model(self, request, obj, form, change):
# ob... | from django.contrib import admin
from .models import Noticias, Categoria
class NoticiasAdmin(admin.ModelAdmin):
def queryset(self, request):
if request.user.is_superuser:
return Noticias.objects.all()
return Noticias.objects.filter(user=request.user)
def save_model(self, request, obj, form, change):
obj.us... | mit | Python |
b2c5064d5d1fe6bc9a5ee1166a9d9373fbb271b5 | add nullBoolean to Miscelleneous provider | meganlkm/faker,trtd/faker,johnraz/faker,beetleman/faker,jaredculp/faker,GLMeece/faker,xfxf/faker-1,venmo/faker,xfxf/faker-python,danhuss/faker,yiliaofan/faker,joke2k/faker,MaryanMorel/faker,joke2k/faker,ShaguptaS/faker,ericchaves/faker,thedrow/faker,HAYASAKA-Ryosuke/faker | faker/providers/Miscelleneous.py | faker/providers/Miscelleneous.py | from . import BaseProvider
from . import DateTime
import random
import hashlib
class Provider(BaseProvider):
languageCodes = ('cn','de','en','es','fr','it','pt','ru')
@classmethod
def boolean(cls, chanceOfGettingTrue=50):
return random.randint(1,100) <= chanceOfGettingTrue
@classmethod
... | from . import BaseProvider
from . import DateTime
import random
import hashlib
class Provider(BaseProvider):
languageCodes = ('cn','de','en','es','fr','it','pt','ru')
@classmethod
def boolean(cls, changeOfGettingTrue=50):
return random.randint(1,100) <= changeOfGettingTrue
@classmethod
... | mit | Python |
19826680f87d9454f830e3fa394aa4429d1c1e91 | Switch to use real domain. | marrow/contentment,marrow/contentment | web/contentment/dispatch.py | web/contentment/dispatch.py | # encoding: utf-8
from inspect import isroutine
from webob.exc import HTTPNotFound
from marrow.package.loader import load
from web.dispatch.object import ObjectDispatch
from web.component.asset.model import Asset
log = __import__('logging').getLogger(__name__)
class ContentmentDispatch:
def __init__(self, conf... | # encoding: utf-8
from inspect import isroutine
from webob.exc import HTTPNotFound
from marrow.package.loader import load
from web.dispatch.object import ObjectDispatch
from web.component.asset.model import Asset
log = __import__('logging').getLogger(__name__)
class ContentmentDispatch:
def __init__(self, conf... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.