commit
stringlengths 40
40
| old_file
stringlengths 4
234
| new_file
stringlengths 4
234
| old_contents
stringlengths 10
3.01k
| new_contents
stringlengths 19
3.38k
| subject
stringlengths 16
736
| message
stringlengths 17
2.63k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
82.6k
| config
stringclasses 4
values | content
stringlengths 134
4.41k
| fuzzy_diff
stringlengths 29
3.44k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
332452cf7ccd6d3ee583be9a6aac27b14771263f
|
source/services/omdb_service.py
|
source/services/omdb_service.py
|
import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
ratings = []
ratings.append(movie_info['tomatoMeter'])
ratings.append(movie_info['tomatoUserMeter'])
return RTRating(ratings)
|
import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
scores = []
scores.append(movie_info['tomatoMeter'])
scores.append(movie_info['tomatoUserMeter'])
rt_rating = RTRating(scores)
rt_rating.link = movie_info['tomatoURL']
return rt_rating
|
Add url to RTRating object
|
Add url to RTRating object
|
Python
|
mit
|
jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu
|
python
|
## Code Before:
import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
ratings = []
ratings.append(movie_info['tomatoMeter'])
ratings.append(movie_info['tomatoUserMeter'])
return RTRating(ratings)
## Instruction:
Add url to RTRating object
## Code After:
import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
scores = []
scores.append(movie_info['tomatoMeter'])
scores.append(movie_info['tomatoUserMeter'])
rt_rating = RTRating(scores)
rt_rating.link = movie_info['tomatoURL']
return rt_rating
|
// ... existing code ...
response = requests.post(self.__API_URL, params=payload)
movie_info = response.json()
scores = []
scores.append(movie_info['tomatoMeter'])
scores.append(movie_info['tomatoUserMeter'])
rt_rating = RTRating(scores)
rt_rating.link = movie_info['tomatoURL']
return rt_rating
// ... rest of the code ...
|
9f7344e6d253edb47a863a527bbffdb3e0d839e7
|
Programs/sys_prog_windows.h
|
Programs/sys_prog_windows.h
|
/*
* BRLTTY - A background process providing access to the Linux console (when in
* text mode) for a blind person using a refreshable braille display.
*
* Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved.
*
* BRLTTY comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU General Public License, as published by the Free Software
* Foundation. Please see the file COPYING for details.
*
* Web Page: http://mielke.cc/brltty/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
char *
getProgramPath (void) {
CHAR path[MAX_PATH];
DWORD length = GetModuleFileName(GetModuleHandle(NULL), path, sizeof(path));
while (length > 0)
if (path[--length] == '\\')
path[length] = '/';
return strdupWrapper(path);
}
|
/*
* BRLTTY - A background process providing access to the Linux console (when in
* text mode) for a blind person using a refreshable braille display.
*
* Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved.
*
* BRLTTY comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU General Public License, as published by the Free Software
* Foundation. Please see the file COPYING for details.
*
* Web Page: http://mielke.cc/brltty/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
char *
getProgramPath (void) {
char *path = NULL;
HMODULE handle;
if ((handle = GetModuleHandle(NULL))) {
size_t size = 0X80;
char *buffer = NULL;
while (1) {
buffer = reallocWrapper(buffer, size<<=1);
{
DWORD length = GetModuleFileName(handle, buffer, size);
if (!length) {
LogWindowsError("GetModuleFileName");
break;
}
if (length < size) {
buffer[length] = 0;
path = strdupWrapper(buffer);
while (length > 0)
if (path[--length] == '\\')
path[length] = '/';
break;
}
}
}
free(buffer);
} else {
LogWindowsError("GetModuleHandle");
}
return path;
}
|
Remove the use of PATH_MAX from the Windows implementation of getProgramPath(). (dm)
|
Remove the use of PATH_MAX from the Windows implementation of getProgramPath(). (dm)
git-svn-id: 30a5f035a20f1bc647618dbad7eea2a951b61b7c@1287 91a5dbb7-01b9-0310-9b5f-b28072856b6e
|
C
|
lgpl-2.1
|
brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty
|
c
|
## Code Before:
/*
* BRLTTY - A background process providing access to the Linux console (when in
* text mode) for a blind person using a refreshable braille display.
*
* Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved.
*
* BRLTTY comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU General Public License, as published by the Free Software
* Foundation. Please see the file COPYING for details.
*
* Web Page: http://mielke.cc/brltty/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
char *
getProgramPath (void) {
CHAR path[MAX_PATH];
DWORD length = GetModuleFileName(GetModuleHandle(NULL), path, sizeof(path));
while (length > 0)
if (path[--length] == '\\')
path[length] = '/';
return strdupWrapper(path);
}
## Instruction:
Remove the use of PATH_MAX from the Windows implementation of getProgramPath(). (dm)
git-svn-id: 30a5f035a20f1bc647618dbad7eea2a951b61b7c@1287 91a5dbb7-01b9-0310-9b5f-b28072856b6e
## Code After:
/*
* BRLTTY - A background process providing access to the Linux console (when in
* text mode) for a blind person using a refreshable braille display.
*
* Copyright (C) 1995-2004 by The BRLTTY Team. All rights reserved.
*
* BRLTTY comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU General Public License, as published by the Free Software
* Foundation. Please see the file COPYING for details.
*
* Web Page: http://mielke.cc/brltty/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
char *
getProgramPath (void) {
char *path = NULL;
HMODULE handle;
if ((handle = GetModuleHandle(NULL))) {
size_t size = 0X80;
char *buffer = NULL;
while (1) {
buffer = reallocWrapper(buffer, size<<=1);
{
DWORD length = GetModuleFileName(handle, buffer, size);
if (!length) {
LogWindowsError("GetModuleFileName");
break;
}
if (length < size) {
buffer[length] = 0;
path = strdupWrapper(buffer);
while (length > 0)
if (path[--length] == '\\')
path[length] = '/';
break;
}
}
}
free(buffer);
} else {
LogWindowsError("GetModuleHandle");
}
return path;
}
|
// ... existing code ...
char *
getProgramPath (void) {
char *path = NULL;
HMODULE handle;
if ((handle = GetModuleHandle(NULL))) {
size_t size = 0X80;
char *buffer = NULL;
while (1) {
buffer = reallocWrapper(buffer, size<<=1);
{
DWORD length = GetModuleFileName(handle, buffer, size);
if (!length) {
LogWindowsError("GetModuleFileName");
break;
}
if (length < size) {
buffer[length] = 0;
path = strdupWrapper(buffer);
while (length > 0)
if (path[--length] == '\\')
path[length] = '/';
break;
}
}
}
free(buffer);
} else {
LogWindowsError("GetModuleHandle");
}
return path;
}
// ... rest of the code ...
|
cbeabd95e172ae213a3e95f2285b4ccc00a80254
|
src/you_get/extractors/dailymotion.py
|
src/you_get/extractors/dailymotion.py
|
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = match1(html, r'"title"\s*:\s*"(.+?)",')
for quality in ['720','480','380','240','auto']:
real_url = info[quality][0]["url"]
if real_url:
break
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
|
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = match1(html, r'"title"\s*:\s*"(.+?)",')
for quality in ['720','480','380','240','auto']:
try:
real_url = info[quality][0]["url"]
if real_url:
break
except KeyError:
pass
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
|
Fix problems with videos that do not have 720p mode
|
Fix problems with videos that do not have 720p mode
|
Python
|
mit
|
linhua55/you-get,jindaxia/you-get,qzane/you-get,cnbeining/you-get,zmwangx/you-get,linhua55/you-get,Red54/you-get,lilydjwg/you-get,xyuanmu/you-get,qzane/you-get,zmwangx/you-get,lilydjwg/you-get,smart-techs/you-get,specter4mjy/you-get,xyuanmu/you-get,smart-techs/you-get,cnbeining/you-get
|
python
|
## Code Before:
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = match1(html, r'"title"\s*:\s*"(.+?)",')
for quality in ['720','480','380','240','auto']:
real_url = info[quality][0]["url"]
if real_url:
break
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
## Instruction:
Fix problems with videos that do not have 720p mode
## Code After:
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = match1(html, r'"title"\s*:\s*"(.+?)",')
for quality in ['720','480','380','240','auto']:
try:
real_url = info[quality][0]["url"]
if real_url:
break
except KeyError:
pass
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
|
...
title = match1(html, r'"title"\s*:\s*"(.+?)",')
for quality in ['720','480','380','240','auto']:
try:
real_url = info[quality][0]["url"]
if real_url:
break
except KeyError:
pass
type, ext, size = url_info(real_url)
...
|
8c89257b9b7b58dbdeb977295e95863793877b70
|
cpp/exit_status.h
|
cpp/exit_status.h
|
typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;
#endif
|
typedef enum {Success=0, Error_open_file=1, Error_command_line=2, Error_parse_file=3} exit_status;
#endif
|
Correct c++ exit status values
|
Correct c++ exit status values
|
C
|
mit
|
bjpop/biotool,bjpop/biotool,drpowell/biotool,bjpop/biotool,supernifty/biotool,bjpop/biotool,bjpop/biotool,drpowell/biotool,biotool-paper/biotool,lonsbio/biotool,lonsbio/biotool,biotool-paper/biotool,bjpop/biotool,supernifty/biotool,drpowell/biotool,biotool-paper/biotool,drpowell/biotool,lonsbio/biotool,biotool-paper/biotool,supernifty/biotool,biotool-paper/biotool,bjpop/biotool,supernifty/biotool,bjpop/biotool,drpowell/biotool,bjpop/biotool,drpowell/biotool,biotool-paper/biotool,supernifty/biotool,drpowell/biotool,bionitio-team/bionitio,biotool-paper/biotool,biotool-paper/biotool,biotool-paper/biotool,drpowell/biotool,supernifty/biotool,supernifty/biotool,supernifty/biotool,bjpop/biotool,supernifty/biotool,drpowell/biotool,biotool-paper/biotool,supernifty/biotool,lonsbio/biotool,drpowell/biotool
|
c
|
## Code Before:
typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;
#endif
## Instruction:
Correct c++ exit status values
## Code After:
typedef enum {Success=0, Error_open_file=1, Error_command_line=2, Error_parse_file=3} exit_status;
#endif
|
# ... existing code ...
typedef enum {Success=0, Error_open_file=1, Error_command_line=2, Error_parse_file=3} exit_status;
#endif
# ... rest of the code ...
|
cc0f33a51f3b13cec191a7a97d20af95082e38db
|
tests/test_utils.py
|
tests/test_utils.py
|
"""Tests for the Texcavator utility functions"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
|
"""Tests for the Texcavator utility functions"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
from nose.tools import assert_equals
from testfixtures import compare
import texcavator.utils as utils
def test_json_error_message():
response = utils.json_error_message('test')
compare(response.content, '{"status": "error", "msg": "test"}')
assert_equals(response.status_code, 200)
|
Add test for utility function json_error_message()
|
Add test for utility function json_error_message()
|
Python
|
apache-2.0
|
UUDigitalHumanitieslab/texcavator,msassmann/texcavator,msassmann/texcavator,msassmann/texcavator,UUDigitalHumanitieslab/texcavator,UUDigitalHumanitieslab/texcavator,msassmann/texcavator
|
python
|
## Code Before:
"""Tests for the Texcavator utility functions"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
## Instruction:
Add test for utility function json_error_message()
## Code After:
"""Tests for the Texcavator utility functions"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
from nose.tools import assert_equals
from testfixtures import compare
import texcavator.utils as utils
def test_json_error_message():
response = utils.json_error_message('test')
compare(response.content, '{"status": "error", "msg": "test"}')
assert_equals(response.status_code, 200)
|
// ... existing code ...
"""Tests for the Texcavator utility functions"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
from nose.tools import assert_equals
from testfixtures import compare
import texcavator.utils as utils
def test_json_error_message():
response = utils.json_error_message('test')
compare(response.content, '{"status": "error", "msg": "test"}')
assert_equals(response.status_code, 200)
// ... rest of the code ...
|
de70b1549f33484da87d6958d9f9714e7da50956
|
git_upstream_diff.py
|
git_upstream_diff.py
|
import argparse
import sys
import subprocess2
from git_common import current_branch, get_or_create_merge_base, config_list
from git_common import GIT_EXE
def main(args):
default_args = config_list('depot-tools.upstream-diff.default-args')
args = default_args + args
parser = argparse.ArgumentParser()
parser.add_argument('--wordwise', action='store_true', default=False,
help=(
'Print a colorized wordwise diff '
'instead of line-wise diff'))
opts, extra_args = parser.parse_known_args(args)
cmd = [GIT_EXE, 'diff', '--patience', '-C', '-C']
if opts.wordwise:
cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])']
cmd += [get_or_create_merge_base(current_branch())]
cmd += extra_args
subprocess2.check_call(cmd)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
import argparse
import sys
import subprocess2
import git_common as git
def main(args):
default_args = git.config_list('depot-tools.upstream-diff.default-args')
args = default_args + args
parser = argparse.ArgumentParser()
parser.add_argument('--wordwise', action='store_true', default=False,
help=(
'Print a colorized wordwise diff '
'instead of line-wise diff'))
opts, extra_args = parser.parse_known_args(args)
cur = git.current_branch()
if not cur or cur == 'HEAD':
print 'fatal: Cannot perform git-upstream-diff while not on a branch'
return 1
par = git.upstream(cur)
if not par:
print 'fatal: No upstream configured for branch \'%s\'' % cur
return 1
cmd = [git.GIT_EXE, 'diff', '--patience', '-C', '-C']
if opts.wordwise:
cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])']
cmd += [git.get_or_create_merge_base(cur, par)]
cmd += extra_args
subprocess2.check_call(cmd)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Make udiff print reasonable errors while not on a branch.
|
Make udiff print reasonable errors while not on a branch.
[email protected]
BUG=
Review URL: https://codereview.chromium.org/212493002
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@259647 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
kromain/chromium-tools,cybertk/depot_tools,npe9/depot_tools,HackFisher/depot_tools,kromain/chromium-tools,duongbaoduy/gtools,Neozaru/depot_tools,eatbyte/depot_tools,kaiix/depot_tools,fracting/depot_tools,CoherentLabs/depot_tools,kromain/chromium-tools,Chilledheart/depot_tools,Chilledheart/depot_tools,kromain/chromium-tools,ajohnson23/depot_tools,kaiix/depot_tools,azunite/chrome_build,chinmaygarde/depot_tools,xuyuhan/depot_tools,Neozaru/depot_tools,smikes/depot_tools,hsharsha/depot_tools,liaorubei/depot_tools,SuYiling/chrome_depot_tools,airtimemedia/depot_tools,npe9/depot_tools,duongbaoduy/gtools,smikes/depot_tools,eatbyte/depot_tools,Phonebooth/depot_tools,Midrya/chromium,npe9/depot_tools,Chilledheart/depot_tools,Phonebooth/depot_tools,azureplus/chromium_depot_tools,fanjunwei/depot_tools,withtone/depot_tools,michalliu/chromium-depot_tools,disigma/depot_tools,cybertk/depot_tools,mlufei/depot_tools,Chilledheart/depot_tools,HackFisher/depot_tools,xuyuhan/depot_tools,ajohnson23/depot_tools,aleonliao/depot_tools,sarvex/depot-tools,disigma/depot_tools,cybertk/depot_tools,fanjunwei/depot_tools,aleonliao/depot_tools,npe9/depot_tools,yetu/repotools,G-P-S/depot_tools,Midrya/chromium,duanwujie/depot_tools,sarvex/depot-tools,chinmaygarde/depot_tools,mlufei/depot_tools,SuYiling/chrome_depot_tools,eatbyte/depot_tools,fracting/depot_tools,chinmaygarde/depot_tools,eatbyte/depot_tools,yetu/repotools,gcodetogit/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,xuyuhan/depot_tools,primiano/depot_tools,Neozaru/depot_tools,azureplus/chromium_depot_tools,michalliu/chromium-depot_tools,liaorubei/depot_tools,SuYiling/chrome_depot_tools,CoherentLabs/depot_tools,Neozaru/depot_tools,withtone/depot_tools,Neozaru/depot_tools,fracting/depot_tools,gcodetogit/depot_tools,HackFisher/depot_tools,duanwujie/depot_tools,disigma/depot_tools,liaorubei/depot_tools,hsharsha/depot_tools,aleonliao/depot_tools,yetu/repotools,G-P-S/depot_tools,smikes/depot_tools,azunite/chrome_build,Midrya/chromium,fanjunwei/depot_tools,gcodetogit/depot_tools,Chilledheart/depot_tools,airtimemedia/depot_tools,airtimemedia/depot_tools,cybertk/depot_tools,withtone/depot_tools,liaorubei/depot_tools,duongbaoduy/gtools,michalliu/chromium-depot_tools,duanwujie/depot_tools,primiano/depot_tools,hsharsha/depot_tools,airtimemedia/depot_tools,sarvex/depot-tools,G-P-S/depot_tools,smikes/depot_tools,Phonebooth/depot_tools,mlufei/depot_tools,primiano/depot_tools,HackFisher/depot_tools,fanjunwei/depot_tools,sarvex/depot-tools,azunite/chrome_build,michalliu/chromium-depot_tools,G-P-S/depot_tools,xuyuhan/depot_tools,kaiix/depot_tools,ajohnson23/depot_tools,Phonebooth/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,azureplus/chromium_depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,cybertk/depot_tools,smikes/depot_tools
|
python
|
## Code Before:
import argparse
import sys
import subprocess2
from git_common import current_branch, get_or_create_merge_base, config_list
from git_common import GIT_EXE
def main(args):
default_args = config_list('depot-tools.upstream-diff.default-args')
args = default_args + args
parser = argparse.ArgumentParser()
parser.add_argument('--wordwise', action='store_true', default=False,
help=(
'Print a colorized wordwise diff '
'instead of line-wise diff'))
opts, extra_args = parser.parse_known_args(args)
cmd = [GIT_EXE, 'diff', '--patience', '-C', '-C']
if opts.wordwise:
cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])']
cmd += [get_or_create_merge_base(current_branch())]
cmd += extra_args
subprocess2.check_call(cmd)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
## Instruction:
Make udiff print reasonable errors while not on a branch.
[email protected]
BUG=
Review URL: https://codereview.chromium.org/212493002
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@259647 0039d316-1c4b-4281-b951-d872f2087c98
## Code After:
import argparse
import sys
import subprocess2
import git_common as git
def main(args):
default_args = git.config_list('depot-tools.upstream-diff.default-args')
args = default_args + args
parser = argparse.ArgumentParser()
parser.add_argument('--wordwise', action='store_true', default=False,
help=(
'Print a colorized wordwise diff '
'instead of line-wise diff'))
opts, extra_args = parser.parse_known_args(args)
cur = git.current_branch()
if not cur or cur == 'HEAD':
print 'fatal: Cannot perform git-upstream-diff while not on a branch'
return 1
par = git.upstream(cur)
if not par:
print 'fatal: No upstream configured for branch \'%s\'' % cur
return 1
cmd = [git.GIT_EXE, 'diff', '--patience', '-C', '-C']
if opts.wordwise:
cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])']
cmd += [git.get_or_create_merge_base(cur, par)]
cmd += extra_args
subprocess2.check_call(cmd)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
...
import subprocess2
import git_common as git
def main(args):
default_args = git.config_list('depot-tools.upstream-diff.default-args')
args = default_args + args
parser = argparse.ArgumentParser()
...
'instead of line-wise diff'))
opts, extra_args = parser.parse_known_args(args)
cur = git.current_branch()
if not cur or cur == 'HEAD':
print 'fatal: Cannot perform git-upstream-diff while not on a branch'
return 1
par = git.upstream(cur)
if not par:
print 'fatal: No upstream configured for branch \'%s\'' % cur
return 1
cmd = [git.GIT_EXE, 'diff', '--patience', '-C', '-C']
if opts.wordwise:
cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])']
cmd += [git.get_or_create_merge_base(cur, par)]
cmd += extra_args
...
|
afc18ff91bde4e6e6da554c7f9e520e5cac89fa2
|
streams.py
|
streams.py
|
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
submissions = r.get_subreddit('nbastreams').get_hot(limit=10)
for submission in submissions:
print(submission.selftext_html)
|
from bs4 import BeautifulSoup
import html
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
def get_streams_for_team(teams):
teams.append('Game Thread')
submissions = r.get_subreddit('nbastreams').get_hot(limit=20)
streams = []
for submission in submissions:
if all(team in submission.title for team in teams):
for comment in submission.comments:
soup = BeautifulSoup(
html.unescape(comment.body_html), 'html.parser')
if soup.find('a'):
streams.append(soup.find('a')['href'])
return streams
if __name__ == '__main__':
print(get_streams_for_team(['Spurs']))
|
Add comment parser; get stream links for any (2) team(s)
|
Add comment parser; get stream links for any (2) team(s)
|
Python
|
mit
|
kshvmdn/NBAScores,kshvmdn/nba.js,kshvmdn/nba-scores
|
python
|
## Code Before:
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
submissions = r.get_subreddit('nbastreams').get_hot(limit=10)
for submission in submissions:
print(submission.selftext_html)
## Instruction:
Add comment parser; get stream links for any (2) team(s)
## Code After:
from bs4 import BeautifulSoup
import html
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
def get_streams_for_team(teams):
teams.append('Game Thread')
submissions = r.get_subreddit('nbastreams').get_hot(limit=20)
streams = []
for submission in submissions:
if all(team in submission.title for team in teams):
for comment in submission.comments:
soup = BeautifulSoup(
html.unescape(comment.body_html), 'html.parser')
if soup.find('a'):
streams.append(soup.find('a')['href'])
return streams
if __name__ == '__main__':
print(get_streams_for_team(['Spurs']))
|
...
from bs4 import BeautifulSoup
import html
import praw
r = praw.Reddit(user_agent='nba_stream_parser')
def get_streams_for_team(teams):
teams.append('Game Thread')
submissions = r.get_subreddit('nbastreams').get_hot(limit=20)
streams = []
for submission in submissions:
if all(team in submission.title for team in teams):
for comment in submission.comments:
soup = BeautifulSoup(
html.unescape(comment.body_html), 'html.parser')
if soup.find('a'):
streams.append(soup.find('a')['href'])
return streams
if __name__ == '__main__':
print(get_streams_for_team(['Spurs']))
...
|
0889a48f8ebe652bccbf0c719a386ab2ced4edb2
|
edocs-secure/src/main/java/com/github/aureliano/edocs/secure/hash/PasswordHashGenerator.java
|
edocs-secure/src/main/java/com/github/aureliano/edocs/secure/hash/PasswordHashGenerator.java
|
package com.github.aureliano.edocs.secure.hash;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;
public final class PasswordHashGenerator {
private PasswordHashGenerator() {}
public static final String generate(PasswordEncryptionModel pwd) {
String text = pwd.getPassword() + pwd.getSalt();
try {
for (short i = 0; i < pwd.getHashIterations(); i++) {
text = hash(text, pwd.getAlgorithm().getLabel());
}
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
throw new SecurityException(ex);
}
return text;
}
private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"));
byte bytes[] = md.digest();
String hash = DatatypeConverter.printBase64Binary(bytes);
return hash;
}
}
|
package com.github.aureliano.edocs.secure.hash;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import com.github.aureliano.edocs.common.config.AppConfiguration;
import com.github.aureliano.edocs.common.config.ConfigurationSingleton;
import com.github.aureliano.edocs.common.config.SecureConfiguration;
import com.github.aureliano.edocs.secure.model.Algorithm;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;
public final class PasswordHashGenerator {
private PasswordHashGenerator() {}
public static final String generate(PasswordEncryptionModel pwd) {
String text = pwd.getPassword() + pwd.getSalt();
try {
for (short i = 0; i < pwd.getHashIterations(); i++) {
text = hash(text, pwd.getAlgorithm().getLabel());
}
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
throw new SecurityException(ex);
}
return text;
}
public static final String generateFromAppConfiguration(String password) {
AppConfiguration appConfiguration = ConfigurationSingleton.instance().getAppConfiguration();
SecureConfiguration configuration = appConfiguration.getSecureConfiguration();
return PasswordHashGenerator.generate(new PasswordEncryptionModel()
.withAlgorithm(Algorithm.valueOf(configuration.getAlgorithm()))
.withHashIterations(configuration.getHashIterations())
.withSalt(configuration.getSalt())
.withPassword(password));
}
private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"));
byte bytes[] = md.digest();
String hash = DatatypeConverter.printBase64Binary(bytes);
return hash;
}
}
|
Add method to generate passowrd hash with configuration properties.
|
Add method to generate passowrd hash with configuration properties.
|
Java
|
mit
|
aureliano/e-docs
|
java
|
## Code Before:
package com.github.aureliano.edocs.secure.hash;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;
public final class PasswordHashGenerator {
private PasswordHashGenerator() {}
public static final String generate(PasswordEncryptionModel pwd) {
String text = pwd.getPassword() + pwd.getSalt();
try {
for (short i = 0; i < pwd.getHashIterations(); i++) {
text = hash(text, pwd.getAlgorithm().getLabel());
}
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
throw new SecurityException(ex);
}
return text;
}
private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"));
byte bytes[] = md.digest();
String hash = DatatypeConverter.printBase64Binary(bytes);
return hash;
}
}
## Instruction:
Add method to generate passowrd hash with configuration properties.
## Code After:
package com.github.aureliano.edocs.secure.hash;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import com.github.aureliano.edocs.common.config.AppConfiguration;
import com.github.aureliano.edocs.common.config.ConfigurationSingleton;
import com.github.aureliano.edocs.common.config.SecureConfiguration;
import com.github.aureliano.edocs.secure.model.Algorithm;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;
public final class PasswordHashGenerator {
private PasswordHashGenerator() {}
public static final String generate(PasswordEncryptionModel pwd) {
String text = pwd.getPassword() + pwd.getSalt();
try {
for (short i = 0; i < pwd.getHashIterations(); i++) {
text = hash(text, pwd.getAlgorithm().getLabel());
}
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
throw new SecurityException(ex);
}
return text;
}
public static final String generateFromAppConfiguration(String password) {
AppConfiguration appConfiguration = ConfigurationSingleton.instance().getAppConfiguration();
SecureConfiguration configuration = appConfiguration.getSecureConfiguration();
return PasswordHashGenerator.generate(new PasswordEncryptionModel()
.withAlgorithm(Algorithm.valueOf(configuration.getAlgorithm()))
.withHashIterations(configuration.getHashIterations())
.withSalt(configuration.getSalt())
.withPassword(password));
}
private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"));
byte bytes[] = md.digest();
String hash = DatatypeConverter.printBase64Binary(bytes);
return hash;
}
}
|
# ... existing code ...
import javax.xml.bind.DatatypeConverter;
import com.github.aureliano.edocs.common.config.AppConfiguration;
import com.github.aureliano.edocs.common.config.ConfigurationSingleton;
import com.github.aureliano.edocs.common.config.SecureConfiguration;
import com.github.aureliano.edocs.secure.model.Algorithm;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;
public final class PasswordHashGenerator {
# ... modified code ...
return text;
}
public static final String generateFromAppConfiguration(String password) {
AppConfiguration appConfiguration = ConfigurationSingleton.instance().getAppConfiguration();
SecureConfiguration configuration = appConfiguration.getSecureConfiguration();
return PasswordHashGenerator.generate(new PasswordEncryptionModel()
.withAlgorithm(Algorithm.valueOf(configuration.getAlgorithm()))
.withHashIterations(configuration.getHashIterations())
.withSalt(configuration.getSalt())
.withPassword(password));
}
private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"));
# ... rest of the code ...
|
37715104dec586ea67b253e4e7ed35795cb5ea8c
|
track.py
|
track.py
|
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
# event = Event('API', 'Fetch', label=label, value=count)
# report('UA-68765997-3', client_id, event)
|
from google_measurement_protocol import event, report
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
data = event('API', 'Fetch', label=label, value=count)
report('UA-68765997-3', client_id, data)
|
Add google measurement protocol back
|
Add google measurement protocol back
|
Python
|
mit
|
reneepadgham/diverseui,reneepadgham/diverseui,reneepadgham/diverseui
|
python
|
## Code Before:
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
# event = Event('API', 'Fetch', label=label, value=count)
# report('UA-68765997-3', client_id, event)
## Instruction:
Add google measurement protocol back
## Code After:
from google_measurement_protocol import event, report
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
data = event('API', 'Fetch', label=label, value=count)
report('UA-68765997-3', client_id, data)
|
# ... existing code ...
from google_measurement_protocol import event, report
import uuid
# ... modified code ...
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
data = event('API', 'Fetch', label=label, value=count)
report('UA-68765997-3', client_id, data)
# ... rest of the code ...
|
08dc34df72898761e2da9c3ccdf6a7592eb8c7bf
|
src/exercise210.c
|
src/exercise210.c
|
/*
* A solution to Exercise 2-3 in The C Programming Language (Second Edition).
*
* This file was written by Damien Dart, <[email protected]>. This is free
* and unencumbered software released into the public domain. For more
* information, please refer to the accompanying "UNLICENCE" file.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int16_t lower(int16_t);
int main(void)
{
int16_t character;
while((character = getchar()) != EOF) {
putchar(lower(character));
}
return EXIT_SUCCESS;
}
int16_t lower(int16_t character)
{
return (character >= 'A' && character <= 'Z') ? character + 'a' - 'A' : character;
}
|
/*
* A solution to Exercise 2-10 in The C Programming Language (Second Edition).
*
* This file was written by Damien Dart, <[email protected]>. This is free
* and unencumbered software released into the public domain. For more
* information, please refer to the accompanying "UNLICENCE" file.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int16_t lower(int16_t);
int main(void)
{
int16_t character;
while((character = getchar()) != EOF) {
putchar(lower(character));
}
return EXIT_SUCCESS;
}
int16_t lower(int16_t character)
{
return (character >= 'A' && character <= 'Z') ? character + 'a' - 'A' : character;
}
|
Purge tabs and fix a comment.
|
Purge tabs and fix a comment.
|
C
|
unlicense
|
damiendart/knr-solutions,damiendart/knr-solutions,damiendart/knr-solutions
|
c
|
## Code Before:
/*
* A solution to Exercise 2-3 in The C Programming Language (Second Edition).
*
* This file was written by Damien Dart, <[email protected]>. This is free
* and unencumbered software released into the public domain. For more
* information, please refer to the accompanying "UNLICENCE" file.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int16_t lower(int16_t);
int main(void)
{
int16_t character;
while((character = getchar()) != EOF) {
putchar(lower(character));
}
return EXIT_SUCCESS;
}
int16_t lower(int16_t character)
{
return (character >= 'A' && character <= 'Z') ? character + 'a' - 'A' : character;
}
## Instruction:
Purge tabs and fix a comment.
## Code After:
/*
* A solution to Exercise 2-10 in The C Programming Language (Second Edition).
*
* This file was written by Damien Dart, <[email protected]>. This is free
* and unencumbered software released into the public domain. For more
* information, please refer to the accompanying "UNLICENCE" file.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int16_t lower(int16_t);
int main(void)
{
int16_t character;
while((character = getchar()) != EOF) {
putchar(lower(character));
}
return EXIT_SUCCESS;
}
int16_t lower(int16_t character)
{
return (character >= 'A' && character <= 'Z') ? character + 'a' - 'A' : character;
}
|
...
/*
* A solution to Exercise 2-10 in The C Programming Language (Second Edition).
*
* This file was written by Damien Dart, <[email protected]>. This is free
* and unencumbered software released into the public domain. For more
...
int main(void)
{
int16_t character;
while((character = getchar()) != EOF) {
putchar(lower(character));
}
return EXIT_SUCCESS;
}
int16_t lower(int16_t character)
{
return (character >= 'A' && character <= 'Z') ? character + 'a' - 'A' : character;
}
...
|
ecd43e2d3679759d2ee389b35752cb8db18c5b22
|
microdrop/microdrop.py
|
microdrop/microdrop.py
|
import update
if __name__ == '__main__':
archive_version = update.archive_version()
driver_version = update.package_version()
firmware_version = update.firmware_version()
print "archive version=", archive_version
print "driver_version=", driver_version
print "firmware_version=", firmware_version
if driver_version != archive_version:
print "updating driver to version %s..." % archive_version
if update.update_package():
print " success"
else:
print " failed"
if firmware_version != archive_version:
print "updating firmware to version %s..." % archive_version
if update.update_firmware():
print " success"
else:
print " failed"
from app import App
app = App()
|
import os
import utility
import update
if __name__ == '__main__':
# Change directory to where microdrop.py resides, so this program can be
# run from any directory.
os.chdir(utility.base_path())
archive_version = update.archive_version()
driver_version = update.package_version()
firmware_version = update.firmware_version()
print "archive version=", archive_version
print "driver_version=", driver_version
print "firmware_version=", firmware_version
if driver_version != archive_version:
print "updating driver to version %s..." % archive_version
if update.update_package():
print " success"
else:
print " failed"
if firmware_version != archive_version:
print "updating firmware to version %s..." % archive_version
if update.update_firmware():
print " success"
else:
print " failed"
from app import App
app = App()
|
Change dir to allow script to be run from anywhere
|
Change dir to allow script to be run from anywhere
|
Python
|
bsd-3-clause
|
wheeler-microfluidics/microdrop
|
python
|
## Code Before:
import update
if __name__ == '__main__':
archive_version = update.archive_version()
driver_version = update.package_version()
firmware_version = update.firmware_version()
print "archive version=", archive_version
print "driver_version=", driver_version
print "firmware_version=", firmware_version
if driver_version != archive_version:
print "updating driver to version %s..." % archive_version
if update.update_package():
print " success"
else:
print " failed"
if firmware_version != archive_version:
print "updating firmware to version %s..." % archive_version
if update.update_firmware():
print " success"
else:
print " failed"
from app import App
app = App()
## Instruction:
Change dir to allow script to be run from anywhere
## Code After:
import os
import utility
import update
if __name__ == '__main__':
# Change directory to where microdrop.py resides, so this program can be
# run from any directory.
os.chdir(utility.base_path())
archive_version = update.archive_version()
driver_version = update.package_version()
firmware_version = update.firmware_version()
print "archive version=", archive_version
print "driver_version=", driver_version
print "firmware_version=", firmware_version
if driver_version != archive_version:
print "updating driver to version %s..." % archive_version
if update.update_package():
print " success"
else:
print " failed"
if firmware_version != archive_version:
print "updating firmware to version %s..." % archive_version
if update.update_firmware():
print " success"
else:
print " failed"
from app import App
app = App()
|
...
import os
import utility
import update
if __name__ == '__main__':
# Change directory to where microdrop.py resides, so this program can be
# run from any directory.
os.chdir(utility.base_path())
archive_version = update.archive_version()
driver_version = update.package_version()
firmware_version = update.firmware_version()
...
|
945d64464857581052e18d79e62a6fde8bdecb9b
|
fabfile.py
|
fabfile.py
|
import sys
from fabric.api import local, task
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
|
import sys
from pathlib import Path
from fabric.api import local, task, lcd, env
from fabric.contrib.console import confirm
from fabric.utils import abort
src_p = Path(env.real_fabfile).parent / 'src'
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
@task
def backup():
cmd_dumpdata = 'python manage.py dumpdata '
with lcd(src_p):
local(
cmd_dumpdata + 'users.EmailUser data_sources.DataSource | '
'tee ../db_dump/user_sources.json'
)
local(
cmd_dumpdata + 'experiments | '
'tee ../db_dump/experiments.json'
)
local(
cmd_dumpdata + 'analyses.GenomeReference | '
'tee ../db_dump/genome_reference.json'
)
@task
def reborn():
with lcd(src_p.as_posix()):
db_dump_dir = Path(env.cwd, '../db_dump')
if not (
db_dump_dir.joinpath('user_sources.json').exists() and
db_dump_dir.joinpath('genome_reference.json').exists() and
db_dump_dir.joinpath('experiments.json').exists()
):
abort('Backup the import database content first!')
confirm('Destory and re-create the current database?', False)
local('dropdb biocloud')
local('createdb biocloud')
local('python manage.py migrate')
local('python manage.py loaddata ../db_dump/user_sources.json')
local('python manage.py loaddata ../db_dump/genome_reference.json')
local('python manage.py loaddata ../db_dump/experiments.json')
|
Add fab command to backup and destroy database
|
Add fab command to backup and destroy database
|
Python
|
mit
|
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
|
python
|
## Code Before:
import sys
from fabric.api import local, task
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
## Instruction:
Add fab command to backup and destroy database
## Code After:
import sys
from pathlib import Path
from fabric.api import local, task, lcd, env
from fabric.contrib.console import confirm
from fabric.utils import abort
src_p = Path(env.real_fabfile).parent / 'src'
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
@task
def backup():
cmd_dumpdata = 'python manage.py dumpdata '
with lcd(src_p):
local(
cmd_dumpdata + 'users.EmailUser data_sources.DataSource | '
'tee ../db_dump/user_sources.json'
)
local(
cmd_dumpdata + 'experiments | '
'tee ../db_dump/experiments.json'
)
local(
cmd_dumpdata + 'analyses.GenomeReference | '
'tee ../db_dump/genome_reference.json'
)
@task
def reborn():
with lcd(src_p.as_posix()):
db_dump_dir = Path(env.cwd, '../db_dump')
if not (
db_dump_dir.joinpath('user_sources.json').exists() and
db_dump_dir.joinpath('genome_reference.json').exists() and
db_dump_dir.joinpath('experiments.json').exists()
):
abort('Backup the import database content first!')
confirm('Destory and re-create the current database?', False)
local('dropdb biocloud')
local('createdb biocloud')
local('python manage.py migrate')
local('python manage.py loaddata ../db_dump/user_sources.json')
local('python manage.py loaddata ../db_dump/genome_reference.json')
local('python manage.py loaddata ../db_dump/experiments.json')
|
// ... existing code ...
import sys
from pathlib import Path
from fabric.api import local, task, lcd, env
from fabric.contrib.console import confirm
from fabric.utils import abort
src_p = Path(env.real_fabfile).parent / 'src'
@task
def start_db():
// ... modified code ...
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
@task
def backup():
cmd_dumpdata = 'python manage.py dumpdata '
with lcd(src_p):
local(
cmd_dumpdata + 'users.EmailUser data_sources.DataSource | '
'tee ../db_dump/user_sources.json'
)
local(
cmd_dumpdata + 'experiments | '
'tee ../db_dump/experiments.json'
)
local(
cmd_dumpdata + 'analyses.GenomeReference | '
'tee ../db_dump/genome_reference.json'
)
@task
def reborn():
with lcd(src_p.as_posix()):
db_dump_dir = Path(env.cwd, '../db_dump')
if not (
db_dump_dir.joinpath('user_sources.json').exists() and
db_dump_dir.joinpath('genome_reference.json').exists() and
db_dump_dir.joinpath('experiments.json').exists()
):
abort('Backup the import database content first!')
confirm('Destory and re-create the current database?', False)
local('dropdb biocloud')
local('createdb biocloud')
local('python manage.py migrate')
local('python manage.py loaddata ../db_dump/user_sources.json')
local('python manage.py loaddata ../db_dump/genome_reference.json')
local('python manage.py loaddata ../db_dump/experiments.json')
// ... rest of the code ...
|
bda9c03e40315f4050477463b715fab038a96a1e
|
examples/pystray_icon.py
|
examples/pystray_icon.py
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
from multiprocessing import Process as Thread, Queue
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
return window
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
window = run_webview()
while True:
event = queue.get()
if event == 'open':
if window.closed.is_set():
window = run_webview()
if event == 'exit':
if not window.closed.is_set():
window.destroy()
break
icon_thread.join()
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
|
Fix process spawn on Mac os, simplify logic
|
Fix process spawn on Mac os, simplify logic
|
Python
|
bsd-3-clause
|
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
|
python
|
## Code Before:
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
from multiprocessing import Process as Thread, Queue
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
return window
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
window = run_webview()
while True:
event = queue.get()
if event == 'open':
if window.closed.is_set():
window = run_webview()
if event == 'exit':
if not window.closed.is_set():
window.destroy()
break
icon_thread.join()
## Instruction:
Fix process spawn on Mac os, simplify logic
## Code After:
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
|
...
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
else:
from threading import Thread
from queue import Queue
...
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
...
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
...
|
841144ddc1c9f0b88e81a31b590ca816d5f9b45b
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name='pymongo_smart_auth',
version='0.2.0',
description='This package extends PyMongo to provide built-in smart authentication.',
url='https://github.com/PLPeeters/PyMongo-Smart-Auth',
author='Pierre-Louis Peeters',
author_email='[email protected]',
license='MIT',
packages=['pymongo_smart_auth'],
install_requires=[
'pymongo'
],
zip_safe=True)
|
from setuptools import setup
setup(name='pymongo_smart_auth',
version='0.2.0',
description='This package extends PyMongo to provide built-in smart authentication.',
url='https://github.com/PLPeeters/PyMongo-Smart-Auth',
author='Pierre-Louis Peeters',
author_email='[email protected]',
license='MIT',
packages=['pymongo_smart_auth'],
install_requires=[
'pymongo'
],
keywords=['mongo', 'pymongo', 'authentication', 'seamless'],
zip_safe=True)
|
Add keywords to package info
|
Add keywords to package info
|
Python
|
mit
|
PLPeeters/PyMongo-Smart-Auth,PLPeeters/PyMongo-Smart-Auth
|
python
|
## Code Before:
from setuptools import setup
setup(name='pymongo_smart_auth',
version='0.2.0',
description='This package extends PyMongo to provide built-in smart authentication.',
url='https://github.com/PLPeeters/PyMongo-Smart-Auth',
author='Pierre-Louis Peeters',
author_email='[email protected]',
license='MIT',
packages=['pymongo_smart_auth'],
install_requires=[
'pymongo'
],
zip_safe=True)
## Instruction:
Add keywords to package info
## Code After:
from setuptools import setup
setup(name='pymongo_smart_auth',
version='0.2.0',
description='This package extends PyMongo to provide built-in smart authentication.',
url='https://github.com/PLPeeters/PyMongo-Smart-Auth',
author='Pierre-Louis Peeters',
author_email='[email protected]',
license='MIT',
packages=['pymongo_smart_auth'],
install_requires=[
'pymongo'
],
keywords=['mongo', 'pymongo', 'authentication', 'seamless'],
zip_safe=True)
|
# ... existing code ...
install_requires=[
'pymongo'
],
keywords=['mongo', 'pymongo', 'authentication', 'seamless'],
zip_safe=True)
# ... rest of the code ...
|
707fb2cabcfa9886c968e81964b59995c0b0f2b6
|
python/convert_line_endings.py
|
python/convert_line_endings.py
|
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
Convert line endings for .h, .c and .cpp files as well as .cs
|
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs
|
Python
|
bsd-3-clause
|
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
|
python
|
## Code Before:
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
## Instruction:
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs
## Code After:
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
...
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
...
|
3496b7c14db3da5977a1f63c3bef346549189826
|
src/main/java/com/vaguehope/onosendai/util/HashHelper.java
|
src/main/java/com/vaguehope/onosendai/util/HashHelper.java
|
package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5String (final String s) {
final MessageDigest md = MD_MD5_FACTORY.get();
md.update(getBytes(s), 0, s.length());
return new BigInteger(1, md.digest());
}
private static byte[] getBytes (final String s) {
try {
return s.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* MessageDigest.getInstance("MD5") can take up to a second, so using this
* to cache it and improve performance.
*/
private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
@Override
protected MessageDigest initialValue () {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
return md;
}
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("JVM is missing MD5.", e);
}
}
};
}
|
package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5String (final String s) {
final MessageDigest md = MD_MD5_FACTORY.get();
md.update(getBytes(s));
return new BigInteger(1, md.digest());
}
private static byte[] getBytes (final String s) {
try {
return s.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* MessageDigest.getInstance("MD5") can take up to a second, so using this
* to cache it and improve performance.
*/
private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
@Override
protected MessageDigest initialValue () {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
return md;
}
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("JVM is missing MD5.", e);
}
}
};
}
|
Fix possible issue when MD5ing multibyte strings.
|
Fix possible issue when MD5ing multibyte strings.
|
Java
|
apache-2.0
|
haku/Onosendai,haku/Onosendai
|
java
|
## Code Before:
package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5String (final String s) {
final MessageDigest md = MD_MD5_FACTORY.get();
md.update(getBytes(s), 0, s.length());
return new BigInteger(1, md.digest());
}
private static byte[] getBytes (final String s) {
try {
return s.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* MessageDigest.getInstance("MD5") can take up to a second, so using this
* to cache it and improve performance.
*/
private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
@Override
protected MessageDigest initialValue () {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
return md;
}
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("JVM is missing MD5.", e);
}
}
};
}
## Instruction:
Fix possible issue when MD5ing multibyte strings.
## Code After:
package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5String (final String s) {
final MessageDigest md = MD_MD5_FACTORY.get();
md.update(getBytes(s));
return new BigInteger(1, md.digest());
}
private static byte[] getBytes (final String s) {
try {
return s.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* MessageDigest.getInstance("MD5") can take up to a second, so using this
* to cache it and improve performance.
*/
private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
@Override
protected MessageDigest initialValue () {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
return md;
}
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("JVM is missing MD5.", e);
}
}
};
}
|
// ... existing code ...
public static BigInteger md5String (final String s) {
final MessageDigest md = MD_MD5_FACTORY.get();
md.update(getBytes(s));
return new BigInteger(1, md.digest());
}
// ... rest of the code ...
|
37a0cb41a88114ab9edb514e29447756b0c3e92a
|
tests/test_cli.py
|
tests/test_cli.py
|
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result = runner.invoke(main, [version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
|
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
|
Use cli_runner fixture in test
|
Use cli_runner fixture in test
|
Python
|
bsd-3-clause
|
hackebrot/cibopath
|
python
|
## Code Before:
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result = runner.invoke(main, [version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
## Instruction:
Use cli_runner fixture in test
## Code After:
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
|
// ... existing code ...
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
// ... modified code ...
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
// ... rest of the code ...
|
609864faf36b9a82db9fd63d28b5a0da7a22c4f5
|
eforge/__init__.py
|
eforge/__init__.py
|
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 0, 'beta 1')
def get_version():
return '%d.%d.%d %s' % VERSION
|
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION
|
Change master version information to 0.5.99 (git master)
|
Change master version information to 0.5.99 (git master)
Todo: We should probably add the smarts to EForge to grab the git
revision for master, at least if Dulwich is installed :-)
|
Python
|
isc
|
oshepherd/eforge,oshepherd/eforge,oshepherd/eforge
|
python
|
## Code Before:
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 0, 'beta 1')
def get_version():
return '%d.%d.%d %s' % VERSION
## Instruction:
Change master version information to 0.5.99 (git master)
Todo: We should probably add the smarts to EForge to grab the git
revision for master, at least if Dulwich is installed :-)
## Code After:
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION
|
# ... existing code ...
},
}
VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION
# ... rest of the code ...
|
e01571fb8c29b78f16c34bfcd2d806b183224047
|
opps/containers/forms.py
|
opps/containers/forms.py
|
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
if settings.OPPS_MIRROR_CHANNEL:
self.field['mirror_channel'] = forms.CharField(
widget=forms.HiddenInput(), required=False)
|
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
if not settings.OPPS_MIRROR_CHANNEL:
self.fields['mirror_channel'].widget = forms.HiddenInput()
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
|
Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false
|
Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false
|
Python
|
mit
|
opps/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps
|
python
|
## Code Before:
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
if settings.OPPS_MIRROR_CHANNEL:
self.field['mirror_channel'] = forms.CharField(
widget=forms.HiddenInput(), required=False)
## Instruction:
Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false
## Code After:
from django import forms
from django.conf import settings
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
if not settings.OPPS_MIRROR_CHANNEL:
self.fields['mirror_channel'].widget = forms.HiddenInput()
self.fields['json'] = JSONFormField(
widget=JSONField(
attrs={'_model': self._meta.model.__name__}),
required=False)
for field in Field.objects.filter(application__contains=
self._meta.model.__name__):
if field.type == 'checkbox':
for fo in FieldOption.objects.filter(field=field):
self.fields[
'json_{}_{}'.format(
field.slug, fo.option.slug
)] = forms.CharField(required=False)
else:
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
|
...
class ContainerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContainerAdminForm, self).__init__(*args, **kwargs)
if not settings.OPPS_MIRROR_CHANNEL:
self.fields['mirror_channel'].widget = forms.HiddenInput()
self.fields['json'] = JSONFormField(
widget=JSONField(
...
self.fields[
'json_{}'.format(field.slug)
] = forms.CharField(required=False)
...
|
1af1a7acface58cd8a6df5671d83b0a1a3ad4f3e
|
tiddlywebplugins/tiddlyspace/config.py
|
tiddlywebplugins/tiddlyspace/config.py
|
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME),
'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20',
'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'],
'bag_create_policy': 'ANY',
'recipe_create_policy': 'ANY',
'css_uri': '/bags/common/tiddlers/tiddlyweb.css',
'socialusers.reserved_names': ['www', 'about', 'help', 'announcements',
'dev', 'info', 'api', 'status', 'login', 'frontpage'],
'cookie_age': '2592000', # 1 month
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
}
|
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME),
'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20',
'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'],
'bag_create_policy': 'ANY',
'recipe_create_policy': 'ANY',
'css_uri': '/bags/common/tiddlers/tiddlyweb.css',
'socialusers.reserved_names': ['www', 'about', 'help', 'announcements',
'dev', 'info', 'api', 'status', 'login', 'frontpage'],
'cookie_age': '2592000', # 1 month
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
'tiddlywebwiki.binary_limit': 1048576, # 1MB
}
|
Set the tiddlywebwiki binary limit to 1MB.
|
Set the tiddlywebwiki binary limit to 1MB.
|
Python
|
bsd-3-clause
|
FND/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,TiddlySpace/tiddlyspace
|
python
|
## Code Before:
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME),
'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20',
'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'],
'bag_create_policy': 'ANY',
'recipe_create_policy': 'ANY',
'css_uri': '/bags/common/tiddlers/tiddlyweb.css',
'socialusers.reserved_names': ['www', 'about', 'help', 'announcements',
'dev', 'info', 'api', 'status', 'login', 'frontpage'],
'cookie_age': '2592000', # 1 month
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
}
## Instruction:
Set the tiddlywebwiki binary limit to 1MB.
## Code After:
from tiddlywebplugins.instancer.util import get_tiddler_locations
from tiddlywebplugins.tiddlyspace.instance import store_contents
PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
config = {
'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME),
'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20',
'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'],
'bag_create_policy': 'ANY',
'recipe_create_policy': 'ANY',
'css_uri': '/bags/common/tiddlers/tiddlyweb.css',
'socialusers.reserved_names': ['www', 'about', 'help', 'announcements',
'dev', 'info', 'api', 'status', 'login', 'frontpage'],
'cookie_age': '2592000', # 1 month
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
'tiddlywebwiki.binary_limit': 1048576, # 1MB
}
|
// ... existing code ...
'server_store': ['tiddlywebplugins.mysql', {
'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}],
'indexer': 'tiddlywebplugins.mysql',
'tiddlywebwiki.binary_limit': 1048576, # 1MB
}
// ... rest of the code ...
|
d9d9270f0577a6969f7cb2ccf48a8c0aa859b44a
|
circular-buffer/circular_buffer.py
|
circular-buffer/circular_buffer.py
|
class CircularBuffer(object):
def __init__(self, size_max):
self.max = bytearray(size_max) # bytearray represents a mutable sequence of bytes.
self.read_head, self.write_head = 0
|
class CircularBuffer(object):
def __init__(self, size_max):
self.maxBuffer = bytearray(size_max) # bytearray represents a mutable sequence of bytes.
self.readHead, self.writeHead = 0
def insert_data(self, value):
self.maxBuffer[self.writeHead] = value
def clean(self):
self.maxBuffer = bytearray(len(self.maxBuffer))
|
Add functions to insert and clear data
|
Add functions to insert and clear data
|
Python
|
mit
|
amalshehu/exercism-python
|
python
|
## Code Before:
class CircularBuffer(object):
def __init__(self, size_max):
self.max = bytearray(size_max) # bytearray represents a mutable sequence of bytes.
self.read_head, self.write_head = 0
## Instruction:
Add functions to insert and clear data
## Code After:
class CircularBuffer(object):
def __init__(self, size_max):
self.maxBuffer = bytearray(size_max) # bytearray represents a mutable sequence of bytes.
self.readHead, self.writeHead = 0
def insert_data(self, value):
self.maxBuffer[self.writeHead] = value
def clean(self):
self.maxBuffer = bytearray(len(self.maxBuffer))
|
// ... existing code ...
class CircularBuffer(object):
def __init__(self, size_max):
self.maxBuffer = bytearray(size_max) # bytearray represents a mutable sequence of bytes.
self.readHead, self.writeHead = 0
def insert_data(self, value):
self.maxBuffer[self.writeHead] = value
def clean(self):
self.maxBuffer = bytearray(len(self.maxBuffer))
// ... rest of the code ...
|
b7c52258d39e5c0ee8fba2be87e8e671e0c583c3
|
xclib/postfix_io.py
|
xclib/postfix_io.py
|
import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if not line:
break
match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line)
if match:
yield ('isuser',) + match.group(1,2)
else:
logging.error('Illegal request format: ' + line)
outfd.write('500 Illegal request format\n')
outfd.flush()
@classmethod
def write_response(cls, flag, outfd):
if flag == None:
outfd.write('400 Trouble connecting to backend\n')
elif flag:
outfd.write('200 OK\n')
else:
outfd.write('500 No such user\n')
outfd.flush()
|
import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if not line:
break
match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line)
if match:
yield ('isuser',) + match.group(1,2)
elif line == 'quit':
yield ('quit',)
else:
logging.error('Illegal request format: ' + line)
outfd.write('500 Illegal request format\n')
outfd.flush()
@classmethod
def write_response(cls, flag, outfd):
if flag == None:
outfd.write('400 Trouble connecting to backend\n')
elif flag:
outfd.write('200 OK\n')
else:
outfd.write('500 No such user\n')
outfd.flush()
|
Add quit command to postfix
|
Add quit command to postfix
|
Python
|
mit
|
jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth
|
python
|
## Code Before:
import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if not line:
break
match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line)
if match:
yield ('isuser',) + match.group(1,2)
else:
logging.error('Illegal request format: ' + line)
outfd.write('500 Illegal request format\n')
outfd.flush()
@classmethod
def write_response(cls, flag, outfd):
if flag == None:
outfd.write('400 Trouble connecting to backend\n')
elif flag:
outfd.write('200 OK\n')
else:
outfd.write('500 No such user\n')
outfd.flush()
## Instruction:
Add quit command to postfix
## Code After:
import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if not line:
break
match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line)
if match:
yield ('isuser',) + match.group(1,2)
elif line == 'quit':
yield ('quit',)
else:
logging.error('Illegal request format: ' + line)
outfd.write('500 Illegal request format\n')
outfd.flush()
@classmethod
def write_response(cls, flag, outfd):
if flag == None:
outfd.write('400 Trouble connecting to backend\n')
elif flag:
outfd.write('200 OK\n')
else:
outfd.write('500 No such user\n')
outfd.flush()
|
...
match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line)
if match:
yield ('isuser',) + match.group(1,2)
elif line == 'quit':
yield ('quit',)
else:
logging.error('Illegal request format: ' + line)
outfd.write('500 Illegal request format\n')
...
|
a9e41de1f8c765d44d6f38eed561a591e6a00cc9
|
app/src/main/java/chat/rocket/android/util/extensions/Animation.kt
|
app/src/main/java/chat/rocket/android/util/extensions/Animation.kt
|
package chat.rocket.android.util.extensions
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
fun View.rotateBy(value: Float, duration: Long = 200) {
animate()
.rotationBy(value)
.setDuration(duration)
.start()
}
fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
if (startValue > finishValue) {
setVisible(false)
} else {
setVisible(true)
}
}
fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) {
val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius)
anim.duration = duration
if (startRadius < endRadius) {
setVisible(true)
} else {
setVisible(false)
}
anim.start()
}
|
package chat.rocket.android.util.extensions
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
fun View.rotateBy(value: Float, duration: Long = 200) {
animate()
.rotationBy(value)
.setDuration(duration)
.start()
}
fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(true)
}
fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(false)
}
fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) {
val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius)
anim.duration = duration
if (startRadius < endRadius) {
setVisible(true)
} else {
setVisible(false)
}
anim.start()
}
|
Add function fadeIn and fadeOut (instead of having fadeInOrOut(...))
|
Add function fadeIn and fadeOut (instead of having fadeInOrOut(...))
|
Kotlin
|
mit
|
RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android
|
kotlin
|
## Code Before:
package chat.rocket.android.util.extensions
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
fun View.rotateBy(value: Float, duration: Long = 200) {
animate()
.rotationBy(value)
.setDuration(duration)
.start()
}
fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
if (startValue > finishValue) {
setVisible(false)
} else {
setVisible(true)
}
}
fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) {
val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius)
anim.duration = duration
if (startRadius < endRadius) {
setVisible(true)
} else {
setVisible(false)
}
anim.start()
}
## Instruction:
Add function fadeIn and fadeOut (instead of having fadeInOrOut(...))
## Code After:
package chat.rocket.android.util.extensions
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
fun View.rotateBy(value: Float, duration: Long = 200) {
animate()
.rotationBy(value)
.setDuration(duration)
.start()
}
fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(true)
}
fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(false)
}
fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) {
val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius)
anim.duration = duration
if (startRadius < endRadius) {
setVisible(true)
} else {
setVisible(false)
}
anim.start()
}
|
...
.start()
}
fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
...
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(true)
}
fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) {
animate()
.alpha(startValue)
.setDuration(duration)
.setInterpolator(DecelerateInterpolator())
.withEndAction({
animate()
.alpha(finishValue)
.setDuration(duration)
.setInterpolator(AccelerateInterpolator()).start()
}).start()
setVisible(false)
}
fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) {
...
|
10efd969a9653db0737df98d99b2df176ffc0c7f
|
code_samples/simple_language_plugin/src/com/simpleplugin/SimpleFileTypeFactory.java
|
code_samples/simple_language_plugin/src/com/simpleplugin/SimpleFileTypeFactory.java
|
package com.simpleplugin;
import com.intellij.openapi.fileTypes.*;
import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple");
}
}
|
package com.simpleplugin;
import com.intellij.openapi.fileTypes.*;
import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE);
}
}
|
Remove passing a file extension explicitly.
|
Remove passing a file extension explicitly.
Hello!
In this code, the `SimpleFileType` instance passed as the first argument and the `"simple"` file extension as the second parameter.
As far as I can see in FileTypeManagerImpl:263:
```java
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
```
There is no need to declare it explicitly as it is taken by calling `SimpleFileType.#getDefaultExtension()` by default, so this parameter is redundant.
To make tutorial more simple, I suggest this removal: seeing the second parameter is a bit confusing when we're passing the same value, returned from `getDefaultExtension()`.
Since the tutorial shows the basics, not a flexibility of an API, the parameter can be removed.
Thanks!
|
Java
|
apache-2.0
|
artspb/intellij-sdk-docs,JetBrains/intellij-sdk-docs,artspb/intellij-sdk-docs,artspb/intellij-sdk-docs,JetBrains/intellij-sdk-docs,JetBrains/intellij-sdk-docs,artspb/intellij-sdk-docs
|
java
|
## Code Before:
package com.simpleplugin;
import com.intellij.openapi.fileTypes.*;
import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple");
}
}
## Instruction:
Remove passing a file extension explicitly.
Hello!
In this code, the `SimpleFileType` instance passed as the first argument and the `"simple"` file extension as the second parameter.
As far as I can see in FileTypeManagerImpl:263:
```java
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
```
There is no need to declare it explicitly as it is taken by calling `SimpleFileType.#getDefaultExtension()` by default, so this parameter is redundant.
To make tutorial more simple, I suggest this removal: seeing the second parameter is a bit confusing when we're passing the same value, returned from `getDefaultExtension()`.
Since the tutorial shows the basics, not a flexibility of an API, the parameter can be removed.
Thanks!
## Code After:
package com.simpleplugin;
import com.intellij.openapi.fileTypes.*;
import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE);
}
}
|
# ... existing code ...
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE);
}
}
# ... rest of the code ...
|
42d282fd4f4dc53389fe62eba8b934cb7174acf0
|
include/lldb/lldb-python.h
|
include/lldb/lldb-python.h
|
//===-- lldb-python.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_lldb_python_h_
#define LLDB_lldb_python_h_
// Python.h needs to be included before any system headers in order to avoid redefinition of macros
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#include <Python/Python.h>
#endif // LLDB_DISABLE_PYTHON
#endif // LLDB_lldb_python_h_
|
//===-- lldb-python.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_lldb_python_h_
#define LLDB_lldb_python_h_
// Python.h needs to be included before any system headers in order to avoid redefinition of macros
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#ifdef __FreeBSD__
#include <Python.h>
#else
#include <Python/Python.h>
#endif
#endif // LLDB_DISABLE_PYTHON
#endif // LLDB_lldb_python_h_
|
Fix build on FreeBSD after r196141
|
Fix build on FreeBSD after r196141
This should probably be replaced with build infrastructure support for
a platform-specific canonical Python include path, but for now it should
restore the FreeBSD buildbot.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@196167 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
|
c
|
## Code Before:
//===-- lldb-python.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_lldb_python_h_
#define LLDB_lldb_python_h_
// Python.h needs to be included before any system headers in order to avoid redefinition of macros
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#include <Python/Python.h>
#endif // LLDB_DISABLE_PYTHON
#endif // LLDB_lldb_python_h_
## Instruction:
Fix build on FreeBSD after r196141
This should probably be replaced with build infrastructure support for
a platform-specific canonical Python include path, but for now it should
restore the FreeBSD buildbot.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@196167 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
//===-- lldb-python.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_lldb_python_h_
#define LLDB_lldb_python_h_
// Python.h needs to be included before any system headers in order to avoid redefinition of macros
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#ifdef __FreeBSD__
#include <Python.h>
#else
#include <Python/Python.h>
#endif
#endif // LLDB_DISABLE_PYTHON
#endif // LLDB_lldb_python_h_
|
# ... existing code ...
#else
#ifdef __FreeBSD__
#include <Python.h>
#else
#include <Python/Python.h>
#endif
#endif // LLDB_DISABLE_PYTHON
# ... rest of the code ...
|
07d3a2e8775954db8f887c8c084b857976b02d34
|
src/main/java/in/twizmwaz/cardinal/module/modules/filter/type/logic/AnyFilter.java
|
src/main/java/in/twizmwaz/cardinal/module/modules/filter/type/logic/AnyFilter.java
|
package in.twizmwaz.cardinal.module.modules.filter.type.logic;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW;
public class AnyFilter extends FilterModule {
private final ModuleCollection<FilterModule> children;
public AnyFilter(final String name, final ModuleCollection<FilterModule> children) {
super(name);
this.children = children;
}
@Override
public FilterState evaluate(final Object object) {
for (FilterModule child : children) {
if (child.evaluate(object).equals(ALLOW)) return ALLOW;
}
return ALLOW;
}
}
|
package in.twizmwaz.cardinal.module.modules.filter.type.logic;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.DENY;
public class AnyFilter extends FilterModule {
private final ModuleCollection<FilterModule> children;
public AnyFilter(final String name, final ModuleCollection<FilterModule> children) {
super(name);
this.children = children;
}
@Override
public FilterState evaluate(final Object object) {
for (FilterModule child : children) {
if (child.evaluate(object).equals(ALLOW)) return ALLOW;
}
return DENY;
}
}
|
Fix logic in any logic filter
|
Fix logic in any logic filter
|
Java
|
mit
|
Alan736/NotCardinalPGM,Alan736/NotCardinalPGM,iPGz/CardinalPGM,twizmwazin/CardinalPGM,angelitorb99/CardinalPGM,CaptainElliott/CardinalPGM,Aaron1011/CardinalPGM,dentmaged/Cardinal-Plus,dentmaged/Cardinal-Dev,Electroid/ExperimentalPGM,Electroid/ExperimentalPGM,TheMolkaPL/CardinalPGM,dentmaged/CardinalPGM,Pablete1234/CardinalPGM,dentmaged/CardinalPGM,SungMatt/CardinalPGM,TheMolkaPL/CardinalPGM,dentmaged/Cardinal-Dev,dentmaged/Cardinal-Plus
|
java
|
## Code Before:
package in.twizmwaz.cardinal.module.modules.filter.type.logic;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW;
public class AnyFilter extends FilterModule {
private final ModuleCollection<FilterModule> children;
public AnyFilter(final String name, final ModuleCollection<FilterModule> children) {
super(name);
this.children = children;
}
@Override
public FilterState evaluate(final Object object) {
for (FilterModule child : children) {
if (child.evaluate(object).equals(ALLOW)) return ALLOW;
}
return ALLOW;
}
}
## Instruction:
Fix logic in any logic filter
## Code After:
package in.twizmwaz.cardinal.module.modules.filter.type.logic;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.DENY;
public class AnyFilter extends FilterModule {
private final ModuleCollection<FilterModule> children;
public AnyFilter(final String name, final ModuleCollection<FilterModule> children) {
super(name);
this.children = children;
}
@Override
public FilterState evaluate(final Object object) {
for (FilterModule child : children) {
if (child.evaluate(object).equals(ALLOW)) return ALLOW;
}
return DENY;
}
}
|
# ... existing code ...
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW;
import static in.twizmwaz.cardinal.module.modules.filter.FilterState.DENY;
public class AnyFilter extends FilterModule {
# ... modified code ...
for (FilterModule child : children) {
if (child.evaluate(object).equals(ALLOW)) return ALLOW;
}
return DENY;
}
}
# ... rest of the code ...
|
b7335f5c011d9fad3570a097fb1165cc6fbd3cef
|
src/python/grpcio_tests/tests/unit/_logging_test.py
|
src/python/grpcio_tests/tests/unit/_logging_test.py
|
"""Test of gRPC Python's interaction with the python logging module"""
import unittest
import six
import grpc
import logging
class LoggingTest(unittest.TestCase):
def test_logger_not_occupied(self):
self.assertEqual(0, len(logging.getLogger().handlers))
if __name__ == '__main__':
unittest.main(verbosity=2)
|
"""Test of gRPC Python's interaction with the python logging module"""
import unittest
import six
from six.moves import reload_module
import logging
import grpc
import functools
import sys
class LoggingTest(unittest.TestCase):
def test_logger_not_occupied(self):
self.assertEqual(0, len(logging.getLogger().handlers))
def test_handler_found(self):
old_stderr = sys.stderr
sys.stderr = six.StringIO()
try:
reload_module(logging)
logging.basicConfig()
reload_module(grpc)
self.assertFalse("No handlers could be found" in sys.stderr.getvalue())
finally:
sys.stderr = old_stderr
reload_module(logging)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Add test for 'No handlers could be found' problem
|
Add test for 'No handlers could be found' problem
|
Python
|
apache-2.0
|
mehrdada/grpc,sreecha/grpc,stanley-cheung/grpc,vjpai/grpc,mehrdada/grpc,muxi/grpc,pszemus/grpc,stanley-cheung/grpc,jtattermusch/grpc,donnadionne/grpc,grpc/grpc,mehrdada/grpc,pszemus/grpc,ctiller/grpc,nicolasnoble/grpc,firebase/grpc,donnadionne/grpc,ctiller/grpc,jtattermusch/grpc,donnadionne/grpc,vjpai/grpc,muxi/grpc,donnadionne/grpc,grpc/grpc,vjpai/grpc,carl-mastrangelo/grpc,carl-mastrangelo/grpc,stanley-cheung/grpc,ctiller/grpc,jboeuf/grpc,donnadionne/grpc,ejona86/grpc,jboeuf/grpc,carl-mastrangelo/grpc,carl-mastrangelo/grpc,ctiller/grpc,nicolasnoble/grpc,grpc/grpc,pszemus/grpc,stanley-cheung/grpc,sreecha/grpc,jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,nicolasnoble/grpc,nicolasnoble/grpc,nicolasnoble/grpc,grpc/grpc,pszemus/grpc,carl-mastrangelo/grpc,mehrdada/grpc,nicolasnoble/grpc,grpc/grpc,jtattermusch/grpc,pszemus/grpc,muxi/grpc,carl-mastrangelo/grpc,ctiller/grpc,vjpai/grpc,grpc/grpc,ctiller/grpc,jtattermusch/grpc,sreecha/grpc,vjpai/grpc,firebase/grpc,donnadionne/grpc,sreecha/grpc,donnadionne/grpc,muxi/grpc,grpc/grpc,muxi/grpc,sreecha/grpc,pszemus/grpc,vjpai/grpc,firebase/grpc,grpc/grpc,jboeuf/grpc,jboeuf/grpc,carl-mastrangelo/grpc,firebase/grpc,ejona86/grpc,pszemus/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,ejona86/grpc,vjpai/grpc,ejona86/grpc,vjpai/grpc,vjpai/grpc,mehrdada/grpc,pszemus/grpc,muxi/grpc,jtattermusch/grpc,jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,mehrdada/grpc,ctiller/grpc,grpc/grpc,ejona86/grpc,pszemus/grpc,jtattermusch/grpc,firebase/grpc,ejona86/grpc,firebase/grpc,nicolasnoble/grpc,firebase/grpc,ejona86/grpc,nicolasnoble/grpc,mehrdada/grpc,firebase/grpc,donnadionne/grpc,stanley-cheung/grpc,pszemus/grpc,jboeuf/grpc,donnadionne/grpc,vjpai/grpc,donnadionne/grpc,mehrdada/grpc,ctiller/grpc,muxi/grpc,vjpai/grpc,pszemus/grpc,stanley-cheung/grpc,jboeuf/grpc,mehrdada/grpc,carl-mastrangelo/grpc,jtattermusch/grpc,carl-mastrangelo/grpc,mehrdada/grpc,muxi/grpc,jboeuf/grpc,ctiller/grpc,mehrdada/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,ejona86/grpc,ejona86/grpc,mehrdada/grpc,muxi/grpc,muxi/grpc,pszemus/grpc,donnadionne/grpc,nicolasnoble/grpc,sreecha/grpc,jboeuf/grpc,sreecha/grpc,carl-mastrangelo/grpc,jtattermusch/grpc,donnadionne/grpc,ctiller/grpc,firebase/grpc,vjpai/grpc,carl-mastrangelo/grpc,jboeuf/grpc,firebase/grpc,jtattermusch/grpc,jtattermusch/grpc,muxi/grpc,grpc/grpc,sreecha/grpc,sreecha/grpc,ejona86/grpc,grpc/grpc,sreecha/grpc,stanley-cheung/grpc,firebase/grpc,muxi/grpc,stanley-cheung/grpc,jboeuf/grpc,jboeuf/grpc,sreecha/grpc,nicolasnoble/grpc,grpc/grpc,firebase/grpc,sreecha/grpc,ejona86/grpc,nicolasnoble/grpc,jboeuf/grpc
|
python
|
## Code Before:
"""Test of gRPC Python's interaction with the python logging module"""
import unittest
import six
import grpc
import logging
class LoggingTest(unittest.TestCase):
def test_logger_not_occupied(self):
self.assertEqual(0, len(logging.getLogger().handlers))
if __name__ == '__main__':
unittest.main(verbosity=2)
## Instruction:
Add test for 'No handlers could be found' problem
## Code After:
"""Test of gRPC Python's interaction with the python logging module"""
import unittest
import six
from six.moves import reload_module
import logging
import grpc
import functools
import sys
class LoggingTest(unittest.TestCase):
def test_logger_not_occupied(self):
self.assertEqual(0, len(logging.getLogger().handlers))
def test_handler_found(self):
old_stderr = sys.stderr
sys.stderr = six.StringIO()
try:
reload_module(logging)
logging.basicConfig()
reload_module(grpc)
self.assertFalse("No handlers could be found" in sys.stderr.getvalue())
finally:
sys.stderr = old_stderr
reload_module(logging)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
# ... existing code ...
import unittest
import six
from six.moves import reload_module
import logging
import grpc
import functools
import sys
class LoggingTest(unittest.TestCase):
# ... modified code ...
def test_logger_not_occupied(self):
self.assertEqual(0, len(logging.getLogger().handlers))
def test_handler_found(self):
old_stderr = sys.stderr
sys.stderr = six.StringIO()
try:
reload_module(logging)
logging.basicConfig()
reload_module(grpc)
self.assertFalse("No handlers could be found" in sys.stderr.getvalue())
finally:
sys.stderr = old_stderr
reload_module(logging)
if __name__ == '__main__':
unittest.main(verbosity=2)
# ... rest of the code ...
|
582edd6bd36e8b40a37a8aaaa013704b5cd73ad6
|
dotbot/config.py
|
dotbot/config.py
|
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
print ext
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
|
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
|
Fix compatibility with Python 3
|
Fix compatibility with Python 3
This patch removes a stray print statement that was causing problems
with Python 3.
|
Python
|
mit
|
bchretien/dotbot,imattman/dotbot,imattman/dotbot,anishathalye/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot,imattman/dotbot
|
python
|
## Code Before:
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
print ext
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
## Instruction:
Fix compatibility with Python 3
This patch removes a stray print statement that was causing problems
with Python 3.
## Code After:
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
|
...
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
else:
...
|
747f8b50fbd8330dda39f3d64cea5b4dfe35c65c
|
src/java/com/threerings/presents/net/BootstrapData.java
|
src/java/com/threerings/presents/net/BootstrapData.java
|
//
// $Id: BootstrapData.java,v 1.1 2001/07/19 07:09:16 mdb Exp $
package com.threerings.cocktail.cher.net;
import com.threerings.cocktail.cher.dobj.DObject;
/**
* An <code>BootstrapData</code> object is communicated back to the client
* after authentication has succeeded and after the server is fully
* prepared to deal with the client. It contains information the client
* will need to interact with the server.
*/
public class BootstrapData extends DObject
{
/** The oid of this client's associated distributed object. */
public int clientOid;
/** The oid to which to send invocation requests. */
public int invOid;
public String toString ()
{
return "[clientOid=" + clientOid + ", invOid=" + invOid + "]";
}
}
|
//
// $Id: BootstrapData.java,v 1.2 2001/10/09 18:17:52 mdb Exp $
package com.threerings.cocktail.cher.net;
import com.threerings.cocktail.cher.dobj.DObject;
/**
* A <code>BootstrapData</code> object is communicated back to the client
* after authentication has succeeded and after the server is fully
* prepared to deal with the client. It contains information the client
* will need to interact with the server.
*/
public class BootstrapData extends DObject
{
/** The oid of this client's associated distributed object. */
public int clientOid;
/** The oid to which to send invocation requests. */
public int invOid;
// documentation inherited
public void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", clientOid=").append(clientOid);
buf.append(", invOid=").append(invOid);
}
}
|
Use the proper toString() method.
|
Use the proper toString() method.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@413 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
Java
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
java
|
## Code Before:
//
// $Id: BootstrapData.java,v 1.1 2001/07/19 07:09:16 mdb Exp $
package com.threerings.cocktail.cher.net;
import com.threerings.cocktail.cher.dobj.DObject;
/**
* An <code>BootstrapData</code> object is communicated back to the client
* after authentication has succeeded and after the server is fully
* prepared to deal with the client. It contains information the client
* will need to interact with the server.
*/
public class BootstrapData extends DObject
{
/** The oid of this client's associated distributed object. */
public int clientOid;
/** The oid to which to send invocation requests. */
public int invOid;
public String toString ()
{
return "[clientOid=" + clientOid + ", invOid=" + invOid + "]";
}
}
## Instruction:
Use the proper toString() method.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@413 542714f4-19e9-0310-aa3c-eee0fc999fb1
## Code After:
//
// $Id: BootstrapData.java,v 1.2 2001/10/09 18:17:52 mdb Exp $
package com.threerings.cocktail.cher.net;
import com.threerings.cocktail.cher.dobj.DObject;
/**
* A <code>BootstrapData</code> object is communicated back to the client
* after authentication has succeeded and after the server is fully
* prepared to deal with the client. It contains information the client
* will need to interact with the server.
*/
public class BootstrapData extends DObject
{
/** The oid of this client's associated distributed object. */
public int clientOid;
/** The oid to which to send invocation requests. */
public int invOid;
// documentation inherited
public void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", clientOid=").append(clientOid);
buf.append(", invOid=").append(invOid);
}
}
|
// ... existing code ...
//
// $Id: BootstrapData.java,v 1.2 2001/10/09 18:17:52 mdb Exp $
package com.threerings.cocktail.cher.net;
// ... modified code ...
import com.threerings.cocktail.cher.dobj.DObject;
/**
* A <code>BootstrapData</code> object is communicated back to the client
* after authentication has succeeded and after the server is fully
* prepared to deal with the client. It contains information the client
* will need to interact with the server.
...
/** The oid to which to send invocation requests. */
public int invOid;
// documentation inherited
public void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", clientOid=").append(clientOid);
buf.append(", invOid=").append(invOid);
}
}
// ... rest of the code ...
|
a7fdc9f834dec480236c397c03e7b929e74ccd80
|
shuup/default_reports/mixins.py
|
shuup/default_reports/mixins.py
|
from django.db.models import Q
from shuup.core.models import Order
class OrderReportMixin(object):
def get_objects(self):
queryset = Order.objects.filter(
shop=self.shop,
order_date__range=(self.start_date, self.end_date))
creator = self.options.get("creator")
orderer = self.options.get("orderer")
customer = self.options.get("customer")
filters = Q()
if creator:
filters &= Q(creator__in=creator)
if orderer:
filters &= Q(orderer__in=orderer)
if customer:
filters &= Q(customer__in=customer)
return queryset.filter(filters).valid().paid().order_by("order_date")
|
from datetime import timedelta
from django.db.models import Q
from shuup.core.models import Order
from shuup.utils.dates import to_aware
class OrderReportMixin(object):
def get_objects(self):
start = to_aware(self.start_date) # 0:00 on start_date
end = to_aware(self.end_date) + timedelta(days=1) # 24:00 on end_date
queryset = Order.objects.filter(
shop=self.shop, order_date__range=(start, end))
creator = self.options.get("creator")
orderer = self.options.get("orderer")
customer = self.options.get("customer")
filters = Q()
if creator:
filters &= Q(creator__in=creator)
if orderer:
filters &= Q(orderer__in=orderer)
if customer:
filters &= Q(customer__in=customer)
return queryset.filter(filters).valid().paid().order_by("order_date")
|
Include orders which are made during selected end date in reports
|
Include orders which are made during selected end date in reports
Comparing DateTimeField with date causes lack of precision which
can occur with range. This causes orders which order_date is
the same date than end_date will be not included in the queryset.
Fix this problem with adding one extra day to the end_date value
and so order made during the selected end date will be also included
in the reports.
|
Python
|
agpl-3.0
|
shoopio/shoop,shoopio/shoop,shoopio/shoop
|
python
|
## Code Before:
from django.db.models import Q
from shuup.core.models import Order
class OrderReportMixin(object):
def get_objects(self):
queryset = Order.objects.filter(
shop=self.shop,
order_date__range=(self.start_date, self.end_date))
creator = self.options.get("creator")
orderer = self.options.get("orderer")
customer = self.options.get("customer")
filters = Q()
if creator:
filters &= Q(creator__in=creator)
if orderer:
filters &= Q(orderer__in=orderer)
if customer:
filters &= Q(customer__in=customer)
return queryset.filter(filters).valid().paid().order_by("order_date")
## Instruction:
Include orders which are made during selected end date in reports
Comparing DateTimeField with date causes lack of precision which
can occur with range. This causes orders which order_date is
the same date than end_date will be not included in the queryset.
Fix this problem with adding one extra day to the end_date value
and so order made during the selected end date will be also included
in the reports.
## Code After:
from datetime import timedelta
from django.db.models import Q
from shuup.core.models import Order
from shuup.utils.dates import to_aware
class OrderReportMixin(object):
def get_objects(self):
start = to_aware(self.start_date) # 0:00 on start_date
end = to_aware(self.end_date) + timedelta(days=1) # 24:00 on end_date
queryset = Order.objects.filter(
shop=self.shop, order_date__range=(start, end))
creator = self.options.get("creator")
orderer = self.options.get("orderer")
customer = self.options.get("customer")
filters = Q()
if creator:
filters &= Q(creator__in=creator)
if orderer:
filters &= Q(orderer__in=orderer)
if customer:
filters &= Q(customer__in=customer)
return queryset.filter(filters).valid().paid().order_by("order_date")
|
# ... existing code ...
from datetime import timedelta
from django.db.models import Q
from shuup.core.models import Order
from shuup.utils.dates import to_aware
class OrderReportMixin(object):
def get_objects(self):
start = to_aware(self.start_date) # 0:00 on start_date
end = to_aware(self.end_date) + timedelta(days=1) # 24:00 on end_date
queryset = Order.objects.filter(
shop=self.shop, order_date__range=(start, end))
creator = self.options.get("creator")
orderer = self.options.get("orderer")
customer = self.options.get("customer")
# ... rest of the code ...
|
6e96905b97bbb3c154a15e90b3dc3d118db7c96e
|
src/OI.h
|
src/OI.h
|
class OI
{
private:
Joystick joystick;
public:
OI();
inline float GetXplusY(){
float val;
val = FractionOmitted(joystick.GetY() + joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetXminusY(){
float val;
val = FractionOmitted(joystick.GetY() - joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetStickX(){ return FractionOmitted(joystick.GetX()); }
inline float GetStickY(){ return FractionOmitted(joystick.GetY()); }
inline float GetStickTwist(){ return FractionOmitted(joystick.GetTwist()); }
inline float GetStickThrottle(){ return FractionOmitted(joystick.GetThrottle()); }
inline float FractionOmitted(float original){
if(fabsf(original) < 0.01 ){
original = 0;
}
return original;
}
};
#endif
|
class OI
{
private:
Joystick joystick;
public:
OI();
inline float GetXplusY(){
float val;
val = FractionOmitted(joystick.GetY() + joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetXminusY(){
float val;
val = FractionOmitted(joystick.GetY() - joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetStickX(){ return FractionOmitted(joystick.GetX()); }
inline float GetStickY(){ return FractionOmitted(joystick.GetY()); }
inline float GetStickTwist(){ return FractionOmitted(joystick.GetTwist()); }
inline float GetStickThrottle(){ return FractionOmitted(joystick.GetThrottle()); }
inline float GetStickRightX(){ return FractionOmitted(joystick.GetRawAxis(5)); }
inline float GetStcikRightY(){ return FractionOmitted(joystick.GetRawAxis(6)); }
inline float FractionOmitted(float original){
if(fabsf(original) < 0.01 ){
original = 0;
}
return original;
}
};
#endif
|
Create RightStick X and Y value get Function
|
Create RightStick X and Y value get Function
|
C
|
epl-1.0
|
tokyotechnicalsamurai/shougun
|
c
|
## Code Before:
class OI
{
private:
Joystick joystick;
public:
OI();
inline float GetXplusY(){
float val;
val = FractionOmitted(joystick.GetY() + joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetXminusY(){
float val;
val = FractionOmitted(joystick.GetY() - joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetStickX(){ return FractionOmitted(joystick.GetX()); }
inline float GetStickY(){ return FractionOmitted(joystick.GetY()); }
inline float GetStickTwist(){ return FractionOmitted(joystick.GetTwist()); }
inline float GetStickThrottle(){ return FractionOmitted(joystick.GetThrottle()); }
inline float FractionOmitted(float original){
if(fabsf(original) < 0.01 ){
original = 0;
}
return original;
}
};
#endif
## Instruction:
Create RightStick X and Y value get Function
## Code After:
class OI
{
private:
Joystick joystick;
public:
OI();
inline float GetXplusY(){
float val;
val = FractionOmitted(joystick.GetY() + joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetXminusY(){
float val;
val = FractionOmitted(joystick.GetY() - joystick.GetX());
if(val > 1.2) val = 1.2;
if(val < -1.2) val = -1.2;
return val;
}
inline float GetStickX(){ return FractionOmitted(joystick.GetX()); }
inline float GetStickY(){ return FractionOmitted(joystick.GetY()); }
inline float GetStickTwist(){ return FractionOmitted(joystick.GetTwist()); }
inline float GetStickThrottle(){ return FractionOmitted(joystick.GetThrottle()); }
inline float GetStickRightX(){ return FractionOmitted(joystick.GetRawAxis(5)); }
inline float GetStcikRightY(){ return FractionOmitted(joystick.GetRawAxis(6)); }
inline float FractionOmitted(float original){
if(fabsf(original) < 0.01 ){
original = 0;
}
return original;
}
};
#endif
|
// ... existing code ...
inline float GetStickY(){ return FractionOmitted(joystick.GetY()); }
inline float GetStickTwist(){ return FractionOmitted(joystick.GetTwist()); }
inline float GetStickThrottle(){ return FractionOmitted(joystick.GetThrottle()); }
inline float GetStickRightX(){ return FractionOmitted(joystick.GetRawAxis(5)); }
inline float GetStcikRightY(){ return FractionOmitted(joystick.GetRawAxis(6)); }
inline float FractionOmitted(float original){
if(fabsf(original) < 0.01 ){
// ... rest of the code ...
|
fa6c2c43289eeee1c0efab45101149b49be1b5cb
|
scrapi/processing/osf/__init__.py
|
scrapi/processing/osf/__init__.py
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
if not resource:
resource = crud.create_resource(resource_norm, resource_hash)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
if not report:
report = crud.create_report(report_norm, resource, report_hash)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
crud.update_node(report, report_norm)
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
found, _hash = collision.already_processed(raw_doc)
if found:
return
normalized['meta'] = {
'docHash': _hash
}
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
report_norm['meta']['uids'] = report_hash
resource_norm['meta']['uids'] = resource_hash
if not resource:
resource = crud.create_resource(resource_norm)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
crud.update_node(report, report_norm)
if not report:
report = crud.create_report(report_norm, resource)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
|
Update dumping to osf logic
|
Update dumping to osf logic
|
Python
|
apache-2.0
|
ostwald/scrapi,mehanig/scrapi,felliott/scrapi,alexgarciac/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,jeffreyliu3230/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi
|
python
|
## Code Before:
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
if not resource:
resource = crud.create_resource(resource_norm, resource_hash)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
if not report:
report = crud.create_report(report_norm, resource, report_hash)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
crud.update_node(report, report_norm)
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
## Instruction:
Update dumping to osf logic
## Code After:
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
found, _hash = collision.already_processed(raw_doc)
if found:
return
normalized['meta'] = {
'docHash': _hash
}
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
report_norm['meta']['uids'] = report_hash
resource_norm['meta']['uids'] = resource_hash
if not resource:
resource = crud.create_resource(resource_norm)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
crud.update_node(report, report_norm)
if not report:
report = crud.create_report(report_norm, resource)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
|
...
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
found, _hash = collision.already_processed(raw_doc)
if found:
return
normalized['meta'] = {
'docHash': _hash
}
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
...
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
report_norm['meta']['uids'] = report_hash
resource_norm['meta']['uids'] = resource_hash
if not resource:
resource = crud.create_resource(resource_norm)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
crud.update_node(report, report_norm)
if not report:
report = crud.create_report(report_norm, resource)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
...
|
2b33ac168c6e252e441f9b0a547d2bf18c153984
|
Squirrel/SQRLInstaller+Private.h
|
Squirrel/SQRLInstaller+Private.h
|
//
// SQRLInstaller+Private.h
// Squirrel
//
// Created by Justin Spahr-Summers on 2013-11-19.
// Copyright (c) 2013 GitHub. All rights reserved.
//
#import "SQRLInstaller.h"
// A preferences key for the URL where the target bundle has been moved before
// installation.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from rewriting the URL during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedTargetBundleURLKey;
// A preferences key for the URL where the update bundle has been moved before
// installation.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from rewriting the URL during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedUpdateBundleURLKey;
// A preferences key for the code signature that the update _and_ target bundles
// must match in order to be valid.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from spoofing the validity requirements.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerCodeSignatureKey;
|
//
// SQRLInstaller+Private.h
// Squirrel
//
// Created by Justin Spahr-Summers on 2013-11-19.
// Copyright (c) 2013 GitHub. All rights reserved.
//
#import "SQRLInstaller.h"
// A preferences key for the URL where the target bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedTargetBundleURLKey;
// A preferences key for the URL where the update bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedUpdateBundleURLKey;
// A preferences key for the code signature that the update _and_ target bundles
// must match in order to be valid.
//
// This is stored in preferences to prevent an attacker from spoofing the
// validity requirements.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerCodeSignatureKey;
|
Update docs to reflect that the root prefs aren’t opposed to shipit state
|
Update docs to reflect that the root prefs aren’t opposed to shipit state
ShipIt state is now in the prefs too.
|
C
|
mit
|
EdZava/Squirrel.Mac,EdZava/Squirrel.Mac,Squirrel/Squirrel.Mac,emiscience/Squirrel.Mac,EdZava/Squirrel.Mac,Squirrel/Squirrel.Mac,emiscience/Squirrel.Mac,emiscience/Squirrel.Mac,Squirrel/Squirrel.Mac
|
c
|
## Code Before:
//
// SQRLInstaller+Private.h
// Squirrel
//
// Created by Justin Spahr-Summers on 2013-11-19.
// Copyright (c) 2013 GitHub. All rights reserved.
//
#import "SQRLInstaller.h"
// A preferences key for the URL where the target bundle has been moved before
// installation.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from rewriting the URL during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedTargetBundleURLKey;
// A preferences key for the URL where the update bundle has been moved before
// installation.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from rewriting the URL during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedUpdateBundleURLKey;
// A preferences key for the code signature that the update _and_ target bundles
// must match in order to be valid.
//
// This is stored in preferences, rather than `SQRLShipItState`, to prevent an
// attacker from spoofing the validity requirements.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerCodeSignatureKey;
## Instruction:
Update docs to reflect that the root prefs aren’t opposed to shipit state
ShipIt state is now in the prefs too.
## Code After:
//
// SQRLInstaller+Private.h
// Squirrel
//
// Created by Justin Spahr-Summers on 2013-11-19.
// Copyright (c) 2013 GitHub. All rights reserved.
//
#import "SQRLInstaller.h"
// A preferences key for the URL where the target bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedTargetBundleURLKey;
// A preferences key for the URL where the update bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerOwnedUpdateBundleURLKey;
// A preferences key for the code signature that the update _and_ target bundles
// must match in order to be valid.
//
// This is stored in preferences to prevent an attacker from spoofing the
// validity requirements.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
extern NSString * const SQRLInstallerCodeSignatureKey;
|
...
// A preferences key for the URL where the target bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
...
// A preferences key for the URL where the update bundle has been moved before
// installation.
//
// This is stored in preferences to prevent an attacker from rewriting the URL
// during the installation process.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
...
// A preferences key for the code signature that the update _and_ target bundles
// must match in order to be valid.
//
// This is stored in preferences to prevent an attacker from spoofing the
// validity requirements.
//
// Note that this key must remain backwards compatible, so ShipIt doesn't fail
// confusingly on a newer version.
...
|
f551d23531ec4aab041494ac8af921eb77d6b2a0
|
nb_conda/__init__.py
|
nb_conda/__init__.py
|
from ._version import version_info, __version__
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'nbextension/static',
'dest': 'nb_conda',
'require': 'nb_conda/main'
}]
def _jupyter_server_extension_paths():
return [{
'require': 'nb_conda.nbextension'
}]
|
from ._version import version_info, __version__
def _jupyter_nbextension_paths():
return [dict(section="notebook",
src="nbextension/static",
dest="nb_conda",
require="nb_conda/main")]
def _jupyter_server_extension_paths():
return [dict(module='nb_conda.nbextension')]
|
Update to the latest way to offer metadata
|
Update to the latest way to offer metadata
|
Python
|
bsd-3-clause
|
Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda
|
python
|
## Code Before:
from ._version import version_info, __version__
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'nbextension/static',
'dest': 'nb_conda',
'require': 'nb_conda/main'
}]
def _jupyter_server_extension_paths():
return [{
'require': 'nb_conda.nbextension'
}]
## Instruction:
Update to the latest way to offer metadata
## Code After:
from ._version import version_info, __version__
def _jupyter_nbextension_paths():
return [dict(section="notebook",
src="nbextension/static",
dest="nb_conda",
require="nb_conda/main")]
def _jupyter_server_extension_paths():
return [dict(module='nb_conda.nbextension')]
|
# ... existing code ...
from ._version import version_info, __version__
def _jupyter_nbextension_paths():
return [dict(section="notebook",
src="nbextension/static",
dest="nb_conda",
require="nb_conda/main")]
def _jupyter_server_extension_paths():
return [dict(module='nb_conda.nbextension')]
# ... rest of the code ...
|
7d4b2af132001927ea42b69650b6b45301ee335f
|
astrobin/management/commands/notify_new_blog_entry.py
|
astrobin/management/commands/notify_new_blog_entry.py
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from zinnia.models import Entry
from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.all()[0]
push_notification(
User.objects.all(),
'new_blog_entry',
{
'object': entry.title,
'object_url': entry.get_absolute_url()
}
)
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.all()[0]
for u in User.objects.all():
m = persistent_messages.models.Message(
user = u,
from_user = User.objects.get(username = 'astrobin'),
message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>',
level = persistent_messages.INFO,
)
m.save()
|
Fix management command to send notification about new blog post.
|
Fix management command to send notification about new blog post.
|
Python
|
agpl-3.0
|
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
|
python
|
## Code Before:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from zinnia.models import Entry
from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.all()[0]
push_notification(
User.objects.all(),
'new_blog_entry',
{
'object': entry.title,
'object_url': entry.get_absolute_url()
}
)
## Instruction:
Fix management command to send notification about new blog post.
## Code After:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.all()[0]
for u in User.objects.all():
m = persistent_messages.models.Message(
user = u,
from_user = User.objects.get(username = 'astrobin'),
message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>',
level = persistent_messages.INFO,
)
m.save()
|
...
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
...
def handle(self, *args, **options):
entry = Entry.objects.all()[0]
for u in User.objects.all():
m = persistent_messages.models.Message(
user = u,
from_user = User.objects.get(username = 'astrobin'),
message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>',
level = persistent_messages.INFO,
)
m.save()
...
|
7165c34338fcb1f5b81a736837af04b3fee6deff
|
src/main/java/abra/Options.java
|
src/main/java/abra/Options.java
|
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.IOException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* Abstract base class for helping with options parsing.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public abstract class Options {
protected static final String HELP = "help";
private OptionSet options;
protected void printHelp() {
try {
getOptionParser().printHelpOn(System.err);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException encountered when attempting to output help.");
}
}
public void parseOptions(String[] args) {
try {
options = getOptionParser().parse(args);
if (options.has(HELP)) {
printHelp();
} else {
init();
validate();
}
} catch (joptsimple.OptionException e) {
System.err.println(e.getMessage());
printHelp();
}
}
protected OptionSet getOptions() {
return options;
}
abstract protected OptionParser getOptionParser();
abstract protected void validate();
protected void init() {
}
}
|
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.IOException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* Abstract base class for helping with options parsing.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public abstract class Options {
protected static final String HELP = "help";
private OptionSet options;
protected void printHelp() {
try {
getOptionParser().printHelpOn(System.err);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException encountered when attempting to output help.");
}
}
public void parseOptions(String[] args) {
try {
options = getOptionParser().parse(args);
if (options.has(HELP)) {
printHelp();
} else {
init();
validate();
}
} catch (joptsimple.OptionException e) {
System.err.println(e.getMessage());
printHelp();
throw e;
}
}
protected OptionSet getOptions() {
return options;
}
abstract protected OptionParser getOptionParser();
abstract protected void validate();
protected void init() {
}
}
|
Allow param exception to trickle up.
|
Allow param exception to trickle up.
|
Java
|
mit
|
mozack/abra2,mozack/abra2,mozack/abra2,mozack/abra2
|
java
|
## Code Before:
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.IOException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* Abstract base class for helping with options parsing.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public abstract class Options {
protected static final String HELP = "help";
private OptionSet options;
protected void printHelp() {
try {
getOptionParser().printHelpOn(System.err);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException encountered when attempting to output help.");
}
}
public void parseOptions(String[] args) {
try {
options = getOptionParser().parse(args);
if (options.has(HELP)) {
printHelp();
} else {
init();
validate();
}
} catch (joptsimple.OptionException e) {
System.err.println(e.getMessage());
printHelp();
}
}
protected OptionSet getOptions() {
return options;
}
abstract protected OptionParser getOptionParser();
abstract protected void validate();
protected void init() {
}
}
## Instruction:
Allow param exception to trickle up.
## Code After:
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.IOException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* Abstract base class for helping with options parsing.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public abstract class Options {
protected static final String HELP = "help";
private OptionSet options;
protected void printHelp() {
try {
getOptionParser().printHelpOn(System.err);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException encountered when attempting to output help.");
}
}
public void parseOptions(String[] args) {
try {
options = getOptionParser().parse(args);
if (options.has(HELP)) {
printHelp();
} else {
init();
validate();
}
} catch (joptsimple.OptionException e) {
System.err.println(e.getMessage());
printHelp();
throw e;
}
}
protected OptionSet getOptions() {
return options;
}
abstract protected OptionParser getOptionParser();
abstract protected void validate();
protected void init() {
}
}
|
# ... existing code ...
} catch (joptsimple.OptionException e) {
System.err.println(e.getMessage());
printHelp();
throw e;
}
}
# ... rest of the code ...
|
2da5453ec13221c663f1898a55f65de6aa4d9d74
|
commons/src/main/java/org/wikimedia/commons/contributions/ContributionViewHolder.java
|
commons/src/main/java/org/wikimedia/commons/contributions/ContributionViewHolder.java
|
package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final ImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (ImageView)parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
|
package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.MediaWikiImageView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final MediaWikiImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
|
Make the ImageView to be of the specific type
|
Make the ImageView to be of the specific type
Change-Id: I51ced26ea0b654457919d915e322d91eb211f781
|
Java
|
apache-2.0
|
nicolas-raoul/apps-android-commons,domdomegg/apps-android-commons,misaochan/apps-android-commons,chaosbastler/apps-android-commons,tobias47n9e/apps-android-commons,chaosbastler/apps-android-commons,johnjohndoe/apps-android-commons,dbrant/apps-android-commons,psh/apps-android-commons,neslihanturan/apps-android-commons,misaochan/apps-android-commons,maskaravivek/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,whym/apps-android-commons,maskaravivek/apps-android-commons,sandarumk/apps-android-commons,dbrant/apps-android-commons,misaochan/apps-android-commons,akaita/apps-android-commons,neslihanturan/apps-android-commons,commons-app/apps-android-commons,tobias47n9e/apps-android-commons,maskaravivek/apps-android-commons,RSBat/apps-android-commons,sandarumk/apps-android-commons,commons-app/apps-android-commons,wikimedia/apps-android-commons,johnjohndoe/apps-android-commons,johnjohndoe/apps-android-commons,commons-app/apps-android-commons,whym/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,johnjohndoe/apps-android-commons,neslihanturan/apps-android-commons,dbrant/apps-android-commons,wikimedia/apps-android-commons,whym/apps-android-commons,neslihanturan/apps-android-commons,neslihanturan/apps-android-commons,akaita/apps-android-commons,tobias47n9e/apps-android-commons,RSBat/apps-android-commons,nicolas-raoul/apps-android-commons,maskaravivek/apps-android-commons,maskaravivek/apps-android-commons,nicolas-raoul/apps-android-commons,whym/apps-android-commons,psh/apps-android-commons,sandarumk/apps-android-commons,dbrant/apps-android-commons,misaochan/apps-android-commons,chaosbastler/apps-android-commons,misaochan/apps-android-commons,domdomegg/apps-android-commons,RSBat/apps-android-commons,wikimedia/apps-android-commons,domdomegg/apps-android-commons,nicolas-raoul/apps-android-commons,domdomegg/apps-android-commons,misaochan/apps-android-commons,akaita/apps-android-commons
|
java
|
## Code Before:
package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final ImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (ImageView)parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
## Instruction:
Make the ImageView to be of the specific type
Change-Id: I51ced26ea0b654457919d915e322d91eb211f781
## Code After:
package org.wikimedia.commons.contributions;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.MediaWikiImageView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final MediaWikiImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
final ProgressBar progressView;
String url;
ContributionViewHolder(View parent) {
imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}
|
// ... existing code ...
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.wikimedia.commons.MediaWikiImageView;
import org.wikimedia.commons.R;
class ContributionViewHolder {
final MediaWikiImageView imageView;
final TextView titleView;
final TextView stateView;
final TextView seqNumView;
// ... modified code ...
String url;
ContributionViewHolder(View parent) {
imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
// ... rest of the code ...
|
c4bcbc49fa1418c085b0b10a836d42e5c69faa01
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="[email protected]",
license="Apache 2.0",
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: System :: Hardware",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
],
keywords=["hardware adders prefix"],
package_dir={"": "src"},
packages=["pptrees"],
package_data={"pptrees": ["mappings/*.v"]},
long_description=open("README.md").read(),
python_requires=">=3.7.*",
install_requires=["networkx", "pydot", "graphviz"],
)
|
from setuptools import setup, find_namespace_packages
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="[email protected]",
license="Apache 2.0",
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: System :: Hardware",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
],
keywords=["hardware adders prefix"],
package_dir={"": "src"},
packages=find_namespace_packages(where="src"),
package_data={"pptrees": ["mappings/*.v"]},
long_description=open("README.md").read(),
python_requires=">=3.7.*",
install_requires=["networkx", "pydot", "graphviz"],
)
|
Apply same fix as in 77a463b50a
|
Apply same fix as in 77a463b50a
Signed-off-by: Teodor-Dumitru Ene <[email protected]>
|
Python
|
apache-2.0
|
tdene/synth_opt_adders
|
python
|
## Code Before:
from setuptools import setup
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="[email protected]",
license="Apache 2.0",
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: System :: Hardware",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
],
keywords=["hardware adders prefix"],
package_dir={"": "src"},
packages=["pptrees"],
package_data={"pptrees": ["mappings/*.v"]},
long_description=open("README.md").read(),
python_requires=">=3.7.*",
install_requires=["networkx", "pydot", "graphviz"],
)
## Instruction:
Apply same fix as in 77a463b50a
Signed-off-by: Teodor-Dumitru Ene <[email protected]>
## Code After:
from setuptools import setup, find_namespace_packages
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="[email protected]",
license="Apache 2.0",
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: System :: Hardware",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
],
keywords=["hardware adders prefix"],
package_dir={"": "src"},
packages=find_namespace_packages(where="src"),
package_data={"pptrees": ["mappings/*.v"]},
long_description=open("README.md").read(),
python_requires=">=3.7.*",
install_requires=["networkx", "pydot", "graphviz"],
)
|
...
from setuptools import setup, find_namespace_packages
setup(
name="pptrees",
...
],
keywords=["hardware adders prefix"],
package_dir={"": "src"},
packages=find_namespace_packages(where="src"),
package_data={"pptrees": ["mappings/*.v"]},
long_description=open("README.md").read(),
python_requires=">=3.7.*",
...
|
b44345efada2a89423c89ec88a24f1dbe97ef562
|
viewer.py
|
viewer.py
|
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
Add simple test for whether WX is installed. Display download link if not.
|
Add simple test for whether WX is installed. Display download link if not.
|
Python
|
agpl-3.0
|
nccgroup/lapith
|
python
|
## Code Before:
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
## Instruction:
Add simple test for whether WX is installed. Display download link if not.
## Code After:
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
// ... existing code ...
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
// ... rest of the code ...
|
a8571b066634b7e7cbeb35844e1ee0b0d678112c
|
tests/test_itunes.py
|
tests/test_itunes.py
|
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript
from itunes.exceptions import AppleScriptError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
|
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript, play_track
from itunes.exceptions import AppleScriptError, TrackError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
def test_play_track(self):
self.assertRaises(TrackError, play_track, "~~~~---`-`-`")
|
Add test for `play_track` function
|
Add test for `play_track` function
New tests make sure that `play_track` raises a TrackError when an
invalid track is requested.
|
Python
|
mit
|
adanoff/iTunesTUI
|
python
|
## Code Before:
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript
from itunes.exceptions import AppleScriptError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
## Instruction:
Add test for `play_track` function
New tests make sure that `play_track` raises a TrackError when an
invalid track is requested.
## Code After:
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript, play_track
from itunes.exceptions import AppleScriptError, TrackError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
def test_play_track(self):
self.assertRaises(TrackError, play_track, "~~~~---`-`-`")
|
// ... existing code ...
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript, play_track
from itunes.exceptions import AppleScriptError, TrackError
class ITunesTests(unittest.TestCase):
"""
// ... modified code ...
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
def test_play_track(self):
self.assertRaises(TrackError, play_track, "~~~~---`-`-`")
// ... rest of the code ...
|
6267fa5d9a3ff2573dc33a23d3456942976b0b7e
|
cyder/base/models.py
|
cyder/base/models.py
|
from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTimeField(auto_now_add=True, null=True)
modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'created'
@classproperty
@classmethod
def pretty_type(cls):
return cls.__name__.lower()
@property
def pretty_name(self):
return unicode(self)
def unique_error_message(self, model_class, unique_check):
error = super(BaseModel, self).unique_error_message(
model_class, unique_check)
kwargs = {}
for field in unique_check:
kwargs[field] = getattr(self, field)
obj = model_class.objects.filter(**kwargs)
if obj and hasattr(obj.get(), 'get_detail_url'):
error = error[:-1] + ' at <a href={0}>{1}.</a>'.format(
obj.get().get_detail_url(), obj.get())
error = mark_safe(error)
return error
class ExpirableMixin(models.Model):
expire = models.DateTimeField(null=True, blank=True)
class Meta:
abstract = True
|
from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTimeField(auto_now_add=True, null=True)
modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'created'
@classproperty
@classmethod
def pretty_type(cls):
return cls.__name__.lower()
@property
def pretty_name(self):
return unicode(self)
def unique_error_message(self, model_class, unique_check):
error = super(BaseModel, self).unique_error_message(
model_class, unique_check)
kwargs = {}
for field in unique_check:
kwargs[field] = getattr(self, field)
obj = model_class.objects.filter(**kwargs)
if obj and hasattr(obj.get(), 'get_detail_url'):
error = error[:-1] + ' at <a href={0}>{1}.</a>'.format(
obj.get().get_detail_url(), obj.get())
error = mark_safe(error)
return error
class ExpirableMixin(models.Model):
expire = models.DateTimeField(null=True, blank=True,
help_text='Format: MM/DD/YYYY')
class Meta:
abstract = True
|
Add help_text to interface 'expire' field
|
Add help_text to interface 'expire' field
|
Python
|
bsd-3-clause
|
OSU-Net/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,akeym/cyder
|
python
|
## Code Before:
from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTimeField(auto_now_add=True, null=True)
modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'created'
@classproperty
@classmethod
def pretty_type(cls):
return cls.__name__.lower()
@property
def pretty_name(self):
return unicode(self)
def unique_error_message(self, model_class, unique_check):
error = super(BaseModel, self).unique_error_message(
model_class, unique_check)
kwargs = {}
for field in unique_check:
kwargs[field] = getattr(self, field)
obj = model_class.objects.filter(**kwargs)
if obj and hasattr(obj.get(), 'get_detail_url'):
error = error[:-1] + ' at <a href={0}>{1}.</a>'.format(
obj.get().get_detail_url(), obj.get())
error = mark_safe(error)
return error
class ExpirableMixin(models.Model):
expire = models.DateTimeField(null=True, blank=True)
class Meta:
abstract = True
## Instruction:
Add help_text to interface 'expire' field
## Code After:
from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTimeField(auto_now_add=True, null=True)
modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'created'
@classproperty
@classmethod
def pretty_type(cls):
return cls.__name__.lower()
@property
def pretty_name(self):
return unicode(self)
def unique_error_message(self, model_class, unique_check):
error = super(BaseModel, self).unique_error_message(
model_class, unique_check)
kwargs = {}
for field in unique_check:
kwargs[field] = getattr(self, field)
obj = model_class.objects.filter(**kwargs)
if obj and hasattr(obj.get(), 'get_detail_url'):
error = error[:-1] + ' at <a href={0}>{1}.</a>'.format(
obj.get().get_detail_url(), obj.get())
error = mark_safe(error)
return error
class ExpirableMixin(models.Model):
expire = models.DateTimeField(null=True, blank=True,
help_text='Format: MM/DD/YYYY')
class Meta:
abstract = True
|
...
class ExpirableMixin(models.Model):
expire = models.DateTimeField(null=True, blank=True,
help_text='Format: MM/DD/YYYY')
class Meta:
abstract = True
...
|
6ad4796030aab2f6dbf8389b4030007d0fcf8761
|
panoptes/test/mount/test_ioptron.py
|
panoptes/test/mount/test_ioptron.py
|
from nose.tools import raises
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@raises(AssertionError)
def test_config_no_commands(self):
""" """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands=dict())
|
from nose.tools import raises
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@raises(AssertionError)
def test_config_bad_commands(self):
""" Passes in a default config but blank commands, which should error """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'})
def test_config_auto_commands(self):
""" Passes in config like above, but no commands, so they should read from defaults """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } })
|
Update to test for mount setup
|
Update to test for mount setup
|
Python
|
mit
|
Guokr1991/POCS,joshwalawender/POCS,AstroHuntsman/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,Guokr1991/POCS,Guokr1991/POCS,Guokr1991/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,AstroHuntsman/POCS,fmin2958/POCS,joshwalawender/POCS,fmin2958/POCS,fmin2958/POCS
|
python
|
## Code Before:
from nose.tools import raises
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@raises(AssertionError)
def test_config_no_commands(self):
""" """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands=dict())
## Instruction:
Update to test for mount setup
## Code After:
from nose.tools import raises
import panoptes
from panoptes.mount.ioptron import Mount
class TestIOptron():
@raises(AssertionError)
def test_no_config_no_commands(self):
""" Mount needs a config """
mount = Mount()
@raises(AssertionError)
def test_config_bad_commands(self):
""" Passes in a default config but blank commands, which should error """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'})
def test_config_auto_commands(self):
""" Passes in config like above, but no commands, so they should read from defaults """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } })
|
...
mount = Mount()
@raises(AssertionError)
def test_config_bad_commands(self):
""" Passes in a default config but blank commands, which should error """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'})
def test_config_auto_commands(self):
""" Passes in config like above, but no commands, so they should read from defaults """
mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } })
...
|
0d42aa0158bb4f13098bdb5341bead9b1d7c686a
|
__init__.py
|
__init__.py
|
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
|
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
if (not 'created' in kwargs) or (not kwargs['created']):
return
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
|
Make sure to send email only when a new user is created
|
Make sure to send email only when a new user is created
|
Python
|
agpl-3.0
|
kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu
|
python
|
## Code Before:
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
## Instruction:
Make sure to send email only when a new user is created
## Code After:
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
if (not 'created' in kwargs) or (not kwargs['created']):
return
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
|
...
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
if (not 'created' in kwargs) or (not kwargs['created']):
return
user = instance
subject = u"New user '%s' created" % (user.username)
...
|
4ec16018192c1bd8fbe60a9e4c410c6c898149f0
|
server/ec2spotmanager/migrations/0007_instance_type_to_list.py
|
server/ec2spotmanager/migrations/0007_instance_type_to_list.py
|
from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
pool.ec2_instance_types_list = [pool.ec2_instance_types]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
migrations.RunPython(instance_types_to_list),
]
|
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_type:
pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
pool.save()
def instance_type_from_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_types:
types = json.loads(pool.ec2_instance_types)
if len(types) > 1:
print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
file=sys.stderr)
pool.ec2_instance_types = types[0]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RunPython(
code=instance_type_to_list,
reverse_code=instance_type_from_list,
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
]
|
Fix migration. Custom triggers are not run in data migrations.
|
Fix migration. Custom triggers are not run in data migrations.
|
Python
|
mpl-2.0
|
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
pool.ec2_instance_types_list = [pool.ec2_instance_types]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
migrations.RunPython(instance_types_to_list),
]
## Instruction:
Fix migration. Custom triggers are not run in data migrations.
## Code After:
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_type:
pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
pool.save()
def instance_type_from_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_types:
types = json.loads(pool.ec2_instance_types)
if len(types) > 1:
print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
file=sys.stderr)
pool.ec2_instance_types = types[0]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RunPython(
code=instance_type_to_list,
reverse_code=instance_type_from_list,
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
]
|
// ... existing code ...
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_type:
pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
pool.save()
def instance_type_from_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_types:
types = json.loads(pool.ec2_instance_types)
if len(types) > 1:
print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
file=sys.stderr)
pool.ec2_instance_types = types[0]
pool.save()
class Migration(migrations.Migration):
// ... modified code ...
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RunPython(
code=instance_type_to_list,
reverse_code=instance_type_from_list,
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
]
// ... rest of the code ...
|
a36fba5021bb5f0f01c6f004b78d021636706487
|
runtime/ceylon/Boolean.java
|
runtime/ceylon/Boolean.java
|
package ceylon;
public final class Boolean extends Object {
private final boolean value;
private Boolean(boolean b) {
value = b;
}
public static ceylon.Boolean instance(boolean b) {
return new ceylon.Boolean(b);
}
@Extension
public ceylon.String string() {
return ceylon.String.instance(java.lang.Boolean.toString(value));
}
}
|
package ceylon;
public final class Boolean extends Object {
private final boolean value;
private Boolean(boolean b) {
value = b;
}
public static ceylon.Boolean instance(boolean b) {
return new ceylon.Boolean(b);
}
@Extension
public ceylon.String string() {
return ceylon.String.instance(java.lang.Boolean.toString(value));
}
public boolean booleanValue() {
return value;
}
}
|
Tidy up ClassVisitor. While statement.
|
Tidy up ClassVisitor. While statement.
|
Java
|
apache-2.0
|
jvasileff/ceylon.language,ceylon/ceylon.language,lucaswerkmeister/ceylon.language,lucaswerkmeister/ceylon.language,unratito/ceylon.language,jvasileff/ceylon.language,unratito/ceylon.language,ceylon/ceylon.language
|
java
|
## Code Before:
package ceylon;
public final class Boolean extends Object {
private final boolean value;
private Boolean(boolean b) {
value = b;
}
public static ceylon.Boolean instance(boolean b) {
return new ceylon.Boolean(b);
}
@Extension
public ceylon.String string() {
return ceylon.String.instance(java.lang.Boolean.toString(value));
}
}
## Instruction:
Tidy up ClassVisitor. While statement.
## Code After:
package ceylon;
public final class Boolean extends Object {
private final boolean value;
private Boolean(boolean b) {
value = b;
}
public static ceylon.Boolean instance(boolean b) {
return new ceylon.Boolean(b);
}
@Extension
public ceylon.String string() {
return ceylon.String.instance(java.lang.Boolean.toString(value));
}
public boolean booleanValue() {
return value;
}
}
|
// ... existing code ...
public ceylon.String string() {
return ceylon.String.instance(java.lang.Boolean.toString(value));
}
public boolean booleanValue() {
return value;
}
}
// ... rest of the code ...
|
ba2f2d7e53f0ffc58c882d78f1b8bc9a468eb164
|
predicates.py
|
predicates.py
|
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
|
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
|
Fix problem rendering oneof() predicate when the members aren't strings
|
Fix problem rendering oneof() predicate when the members aren't strings
|
Python
|
mit
|
mrozekma/pytypecheck
|
python
|
## Code Before:
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
## Instruction:
Fix problem rendering oneof() predicate when the members aren't strings
## Code After:
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
|
...
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
...
|
a5ab366e0329bffec2ee03cde056b005e5d7ac83
|
netty-test-client/src/main/java/com/albin/NettyMain.java
|
netty-test-client/src/main/java/com/albin/NettyMain.java
|
package com.albin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.albin.mqtt.NettyClient;
public class NettyMain {
private static NettyClient client;
private static String topic;
public static void main(String[] args) throws InterruptedException, IOException {
client = new NettyClient(args[0]);
client.connect();
beInteractive();
client.disconnect();
}
private static void beInteractive() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = in.readLine();
if (line.startsWith("pub"))
publish(line.substring(4));
if (line.startsWith("sub"))
subscribe(line.substring(4));
if (line.startsWith("unsub"))
unsubscribe(line.substring(6));
if (line.startsWith("topic")) {
topic = line.substring(6);
}
} while(!"bye".equals(line));
}
private static void unsubscribe(String topic) {
client.unsubscribe(topic);
}
private static void subscribe(String topic) {
client.subscribe(topic);
}
private static void publish(String msg) {
client.publish(topic, msg);
}
}
|
package com.albin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.albin.mqtt.NettyClient;
public class NettyMain {
private static NettyClient client;
private static String topic;
public static void main(String[] args) throws InterruptedException, IOException {
String id = args.length == 0 ? "Dummy_"+System.currentTimeMillis() : args[0];
client = new NettyClient(id);
client.connect();
beInteractive();
client.disconnect();
}
private static void beInteractive() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = in.readLine();
if (line.startsWith("pub"))
publish(line.substring(4));
if (line.startsWith("sub"))
subscribe(line.substring(4));
if (line.startsWith("unsub"))
unsubscribe(line.substring(6));
if (line.startsWith("topic")) {
topic = line.substring(6);
}
} while(!"bye".equals(line));
}
private static void unsubscribe(String topic) {
client.unsubscribe(topic);
}
private static void subscribe(String topic) {
client.subscribe(topic);
}
private static void publish(String msg) {
client.publish(topic, msg);
}
}
|
Test app now creates dummy id if none is specified.
|
Test app now creates dummy id if none is specified.
|
Java
|
apache-2.0
|
soenter/MeQanTT,soenter/MeQanTT,AlbinTheander/MeQanTT
|
java
|
## Code Before:
package com.albin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.albin.mqtt.NettyClient;
public class NettyMain {
private static NettyClient client;
private static String topic;
public static void main(String[] args) throws InterruptedException, IOException {
client = new NettyClient(args[0]);
client.connect();
beInteractive();
client.disconnect();
}
private static void beInteractive() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = in.readLine();
if (line.startsWith("pub"))
publish(line.substring(4));
if (line.startsWith("sub"))
subscribe(line.substring(4));
if (line.startsWith("unsub"))
unsubscribe(line.substring(6));
if (line.startsWith("topic")) {
topic = line.substring(6);
}
} while(!"bye".equals(line));
}
private static void unsubscribe(String topic) {
client.unsubscribe(topic);
}
private static void subscribe(String topic) {
client.subscribe(topic);
}
private static void publish(String msg) {
client.publish(topic, msg);
}
}
## Instruction:
Test app now creates dummy id if none is specified.
## Code After:
package com.albin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.albin.mqtt.NettyClient;
public class NettyMain {
private static NettyClient client;
private static String topic;
public static void main(String[] args) throws InterruptedException, IOException {
String id = args.length == 0 ? "Dummy_"+System.currentTimeMillis() : args[0];
client = new NettyClient(id);
client.connect();
beInteractive();
client.disconnect();
}
private static void beInteractive() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = in.readLine();
if (line.startsWith("pub"))
publish(line.substring(4));
if (line.startsWith("sub"))
subscribe(line.substring(4));
if (line.startsWith("unsub"))
unsubscribe(line.substring(6));
if (line.startsWith("topic")) {
topic = line.substring(6);
}
} while(!"bye".equals(line));
}
private static void unsubscribe(String topic) {
client.unsubscribe(topic);
}
private static void subscribe(String topic) {
client.subscribe(topic);
}
private static void publish(String msg) {
client.publish(topic, msg);
}
}
|
# ... existing code ...
private static String topic;
public static void main(String[] args) throws InterruptedException, IOException {
String id = args.length == 0 ? "Dummy_"+System.currentTimeMillis() : args[0];
client = new NettyClient(id);
client.connect();
beInteractive();
client.disconnect();
# ... rest of the code ...
|
f4cb832d61437ad6e871a1596393adc06ceafab9
|
cookiecutter/utils.py
|
cookiecutter/utils.py
|
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
Add docstring. 4 spaces for consistency.
|
Add docstring. 4 spaces for consistency.
|
Python
|
bsd-3-clause
|
lgp171188/cookiecutter,janusnic/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,willingc/cookiecutter,letolab/cookiecutter,christabor/cookiecutter,cichm/cookiecutter,vincentbernat/cookiecutter,terryjbates/cookiecutter,atlassian/cookiecutter,foodszhang/cookiecutter,michaeljoseph/cookiecutter,cguardia/cookiecutter,alex/cookiecutter,lucius-feng/cookiecutter,lgp171188/cookiecutter,vincentbernat/cookiecutter,kkujawinski/cookiecutter,sp1rs/cookiecutter,atlassian/cookiecutter,hackebrot/cookiecutter,vintasoftware/cookiecutter,audreyr/cookiecutter,ionelmc/cookiecutter,cichm/cookiecutter,venumech/cookiecutter,nhomar/cookiecutter,nhomar/cookiecutter,Vauxoo/cookiecutter,ramiroluz/cookiecutter,Vauxoo/cookiecutter,hackebrot/cookiecutter,stevepiercy/cookiecutter,utek/cookiecutter,christabor/cookiecutter,ionelmc/cookiecutter,tylerdave/cookiecutter,drgarcia1986/cookiecutter,stevepiercy/cookiecutter,jhermann/cookiecutter,Springerle/cookiecutter,letolab/cookiecutter,jhermann/cookiecutter,0k/cookiecutter,ramiroluz/cookiecutter,terryjbates/cookiecutter,foodszhang/cookiecutter,sp1rs/cookiecutter,Springerle/cookiecutter,michaeljoseph/cookiecutter,takeflight/cookiecutter,0k/cookiecutter,luzfcb/cookiecutter,pjbull/cookiecutter,moi65/cookiecutter,lucius-feng/cookiecutter,cguardia/cookiecutter,audreyr/cookiecutter,alex/cookiecutter,utek/cookiecutter,benthomasson/cookiecutter,benthomasson/cookiecutter,moi65/cookiecutter,willingc/cookiecutter,luzfcb/cookiecutter,takeflight/cookiecutter,janusnic/cookiecutter,vintasoftware/cookiecutter,tylerdave/cookiecutter,pjbull/cookiecutter,kkujawinski/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,venumech/cookiecutter,drgarcia1986/cookiecutter
|
python
|
## Code Before:
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
## Instruction:
Add docstring. 4 spaces for consistency.
## Code After:
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
// ... existing code ...
@contextlib.contextmanager
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
// ... rest of the code ...
|
b4b7185a054d07097e743664abda44e121674b8b
|
talks_keeper/forms.py
|
talks_keeper/forms.py
|
from django import forms
from .models import Label, Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
labels = Label.objects.all()
for label_ in labels:
self.fields.update({
'label_{}'.format(label_.id): forms.BooleanField(
label=label_.name,
required=False,
)})
class Meta:
model = Talk
exclude = ['company']
def save(self):
talk = super(TalkForm, self).save()
for label_ in Label.objects.all():
if self.cleaned_data['label_{}'.format(label_.id)]:
label_.talks.add(talk)
|
from django import forms
from .models import Label, Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
instance = kwargs['instance']
labels = Label.objects.all()
for label_ in labels:
if instance is None:
initial = False
else:
initial = label_.talks.filter(id=instance.id).exists()
self.fields.update({
'label_{}'.format(label_.id): forms.BooleanField(
label=label_.name,
required=False,
initial=initial,
)})
class Meta:
model = Talk
exclude = ['company']
def save(self, commit=True):
talk = super(TalkForm, self).save()
for label_ in Label.objects.all():
if self.cleaned_data['label_{}'.format(label_.id)]:
label_.talks.add(talk)
|
Update TalkForm to use checked labels
|
Update TalkForm to use checked labels
|
Python
|
mit
|
samitnuk/talks_keeper,samitnuk/talks_keeper,samitnuk/talks_keeper
|
python
|
## Code Before:
from django import forms
from .models import Label, Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
labels = Label.objects.all()
for label_ in labels:
self.fields.update({
'label_{}'.format(label_.id): forms.BooleanField(
label=label_.name,
required=False,
)})
class Meta:
model = Talk
exclude = ['company']
def save(self):
talk = super(TalkForm, self).save()
for label_ in Label.objects.all():
if self.cleaned_data['label_{}'.format(label_.id)]:
label_.talks.add(talk)
## Instruction:
Update TalkForm to use checked labels
## Code After:
from django import forms
from .models import Label, Talk
class TalkForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
instance = kwargs['instance']
labels = Label.objects.all()
for label_ in labels:
if instance is None:
initial = False
else:
initial = label_.talks.filter(id=instance.id).exists()
self.fields.update({
'label_{}'.format(label_.id): forms.BooleanField(
label=label_.name,
required=False,
initial=initial,
)})
class Meta:
model = Talk
exclude = ['company']
def save(self, commit=True):
talk = super(TalkForm, self).save()
for label_ in Label.objects.all():
if self.cleaned_data['label_{}'.format(label_.id)]:
label_.talks.add(talk)
|
...
def __init__(self, *args, **kwargs):
super(TalkForm, self).__init__(*args, **kwargs)
instance = kwargs['instance']
labels = Label.objects.all()
for label_ in labels:
if instance is None:
initial = False
else:
initial = label_.talks.filter(id=instance.id).exists()
self.fields.update({
'label_{}'.format(label_.id): forms.BooleanField(
label=label_.name,
required=False,
initial=initial,
)})
class Meta:
...
model = Talk
exclude = ['company']
def save(self, commit=True):
talk = super(TalkForm, self).save()
for label_ in Label.objects.all():
if self.cleaned_data['label_{}'.format(label_.id)]:
...
|
b613c582ce5fb4ed3932b2833fa896631ba18826
|
src/main/java/com/epam/ta/reportportal/ws/model/widget/MaterializedWidgetType.java
|
src/main/java/com/epam/ta/reportportal/ws/model/widget/MaterializedWidgetType.java
|
package com.epam.ta.reportportal.ws.model.widget;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Optional;
/**
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
public enum MaterializedWidgetType {
COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable");
private final String type;
MaterializedWidgetType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
|
package com.epam.ta.reportportal.ws.model.widget;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Optional;
/**
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
public enum MaterializedWidgetType {
COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable"),
CUMULATIVE_TREND_CHART("cumulative");
private final String type;
MaterializedWidgetType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
|
Add missed widget type to the validator
|
Add missed widget type to the validator
|
Java
|
apache-2.0
|
reportportal/commons-model
|
java
|
## Code Before:
package com.epam.ta.reportportal.ws.model.widget;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Optional;
/**
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
public enum MaterializedWidgetType {
COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable");
private final String type;
MaterializedWidgetType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
## Instruction:
Add missed widget type to the validator
## Code After:
package com.epam.ta.reportportal.ws.model.widget;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Optional;
/**
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
public enum MaterializedWidgetType {
COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable"),
CUMULATIVE_TREND_CHART("cumulative");
private final String type;
MaterializedWidgetType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
|
// ... existing code ...
*/
public enum MaterializedWidgetType {
COMPONENT_HEALTH_CHECK_TABLE("componentHealthCheckTable"),
CUMULATIVE_TREND_CHART("cumulative");
private final String type;
// ... rest of the code ...
|
b834040b9426954cde912b685af7505b741dab4a
|
control.c
|
control.c
|
struct Packet {
unsigned int status: 1;
unsigned int group: 2;
unsigned int plug: 2;
};
unsigned int packet_to_binary(struct Packet packet) {
unsigned int binary = (packet.status << 7);
binary |= ((packet.group & 0x3) << 2);
binary |= (packet.plug & 0x3);
return binary & 0xFF;
}
void binary_to_packet(struct Packet *packet, unsigned int binary) {
packet->status = (binary >> 7);
packet->group = (binary >> 2) & 0x3;
packet->plug = binary & 0x3;
}
void printBinary(int num, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
while (current > 0) {
printf("%d", ((num & current) >> shift) & 1);
shift--;
current /= 2;
}
printf("\n");
}
|
struct Packet {
unsigned int status: 1;
unsigned int group: 2;
unsigned int plug: 2;
};
unsigned int packet_to_binary(struct Packet packet) {
unsigned int binary = (packet.status << 7);
binary |= ((packet.group & 0x3) << 2);
binary |= (packet.plug & 0x3);
return binary & 0xFF;
}
void binary_to_packet(struct Packet *packet, unsigned int binary) {
packet->status = (binary >> 7);
packet->group = (binary >> 2) & 0x3;
packet->plug = binary & 0x3;
}
void btoa(int num, char *buf, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
char digit[2];
while (current > 0) {
sprintf(digit, "%d", ((num & current) >> shift) & 1);
strncat(buf, digit, 1);
shift--;
current /= 2;
}
strcat(buf, "\0");
}
|
Rename printBinary function and write to string instead
|
Rename printBinary function and write to string instead
printBinary is now called btoa (binary to ascii)
btoa accepts the number, a buffer and a number of digits
buffer length must be (digits + 1)
|
C
|
agpl-3.0
|
jackwilsdon/lightcontrol,jackwilsdon/lightcontrol
|
c
|
## Code Before:
struct Packet {
unsigned int status: 1;
unsigned int group: 2;
unsigned int plug: 2;
};
unsigned int packet_to_binary(struct Packet packet) {
unsigned int binary = (packet.status << 7);
binary |= ((packet.group & 0x3) << 2);
binary |= (packet.plug & 0x3);
return binary & 0xFF;
}
void binary_to_packet(struct Packet *packet, unsigned int binary) {
packet->status = (binary >> 7);
packet->group = (binary >> 2) & 0x3;
packet->plug = binary & 0x3;
}
void printBinary(int num, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
while (current > 0) {
printf("%d", ((num & current) >> shift) & 1);
shift--;
current /= 2;
}
printf("\n");
}
## Instruction:
Rename printBinary function and write to string instead
printBinary is now called btoa (binary to ascii)
btoa accepts the number, a buffer and a number of digits
buffer length must be (digits + 1)
## Code After:
struct Packet {
unsigned int status: 1;
unsigned int group: 2;
unsigned int plug: 2;
};
unsigned int packet_to_binary(struct Packet packet) {
unsigned int binary = (packet.status << 7);
binary |= ((packet.group & 0x3) << 2);
binary |= (packet.plug & 0x3);
return binary & 0xFF;
}
void binary_to_packet(struct Packet *packet, unsigned int binary) {
packet->status = (binary >> 7);
packet->group = (binary >> 2) & 0x3;
packet->plug = binary & 0x3;
}
void btoa(int num, char *buf, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
char digit[2];
while (current > 0) {
sprintf(digit, "%d", ((num & current) >> shift) & 1);
strncat(buf, digit, 1);
shift--;
current /= 2;
}
strcat(buf, "\0");
}
|
// ... existing code ...
packet->plug = binary & 0x3;
}
void btoa(int num, char *buf, int digits) {
int shift = digits - 1;
int current = pow(2, shift);
char digit[2];
while (current > 0) {
sprintf(digit, "%d", ((num & current) >> shift) & 1);
strncat(buf, digit, 1);
shift--;
current /= 2;
}
strcat(buf, "\0");
}
// ... rest of the code ...
|
2c27b19cda505e2b8f0f07d5a6456af9a8a03356
|
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/models/GeneratePMCodeModel.kt
|
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/models/GeneratePMCodeModel.kt
|
package com.github.shiraji.permissionsdispatcherplugin.models
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel {
fun createPsiClass(qualifiedName: String, project: Project): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project);
val searchScope = GlobalSearchScope.allScope(project);
return psiFacade.findClass(qualifiedName, searchScope);
}
}
|
package com.github.shiraji.permissionsdispatcherplugin.models
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel {
fun isActivity(aClass: PsiClass, project: Project): Boolean {
val activity = createPsiClass("android.app.Activity", project) ?: return false
return aClass.isInheritor(activity, true)
}
fun isFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun isSupportFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.support.v4.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun createPsiClass(qualifiedName: String, project: Project): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project);
val searchScope = GlobalSearchScope.allScope(project);
return psiFacade.findClass(qualifiedName, searchScope);
}
}
|
Add features that find if the class is Activity or Fragment
|
Add features that find if the class is Activity or Fragment
|
Kotlin
|
apache-2.0
|
shiraji/permissions-dispatcher-plugin,shiraji/permissions-dispatcher-plugin,shiraji/permissions-dispatcher-plugin
|
kotlin
|
## Code Before:
package com.github.shiraji.permissionsdispatcherplugin.models
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel {
fun createPsiClass(qualifiedName: String, project: Project): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project);
val searchScope = GlobalSearchScope.allScope(project);
return psiFacade.findClass(qualifiedName, searchScope);
}
}
## Instruction:
Add features that find if the class is Activity or Fragment
## Code After:
package com.github.shiraji.permissionsdispatcherplugin.models
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel {
fun isActivity(aClass: PsiClass, project: Project): Boolean {
val activity = createPsiClass("android.app.Activity", project) ?: return false
return aClass.isInheritor(activity, true)
}
fun isFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun isSupportFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.support.v4.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun createPsiClass(qualifiedName: String, project: Project): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project);
val searchScope = GlobalSearchScope.allScope(project);
return psiFacade.findClass(qualifiedName, searchScope);
}
}
|
# ... existing code ...
import com.intellij.psi.search.GlobalSearchScope
class GeneratePMCodeModel {
fun isActivity(aClass: PsiClass, project: Project): Boolean {
val activity = createPsiClass("android.app.Activity", project) ?: return false
return aClass.isInheritor(activity, true)
}
fun isFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun isSupportFragment(aClass: PsiClass, project: Project): Boolean {
val fragment = createPsiClass("android.support.v4.app.Fragment", project) ?: return false
return aClass.isInheritor(fragment, true)
}
fun createPsiClass(qualifiedName: String, project: Project): PsiClass? {
val psiFacade = JavaPsiFacade.getInstance(project);
val searchScope = GlobalSearchScope.allScope(project);
# ... rest of the code ...
|
e8ca2582404d44a6bc97f455187523713c49d90f
|
test/test_random_seed.py
|
test/test_random_seed.py
|
from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=1, random_seed=42)
}
"""
val = genson.loads(gson).next()['gaussian_random_seed']
assert_equal(val, 0.4967141530112327)
def test_gaussian_uniform_seed():
gson = \
"""
{
"gaussian_uniform_seed" : uniform(0, 1, draws=1, random_seed=42)
}
"""
val = genson.loads(gson).next()['gaussian_uniform_seed']
assert_equal(val, 0.3745401188473625)
|
from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['gaussian_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.4967141530112327)
assert_equal(vals[1], -0.13826430117118466)
def test_gaussian_uniform_seed():
gson = \
"""
{
"uniform_random_seed" : uniform(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['uniform_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.3745401188473625)
assert_equal(vals[1], 0.9507143064099162)
|
Add RandomState to help generate different values, with test
|
Add RandomState to help generate different values, with test
|
Python
|
mit
|
davidcox/genson
|
python
|
## Code Before:
from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=1, random_seed=42)
}
"""
val = genson.loads(gson).next()['gaussian_random_seed']
assert_equal(val, 0.4967141530112327)
def test_gaussian_uniform_seed():
gson = \
"""
{
"gaussian_uniform_seed" : uniform(0, 1, draws=1, random_seed=42)
}
"""
val = genson.loads(gson).next()['gaussian_uniform_seed']
assert_equal(val, 0.3745401188473625)
## Instruction:
Add RandomState to help generate different values, with test
## Code After:
from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['gaussian_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.4967141530112327)
assert_equal(vals[1], -0.13826430117118466)
def test_gaussian_uniform_seed():
gson = \
"""
{
"uniform_random_seed" : uniform(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['uniform_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.3745401188473625)
assert_equal(vals[1], 0.9507143064099162)
|
# ... existing code ...
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['gaussian_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.4967141530112327)
assert_equal(vals[1], -0.13826430117118466)
def test_gaussian_uniform_seed():
# ... modified code ...
gson = \
"""
{
"uniform_random_seed" : uniform(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['uniform_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.3745401188473625)
assert_equal(vals[1], 0.9507143064099162)
# ... rest of the code ...
|
e6d965cc36d92ee8f138d487614244c6e3deda69
|
run_tests.py
|
run_tests.py
|
from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
test_list = []
dist_dir = libtbx.env.dist_path(module)
class TestDiscoveryPlugin:
def pytest_itemcollected(self, item):
test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest',
os.path.join(dist_dir, item.nodeid) ])
print "Discovering pytest tests:"
pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()])
return test_list
if (__name__ == "__main__"):
import unittest
test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py")
result = unittest.TextTestRunner().run(test_suite)
import sys
sys.exit(0 if result.wasSuccessful() else 1)
tst_list = [
# "$D/tests/tst_legacy.py",
["$D/tests/tst_legacy_mult.py", "1"]
# ["$D/tests/tst_legacy_mult.py", "2"]
] + discover_pytests("i19")
|
from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
def pytest_warning():
print "=" * 60
print "WARNING: Skipping some tests\n"
print "To run all available tests you need to install pytest"
print "eg. with libtbx.python -m pip install pytest"
print "=" * 60
pytest_warning()
import atexit
atexit.register(pytest_warning)
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
test_list = []
dist_dir = libtbx.env.dist_path(module)
class TestDiscoveryPlugin:
def pytest_itemcollected(self, item):
test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest',
os.path.join(dist_dir, item.nodeid) ])
print "Discovering pytest tests:"
pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()])
return test_list
if (__name__ == "__main__"):
import unittest
test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py")
result = unittest.TextTestRunner().run(test_suite)
import sys
sys.exit(0 if result.wasSuccessful() else 1)
tst_list = [
# "$D/tests/tst_legacy.py",
["$D/tests/tst_legacy_mult.py", "1"]
# ["$D/tests/tst_legacy_mult.py", "2"]
] + discover_pytests("i19")
|
Add warning for skipped tests if pytest not available
|
Add warning for skipped tests if pytest not available
|
Python
|
bsd-3-clause
|
xia2/i19
|
python
|
## Code Before:
from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
test_list = []
dist_dir = libtbx.env.dist_path(module)
class TestDiscoveryPlugin:
def pytest_itemcollected(self, item):
test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest',
os.path.join(dist_dir, item.nodeid) ])
print "Discovering pytest tests:"
pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()])
return test_list
if (__name__ == "__main__"):
import unittest
test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py")
result = unittest.TextTestRunner().run(test_suite)
import sys
sys.exit(0 if result.wasSuccessful() else 1)
tst_list = [
# "$D/tests/tst_legacy.py",
["$D/tests/tst_legacy_mult.py", "1"]
# ["$D/tests/tst_legacy_mult.py", "2"]
] + discover_pytests("i19")
## Instruction:
Add warning for skipped tests if pytest not available
## Code After:
from __future__ import division
import libtbx.load_env
def discover_pytests(module):
try:
import os
import pytest
except ImportError:
def pytest_warning():
print "=" * 60
print "WARNING: Skipping some tests\n"
print "To run all available tests you need to install pytest"
print "eg. with libtbx.python -m pip install pytest"
print "=" * 60
pytest_warning()
import atexit
atexit.register(pytest_warning)
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
test_list = []
dist_dir = libtbx.env.dist_path(module)
class TestDiscoveryPlugin:
def pytest_itemcollected(self, item):
test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest',
os.path.join(dist_dir, item.nodeid) ])
print "Discovering pytest tests:"
pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()])
return test_list
if (__name__ == "__main__"):
import unittest
test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py")
result = unittest.TextTestRunner().run(test_suite)
import sys
sys.exit(0 if result.wasSuccessful() else 1)
tst_list = [
# "$D/tests/tst_legacy.py",
["$D/tests/tst_legacy_mult.py", "1"]
# ["$D/tests/tst_legacy_mult.py", "2"]
] + discover_pytests("i19")
|
// ... existing code ...
import os
import pytest
except ImportError:
def pytest_warning():
print "=" * 60
print "WARNING: Skipping some tests\n"
print "To run all available tests you need to install pytest"
print "eg. with libtbx.python -m pip install pytest"
print "=" * 60
pytest_warning()
import atexit
atexit.register(pytest_warning)
return []
if 'LIBTBX_SKIP_PYTEST' in os.environ:
return []
// ... rest of the code ...
|
9c3d24083be5969ca84c1625dbc0d368acdc51f8
|
tg/tests/test_util.py
|
tg/tests/test_util.py
|
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
Add a test_get_partial_dict unit test, which currently fails
|
Add a test_get_partial_dict unit test, which currently fails
|
Python
|
mit
|
lucius-feng/tg2,lucius-feng/tg2
|
python
|
## Code Before:
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
## Instruction:
Add a test_get_partial_dict unit test, which currently fails
## Code After:
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
# ... existing code ...
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
# ... rest of the code ...
|
4ee409a5635b1d027f5d3c68fb2a62f554c9c801
|
ib_insync/__init__.py
|
ib_insync/__init__.py
|
import sys
import importlib
from .version import __version__, __version_info__ # noqa
from . import util
if sys.version_info < (3, 6, 0):
raise RuntimeError('ib_insync requires Python 3.6 or higher')
try:
import ibapi
except ImportError:
raise RuntimeError(
'IB API from http://interactivebrokers.github.io is required')
if util.ibapiVersionInfo() < (9, 73, 6):
raise RuntimeError(
f'Old version ({ibapi.__version__}) of ibapi package detected. '
'The newest version from http://interactivebrokers.github.io '
'is required')
from .version import __version__, __version_info__ # noqa
from .objects import * # noqa
from .event import * # noqa
from .contract import * # noqa
from .order import * # noqa
from .ticker import * # noqa
from .ib import * # noqa
from .client import * # noqa
from .wrapper import * # noqa
from .flexreport import * # noqa
from .ibcontroller import * # noqa
from . import util # noqa
__all__ = ['util']
for _m in (
objects, event, contract, order, ticker, ib, # noqa
client, wrapper, flexreport, ibcontroller): # noqa
__all__ += _m.__all__
del sys
del importlib
del ibapi
|
import sys
import importlib
if sys.version_info < (3, 6, 0):
raise RuntimeError('ib_insync requires Python 3.6 or higher')
try:
import ibapi
except ImportError:
raise RuntimeError(
'IB API from http://interactivebrokers.github.io is required')
from . import util # noqa
if util.ibapiVersionInfo() < (9, 73, 6):
raise RuntimeError(
f'Old version ({ibapi.__version__}) of ibapi package detected. '
'The newest version from http://interactivebrokers.github.io '
'is required')
from .version import __version__, __version_info__ # noqa
from .objects import * # noqa
from .event import * # noqa
from .contract import * # noqa
from .order import * # noqa
from .ticker import * # noqa
from .ib import * # noqa
from .client import * # noqa
from .wrapper import * # noqa
from .flexreport import * # noqa
from .ibcontroller import * # noqa
__all__ = ['util']
for _m in (
objects, event, contract, order, ticker, ib, # noqa
client, wrapper, flexreport, ibcontroller): # noqa
__all__ += _m.__all__
del sys
del importlib
del ibapi
|
Fix explicit check for presence of ibapi package
|
Fix explicit check for presence of ibapi package
|
Python
|
bsd-2-clause
|
erdewit/ib_insync,erdewit/ib_insync
|
python
|
## Code Before:
import sys
import importlib
from .version import __version__, __version_info__ # noqa
from . import util
if sys.version_info < (3, 6, 0):
raise RuntimeError('ib_insync requires Python 3.6 or higher')
try:
import ibapi
except ImportError:
raise RuntimeError(
'IB API from http://interactivebrokers.github.io is required')
if util.ibapiVersionInfo() < (9, 73, 6):
raise RuntimeError(
f'Old version ({ibapi.__version__}) of ibapi package detected. '
'The newest version from http://interactivebrokers.github.io '
'is required')
from .version import __version__, __version_info__ # noqa
from .objects import * # noqa
from .event import * # noqa
from .contract import * # noqa
from .order import * # noqa
from .ticker import * # noqa
from .ib import * # noqa
from .client import * # noqa
from .wrapper import * # noqa
from .flexreport import * # noqa
from .ibcontroller import * # noqa
from . import util # noqa
__all__ = ['util']
for _m in (
objects, event, contract, order, ticker, ib, # noqa
client, wrapper, flexreport, ibcontroller): # noqa
__all__ += _m.__all__
del sys
del importlib
del ibapi
## Instruction:
Fix explicit check for presence of ibapi package
## Code After:
import sys
import importlib
if sys.version_info < (3, 6, 0):
raise RuntimeError('ib_insync requires Python 3.6 or higher')
try:
import ibapi
except ImportError:
raise RuntimeError(
'IB API from http://interactivebrokers.github.io is required')
from . import util # noqa
if util.ibapiVersionInfo() < (9, 73, 6):
raise RuntimeError(
f'Old version ({ibapi.__version__}) of ibapi package detected. '
'The newest version from http://interactivebrokers.github.io '
'is required')
from .version import __version__, __version_info__ # noqa
from .objects import * # noqa
from .event import * # noqa
from .contract import * # noqa
from .order import * # noqa
from .ticker import * # noqa
from .ib import * # noqa
from .client import * # noqa
from .wrapper import * # noqa
from .flexreport import * # noqa
from .ibcontroller import * # noqa
__all__ = ['util']
for _m in (
objects, event, contract, order, ticker, ib, # noqa
client, wrapper, flexreport, ibcontroller): # noqa
__all__ += _m.__all__
del sys
del importlib
del ibapi
|
# ... existing code ...
import sys
import importlib
if sys.version_info < (3, 6, 0):
raise RuntimeError('ib_insync requires Python 3.6 or higher')
# ... modified code ...
raise RuntimeError(
'IB API from http://interactivebrokers.github.io is required')
from . import util # noqa
if util.ibapiVersionInfo() < (9, 73, 6):
raise RuntimeError(
f'Old version ({ibapi.__version__}) of ibapi package detected. '
'The newest version from http://interactivebrokers.github.io '
'is required')
from .version import __version__, __version_info__ # noqa
from .objects import * # noqa
...
from .wrapper import * # noqa
from .flexreport import * # noqa
from .ibcontroller import * # noqa
__all__ = ['util']
for _m in (
# ... rest of the code ...
|
d9c4f1fea2de1f83f26c6e767a463966920ca3bd
|
app/src/com/ternaryop/utils/DialogUtils.java
|
app/src/com/ternaryop/utils/DialogUtils.java
|
package com.ternaryop.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class DialogUtils {
public static void showErrorDialog(Context context, Exception e) {
showErrorDialog(context, "Error", e);
}
public static void showErrorDialog(Context context, String title, Exception e) {
showSimpleMessageDialog(context, title, e.getLocalizedMessage());
}
public static void showErrorDialog(Context context, int resId, Exception e) {
showSimpleMessageDialog(context, context.getString(resId), e.getLocalizedMessage());
}
public static void showSimpleMessageDialog(Context context, int resId, String message) {
showSimpleMessageDialog(context, context.getString(resId), message);
}
public static void showSimpleMessageDialog(Context context, String title, String message) {
new AlertDialog.Builder(context)
.setCancelable(false) // This blocks the 'BACK' button
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
|
package com.ternaryop.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class DialogUtils {
public static void showErrorDialog(Context context, Throwable t) {
showErrorDialog(context, "Error", t);
}
public static void showErrorDialog(Context context, String title, Throwable t) {
showSimpleMessageDialog(context, title, t.getLocalizedMessage());
}
public static void showErrorDialog(Context context, int resId, Throwable t) {
showSimpleMessageDialog(context, context.getString(resId), t.getLocalizedMessage());
}
public static void showSimpleMessageDialog(Context context, int resId, String message) {
showSimpleMessageDialog(context, context.getString(resId), message);
}
public static void showSimpleMessageDialog(Context context, String title, String message) {
new AlertDialog.Builder(context)
.setCancelable(false) // This blocks the 'BACK' button
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
|
Use Throwable instead of Exception
|
Use Throwable instead of Exception
|
Java
|
mit
|
dafi/photoshelf
|
java
|
## Code Before:
package com.ternaryop.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class DialogUtils {
public static void showErrorDialog(Context context, Exception e) {
showErrorDialog(context, "Error", e);
}
public static void showErrorDialog(Context context, String title, Exception e) {
showSimpleMessageDialog(context, title, e.getLocalizedMessage());
}
public static void showErrorDialog(Context context, int resId, Exception e) {
showSimpleMessageDialog(context, context.getString(resId), e.getLocalizedMessage());
}
public static void showSimpleMessageDialog(Context context, int resId, String message) {
showSimpleMessageDialog(context, context.getString(resId), message);
}
public static void showSimpleMessageDialog(Context context, String title, String message) {
new AlertDialog.Builder(context)
.setCancelable(false) // This blocks the 'BACK' button
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
## Instruction:
Use Throwable instead of Exception
## Code After:
package com.ternaryop.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class DialogUtils {
public static void showErrorDialog(Context context, Throwable t) {
showErrorDialog(context, "Error", t);
}
public static void showErrorDialog(Context context, String title, Throwable t) {
showSimpleMessageDialog(context, title, t.getLocalizedMessage());
}
public static void showErrorDialog(Context context, int resId, Throwable t) {
showSimpleMessageDialog(context, context.getString(resId), t.getLocalizedMessage());
}
public static void showSimpleMessageDialog(Context context, int resId, String message) {
showSimpleMessageDialog(context, context.getString(resId), message);
}
public static void showSimpleMessageDialog(Context context, String title, String message) {
new AlertDialog.Builder(context)
.setCancelable(false) // This blocks the 'BACK' button
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
|
# ... existing code ...
public class DialogUtils {
public static void showErrorDialog(Context context, Throwable t) {
showErrorDialog(context, "Error", t);
}
public static void showErrorDialog(Context context, String title, Throwable t) {
showSimpleMessageDialog(context, title, t.getLocalizedMessage());
}
public static void showErrorDialog(Context context, int resId, Throwable t) {
showSimpleMessageDialog(context, context.getString(resId), t.getLocalizedMessage());
}
public static void showSimpleMessageDialog(Context context, int resId, String message) {
showSimpleMessageDialog(context, context.getString(resId), message);
}
public static void showSimpleMessageDialog(Context context, String title, String message) {
new AlertDialog.Builder(context)
.setCancelable(false) // This blocks the 'BACK' button
# ... rest of the code ...
|
d9ce6cc440019ecfc73f1c82e41da4e9ce02a234
|
smart_open/__init__.py
|
smart_open/__init__.py
|
import logging
from smart_open import version
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
|
import logging
from smart_open import version
logger = logging.getLogger(__name__)
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
|
Configure logging handlers before submodule imports
|
Configure logging handlers before submodule imports
- Fix #474
- Fix #475
|
Python
|
mit
|
RaRe-Technologies/smart_open,RaRe-Technologies/smart_open,piskvorky/smart_open
|
python
|
## Code Before:
import logging
from smart_open import version
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
## Instruction:
Configure logging handlers before submodule imports
- Fix #474
- Fix #475
## Code After:
import logging
from smart_open import version
logger = logging.getLogger(__name__)
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
|
// ... existing code ...
import logging
from smart_open import version
logger = logging.getLogger(__name__)
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
// ... modified code ...
'smart_open',
]
__version__ = version.__version__
// ... rest of the code ...
|
164ac322110407ec3ab7b9dc8b6675a405efa6a9
|
pymantic/__init__.py
|
pymantic/__init__.py
|
from rdflib.plugin import register
from rdflib.serializer import Serializer
from rdflib.parser import Parser
import re
# Fix rdflib's ntriples parser
from rdflib.plugins.parsers import ntriples
ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?'
ntriples.r_literal = re.compile(ntriples.literal + ntriples.litinfo)
register('nt', Serializer, 'pymantic.serializers', 'NTSerializer')
register('nq', Serializer, 'pymantic.serializers', 'NQSerializer')
register('nq', Parser, 'pymantic.parsers', 'NQParser')
content_type_to_rdflib_format = {
'text/plain': 'nt',
'text/x-nquads': 'nq',
'application/rdf+xml': 'xml',
'text/turtle': 'turtle',
}
rdflib_format_to_content_type = dict((value, key) for key, value in\
content_type_to_rdflib_format.iteritems())
|
from rdflib.plugin import register
from rdflib.serializer import Serializer
from rdflib.parser import Parser
import re
# Fix rdflib's ntriples parser
from rdflib.plugins.parsers import ntriples
ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?'
ntriples.r_literal = re.compile(ntriples.literal + ntriples.litinfo)
register('nt', Serializer, 'pymantic.serializers', 'NTSerializer')
register('nq', Serializer, 'pymantic.serializers', 'NQSerializer')
register('nq', Parser, 'pymantic.parsers', 'NQParser')
content_type_to_rdflib_format = {
'text/plain': 'nt',
'text/x-nquads': 'nq',
'application/rdf+xml': 'xml',
'text/turtle': 'turtle',
'text/rdf+n3': 'n3',
}
rdflib_format_to_content_type = dict((value, key) for key, value in\
content_type_to_rdflib_format.iteritems())
|
Expand rdflib to content-type mapping.
|
Expand rdflib to content-type mapping.
|
Python
|
bsd-3-clause
|
igor-kim/blazegraph-python,SYSTAP/blazegraph-python,blazegraph/blazegraph-python,SYSTAP/blazegraph-python,blazegraph/blazegraph-python,igor-kim/blazegraph-python,syapse/pymantic
|
python
|
## Code Before:
from rdflib.plugin import register
from rdflib.serializer import Serializer
from rdflib.parser import Parser
import re
# Fix rdflib's ntriples parser
from rdflib.plugins.parsers import ntriples
ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?'
ntriples.r_literal = re.compile(ntriples.literal + ntriples.litinfo)
register('nt', Serializer, 'pymantic.serializers', 'NTSerializer')
register('nq', Serializer, 'pymantic.serializers', 'NQSerializer')
register('nq', Parser, 'pymantic.parsers', 'NQParser')
content_type_to_rdflib_format = {
'text/plain': 'nt',
'text/x-nquads': 'nq',
'application/rdf+xml': 'xml',
'text/turtle': 'turtle',
}
rdflib_format_to_content_type = dict((value, key) for key, value in\
content_type_to_rdflib_format.iteritems())
## Instruction:
Expand rdflib to content-type mapping.
## Code After:
from rdflib.plugin import register
from rdflib.serializer import Serializer
from rdflib.parser import Parser
import re
# Fix rdflib's ntriples parser
from rdflib.plugins.parsers import ntriples
ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?'
ntriples.r_literal = re.compile(ntriples.literal + ntriples.litinfo)
register('nt', Serializer, 'pymantic.serializers', 'NTSerializer')
register('nq', Serializer, 'pymantic.serializers', 'NQSerializer')
register('nq', Parser, 'pymantic.parsers', 'NQParser')
content_type_to_rdflib_format = {
'text/plain': 'nt',
'text/x-nquads': 'nq',
'application/rdf+xml': 'xml',
'text/turtle': 'turtle',
'text/rdf+n3': 'n3',
}
rdflib_format_to_content_type = dict((value, key) for key, value in\
content_type_to_rdflib_format.iteritems())
|
...
'text/x-nquads': 'nq',
'application/rdf+xml': 'xml',
'text/turtle': 'turtle',
'text/rdf+n3': 'n3',
}
rdflib_format_to_content_type = dict((value, key) for key, value in\
...
|
ff9dc074c0659395eb9c8da07daea5bb35081e2d
|
src/main/java/pl/niekoniecznie/p2e/FileDownloader.java
|
src/main/java/pl/niekoniecznie/p2e/FileDownloader.java
|
package pl.niekoniecznie.p2e;
import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;
public class FileDownloader implements Consumer<PolarEntry> {
private final Path backupDirectory;
private final PolarFileSystem filesystem;
public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
this.backupDirectory = backupDirectory;
this.filesystem = filesystem;
}
@Override
public void accept(PolarEntry entry) {
if (entry.isDirectory()) {
return;
}
InputStream source = filesystem.get(entry);
Path destination = Paths.get(backupDirectory.toString(), entry.getPath());
try {
Files.copy(source, destination);
Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package pl.niekoniecznie.p2e;
import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;
public class FileDownloader implements Consumer<PolarEntry> {
private final Path backupDirectory;
private final PolarFileSystem filesystem;
public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
this.backupDirectory = backupDirectory;
this.filesystem = filesystem;
}
@Override
public void accept(PolarEntry entry) {
if (entry.isDirectory()) {
return;
}
InputStream source = filesystem.get(entry);
Path destination = Paths.get(backupDirectory.toString(), entry.getPath());
try {
Files.deleteIfExists(destination);
Files.copy(source, destination);
Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
Delete existing files before downloading them again
|
Delete existing files before downloading them again
|
Java
|
mit
|
dredzik/polar,dredzik/polarusbdump
|
java
|
## Code Before:
package pl.niekoniecznie.p2e;
import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;
public class FileDownloader implements Consumer<PolarEntry> {
private final Path backupDirectory;
private final PolarFileSystem filesystem;
public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
this.backupDirectory = backupDirectory;
this.filesystem = filesystem;
}
@Override
public void accept(PolarEntry entry) {
if (entry.isDirectory()) {
return;
}
InputStream source = filesystem.get(entry);
Path destination = Paths.get(backupDirectory.toString(), entry.getPath());
try {
Files.copy(source, destination);
Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
## Instruction:
Delete existing files before downloading them again
## Code After:
package pl.niekoniecznie.p2e;
import pl.niekoniecznie.polar.io.PolarEntry;
import pl.niekoniecznie.polar.io.PolarFileSystem;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.function.Consumer;
public class FileDownloader implements Consumer<PolarEntry> {
private final Path backupDirectory;
private final PolarFileSystem filesystem;
public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) {
this.backupDirectory = backupDirectory;
this.filesystem = filesystem;
}
@Override
public void accept(PolarEntry entry) {
if (entry.isDirectory()) {
return;
}
InputStream source = filesystem.get(entry);
Path destination = Paths.get(backupDirectory.toString(), entry.getPath());
try {
Files.deleteIfExists(destination);
Files.copy(source, destination);
Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
# ... existing code ...
Path destination = Paths.get(backupDirectory.toString(), entry.getPath());
try {
Files.deleteIfExists(destination);
Files.copy(source, destination);
Files.setLastModifiedTime(destination, FileTime.from(entry.getModified()));
} catch (IOException e) {
# ... rest of the code ...
|
6a8b7aeacf7ae440dfbbd7e4c74cf08563614c22
|
src/com/haxademic/core/app/P.java
|
src/com/haxademic/core/app/P.java
|
package com.haxademic.core.app;
import javax.media.opengl.GL;
import processing.core.PApplet;
@SuppressWarnings("serial")
public class P
extends PApplet {
public static PAppletHax p;
public static GL gl;
public static String SUNFLOW = "hipstersinc.P5Sunflow";
}
|
package com.haxademic.core.app;
import javax.media.opengl.GL;
import processing.core.PApplet;
@SuppressWarnings("serial")
public class P
extends PApplet {
public static PAppletHax p;
public static GL gl;
}
|
Remove very old sunflow renderer string
|
Remove very old sunflow renderer string
|
Java
|
mit
|
cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic
|
java
|
## Code Before:
package com.haxademic.core.app;
import javax.media.opengl.GL;
import processing.core.PApplet;
@SuppressWarnings("serial")
public class P
extends PApplet {
public static PAppletHax p;
public static GL gl;
public static String SUNFLOW = "hipstersinc.P5Sunflow";
}
## Instruction:
Remove very old sunflow renderer string
## Code After:
package com.haxademic.core.app;
import javax.media.opengl.GL;
import processing.core.PApplet;
@SuppressWarnings("serial")
public class P
extends PApplet {
public static PAppletHax p;
public static GL gl;
}
|
# ... existing code ...
public class P
extends PApplet {
public static PAppletHax p;
public static GL gl;
}
# ... rest of the code ...
|
87e5d0e5e92ed5f94e4238e73453934abc7835dd
|
src/tutorials/code/python/chat/5.py
|
src/tutorials/code/python/chat/5.py
|
from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
from functools import partial
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Listen for incoming messages. When they come in, just print them.
chat.on("message", partial(print, "RECEIVE:"))
# Create a timer that sends the message "Hi!" every second.
PeriodicCallback(
lambda: chat.message('Hi!'),
1000
).start()
# Start the tornado event loop.
IOLoop.instance().start()
|
from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Handle incoming messages.
def on_message(message):
print("RECEIVE:", message)
# Listen for incoming messages. When they come in, just print them.
chat.on("message", on_message)
# Create a timer that sends the message "Hi!" every second.
PeriodicCallback(
lambda: chat.message('Hi!'),
1000
).start()
# Start the tornado event loop.
IOLoop.instance().start()
|
Replace partial with a function definition
|
Replace partial with a function definition
Fix indentation, as well.
|
Python
|
mit
|
WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers
|
python
|
## Code Before:
from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
from functools import partial
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Listen for incoming messages. When they come in, just print them.
chat.on("message", partial(print, "RECEIVE:"))
# Create a timer that sends the message "Hi!" every second.
PeriodicCallback(
lambda: chat.message('Hi!'),
1000
).start()
# Start the tornado event loop.
IOLoop.instance().start()
## Instruction:
Replace partial with a function definition
Fix indentation, as well.
## Code After:
from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Handle incoming messages.
def on_message(message):
print("RECEIVE:", message)
# Listen for incoming messages. When they come in, just print them.
chat.on("message", on_message)
# Create a timer that sends the message "Hi!" every second.
PeriodicCallback(
lambda: chat.message('Hi!'),
1000
).start()
# Start the tornado event loop.
IOLoop.instance().start()
|
...
import config
from tornado.ioloop import PeriodicCallback, IOLoop
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Handle incoming messages.
def on_message(message):
print("RECEIVE:", message)
# Listen for incoming messages. When they come in, just print them.
chat.on("message", on_message)
# Create a timer that sends the message "Hi!" every second.
PeriodicCallback(
lambda: chat.message('Hi!'),
1000
).start()
# Start the tornado event loop.
IOLoop.instance().start()
...
|
b812a8da81ec9943d11b8cb9f709e234c90a2282
|
stylo/utils.py
|
stylo/utils.py
|
from uuid import uuid4
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def register(self, event, obj):
"""Register to receive notifications of an event.
:param event: The name of the kind of event to receive
:param obj: The object to receive that kind of message.
"""
if event not in self.subs:
self.subs[event] = [obj]
return
self.subs[event].append(obj)
def send(self, event, **kwargs):
"""Send a message to whoever may be listening."""
if event not in self.subs:
return
for obj in self.subs[event]:
params = get_parameters(obj)
values = {k: v for k, v in kwargs.items() if k in params}
obj(**values)
_message_bus = MessageBus()
def get_message_bus():
"""A function that returns an instance of the message bus to ensure everyone uses
the same instance."""
return _message_bus
|
import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def register(self, event, obj):
"""Register to receive notifications of an event.
:param event: The name of the kind of event to receive
:param obj: The object to receive that kind of message.
"""
if event not in self.subs:
self.subs[event] = [obj]
return
self.subs[event].append(obj)
def send(self, event, **kwargs):
"""Send a message to whoever may be listening."""
if event not in self.subs:
return
for obj in self.subs[event]:
params = get_parameters(obj)
values = {k: v for k, v in kwargs.items() if k in params}
obj(**values)
_message_bus = MessageBus()
def get_message_bus():
"""A function that returns an instance of the message bus to ensure everyone uses
the same instance."""
return _message_bus
|
Add the function back for now
|
Add the function back for now
|
Python
|
mit
|
alcarney/stylo,alcarney/stylo
|
python
|
## Code Before:
from uuid import uuid4
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def register(self, event, obj):
"""Register to receive notifications of an event.
:param event: The name of the kind of event to receive
:param obj: The object to receive that kind of message.
"""
if event not in self.subs:
self.subs[event] = [obj]
return
self.subs[event].append(obj)
def send(self, event, **kwargs):
"""Send a message to whoever may be listening."""
if event not in self.subs:
return
for obj in self.subs[event]:
params = get_parameters(obj)
values = {k: v for k, v in kwargs.items() if k in params}
obj(**values)
_message_bus = MessageBus()
def get_message_bus():
"""A function that returns an instance of the message bus to ensure everyone uses
the same instance."""
return _message_bus
## Instruction:
Add the function back for now
## Code After:
import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def register(self, event, obj):
"""Register to receive notifications of an event.
:param event: The name of the kind of event to receive
:param obj: The object to receive that kind of message.
"""
if event not in self.subs:
self.subs[event] = [obj]
return
self.subs[event].append(obj)
def send(self, event, **kwargs):
"""Send a message to whoever may be listening."""
if event not in self.subs:
return
for obj in self.subs[event]:
params = get_parameters(obj)
values = {k: v for k, v in kwargs.items() if k in params}
obj(**values)
_message_bus = MessageBus()
def get_message_bus():
"""A function that returns an instance of the message bus to ensure everyone uses
the same instance."""
return _message_bus
|
// ... existing code ...
import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class MessageBus:
// ... rest of the code ...
|
903c0d6a3bda96a0b193cc6efd2f8e868d4d82e2
|
setuptools/tests/test_build_ext.py
|
setuptools/tests/test_build_ext.py
|
import unittest
from distutils.command.build_ext import build_ext as distutils_build_ext
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give back the same
# result than distutils, even if the fullname
# is not in ext_map
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = distutils_build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
|
import unittest
import distutils.command.build_ext as orig
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give back the same
# result than distutils, even if the fullname
# is not in ext_map
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = orig.build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
|
Use namespacing for easier reading
|
Use namespacing for easier reading
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
python
|
## Code Before:
import unittest
from distutils.command.build_ext import build_ext as distutils_build_ext
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give back the same
# result than distutils, even if the fullname
# is not in ext_map
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = distutils_build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
## Instruction:
Use namespacing for easier reading
## Code After:
import unittest
import distutils.command.build_ext as orig
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
class TestBuildExtTest(unittest.TestCase):
def test_get_ext_filename(self):
# setuptools needs to give back the same
# result than distutils, even if the fullname
# is not in ext_map
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = orig.build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
|
...
import unittest
import distutils.command.build_ext as orig
from setuptools.command.build_ext import build_ext
from setuptools.dist import Distribution
...
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = orig.build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
...
|
9bad0d910ec5b50f947605f7e20fdb5d7e3d2d51
|
src/test/java/com/alanrusnak/api2048/engine/MoveExecutorTest.java
|
src/test/java/com/alanrusnak/api2048/engine/MoveExecutorTest.java
|
package com.alanrusnak.api2048.engine;
import com.alanrusnak.api2048.engine.model.Tile;
import org.junit.Assert;
import org.junit.Test;
public class MoveExecutorTest {
MoveExecutor moveExecutor = new MoveExecutor();
@Test
public void testSlideTile0Spaces(){
Tile[] row = row(0,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile1Spaces(){
Tile[] row = row(0,0,2,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile2Spaces(){
Tile[] row = row(0,2,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile3Spaces(){
Tile[] row = row(2,0,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
private Tile[] row(int t1, int t2, int t3, int t4){
return new Tile[]{new Tile(t1), new Tile(t2), new Tile(t3), new Tile(t4)};
}
}
|
package com.alanrusnak.api2048.engine;
import com.alanrusnak.api2048.engine.model.Tile;
import org.junit.Assert;
import org.junit.Test;
public class MoveExecutorTest {
MoveExecutor moveExecutor = new MoveExecutor();
@Test
public void testSlideTile0Spaces(){
Tile[] row = row(0,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile1Spaces(){
Tile[] row = row(0,0,2,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile2Spaces(){
Tile[] row = row(0,2,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile3Spaces(){
Tile[] row = row(2,0,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTileWithSpaceTaken(){
Tile[] row = row(2,0,0,4);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[2].getValue());
}
@Test
public void testMergeTwoTiles(){
Tile[] row = row(2,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(4, row[3].getValue());
}
private Tile[] row(int t1, int t2, int t3, int t4){
return new Tile[]{new Tile(t1), new Tile(t2), new Tile(t3), new Tile(t4)};
}
}
|
Add a new non passing test case for merging
|
Add a new non passing test case for merging
|
Java
|
mit
|
alanrusnak/2048-web-api,alanrusnak/2048-web-api,alanrusnak/2048-web-api
|
java
|
## Code Before:
package com.alanrusnak.api2048.engine;
import com.alanrusnak.api2048.engine.model.Tile;
import org.junit.Assert;
import org.junit.Test;
public class MoveExecutorTest {
MoveExecutor moveExecutor = new MoveExecutor();
@Test
public void testSlideTile0Spaces(){
Tile[] row = row(0,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile1Spaces(){
Tile[] row = row(0,0,2,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile2Spaces(){
Tile[] row = row(0,2,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile3Spaces(){
Tile[] row = row(2,0,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
private Tile[] row(int t1, int t2, int t3, int t4){
return new Tile[]{new Tile(t1), new Tile(t2), new Tile(t3), new Tile(t4)};
}
}
## Instruction:
Add a new non passing test case for merging
## Code After:
package com.alanrusnak.api2048.engine;
import com.alanrusnak.api2048.engine.model.Tile;
import org.junit.Assert;
import org.junit.Test;
public class MoveExecutorTest {
MoveExecutor moveExecutor = new MoveExecutor();
@Test
public void testSlideTile0Spaces(){
Tile[] row = row(0,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile1Spaces(){
Tile[] row = row(0,0,2,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile2Spaces(){
Tile[] row = row(0,2,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTile3Spaces(){
Tile[] row = row(2,0,0,0);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTileWithSpaceTaken(){
Tile[] row = row(2,0,0,4);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[2].getValue());
}
@Test
public void testMergeTwoTiles(){
Tile[] row = row(2,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(4, row[3].getValue());
}
private Tile[] row(int t1, int t2, int t3, int t4){
return new Tile[]{new Tile(t1), new Tile(t2), new Tile(t3), new Tile(t4)};
}
}
|
...
Assert.assertEquals(2, row[3].getValue());
}
@Test
public void testSlideTileWithSpaceTaken(){
Tile[] row = row(2,0,0,4);
moveExecutor.slideRight(row);
Assert.assertEquals(2, row[2].getValue());
}
@Test
public void testMergeTwoTiles(){
Tile[] row = row(2,0,0,2);
moveExecutor.slideRight(row);
Assert.assertEquals(4, row[3].getValue());
}
private Tile[] row(int t1, int t2, int t3, int t4){
return new Tile[]{new Tile(t1), new Tile(t2), new Tile(t3), new Tile(t4)};
}
...
|
49dc93d0fd2ab58815d91aba8afc6796cf45ce98
|
migrations/versions/0093_data_gov_uk.py
|
migrations/versions/0093_data_gov_uk.py
|
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
Revert "Remove name from organisation"
|
Revert "Remove name from organisation"
|
Python
|
mit
|
alphagov/notifications-api,alphagov/notifications-api
|
python
|
## Code Before:
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
## Instruction:
Revert "Remove name from organisation"
## Code After:
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
DATA_GOV_UK_ID = '123496d4-44cb-4324-8e0a-4187101f4bdc'
def upgrade():
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
def downgrade():
op.execute("""
DELETE FROM organisation WHERE "id" = '{}'
""".format(DATA_GOV_UK_ID))
|
...
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
...
|
c8429ec00772455c981ebb799f0c87de55bda64e
|
django_fixmystreet/backoffice/forms.py
|
django_fixmystreet/backoffice/forms.py
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
Fix user not defined error for not logged in users
|
Fix user not defined error for not logged in users
|
Python
|
agpl-3.0
|
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
|
python
|
## Code Before:
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
## Instruction:
Fix user not defined error for not logged in users
## Code After:
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
// ... existing code ...
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
// ... modified code ...
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
// ... rest of the code ...
|
7e2440c00ce75dc3ff0eac53e63d629981a9873a
|
raven/contrib/celery/__init__.py
|
raven/contrib/celery/__init__.py
|
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from raven.base import Client
class CeleryMixin(object):
def send_encoded(self, message):
"Errors through celery"
self.send_raw.delay(message)
@task(routing_key='sentry')
def send_raw(self, message):
return super(CeleryMixin, self).send_encoded(message)
class CeleryClient(CeleryMixin, Client):
pass
def register_signal(client):
def process_failure_signal(exception, traceback, sender, task_id,
signal, args, kwargs, einfo, **kw):
exc_info = (type(exception), exception, traceback)
client.captureException(
exc_info=exc_info,
extra={
'task_id': task_id,
'sender': sender,
'args': args,
'kwargs': kwargs,
})
task_failure.connect(process_failure_signal)
|
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from raven.base import Client
class CeleryMixin(object):
def send_encoded(self, message):
"Errors through celery"
self.send_raw.delay(message)
@task(routing_key='sentry')
def send_raw(self, message):
return super(CeleryMixin, self).send_encoded(message)
class CeleryClient(CeleryMixin, Client):
pass
def register_signal(client):
@task_failure.connect(weak=False)
def process_failure_signal(sender, task_id, exception, args, kwargs,
traceback, einfo, **kw):
client.captureException(
exc_info=einfo.exc_info,
extra={
'task_id': task_id,
'task': sender,
'args': args,
'kwargs': kwargs,
})
|
Fix celery task_failure signal definition
|
Fix celery task_failure signal definition
|
Python
|
bsd-3-clause
|
lepture/raven-python,recht/raven-python,lepture/raven-python,beniwohli/apm-agent-python,dbravender/raven-python,patrys/opbeat_python,recht/raven-python,jbarbuto/raven-python,getsentry/raven-python,akalipetis/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,patrys/opbeat_python,ewdurbin/raven-python,nikolas/raven-python,daikeren/opbeat_python,arthurlogilab/raven-python,icereval/raven-python,ronaldevers/raven-python,jmp0xf/raven-python,danriti/raven-python,danriti/raven-python,smarkets/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akheron/raven-python,dbravender/raven-python,smarkets/raven-python,ticosax/opbeat_python,lepture/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,lopter/raven-python-old,icereval/raven-python,ronaldevers/raven-python,johansteffner/raven-python,jmagnusson/raven-python,tarkatronic/opbeat_python,collective/mr.poe,someonehan/raven-python,jbarbuto/raven-python,inspirehep/raven-python,akalipetis/raven-python,dirtycoder/opbeat_python,smarkets/raven-python,arthurlogilab/raven-python,daikeren/opbeat_python,Photonomie/raven-python,inspirehep/raven-python,beniwohli/apm-agent-python,jbarbuto/raven-python,daikeren/opbeat_python,inspirehep/raven-python,danriti/raven-python,someonehan/raven-python,nikolas/raven-python,patrys/opbeat_python,ewdurbin/raven-python,icereval/raven-python,akheron/raven-python,jbarbuto/raven-python,inspirehep/raven-python,beniwohli/apm-agent-python,someonehan/raven-python,hzy/raven-python,percipient/raven-python,openlabs/raven,ticosax/opbeat_python,getsentry/raven-python,tarkatronic/opbeat_python,dirtycoder/opbeat_python,recht/raven-python,jmp0xf/raven-python,jmagnusson/raven-python,arthurlogilab/raven-python,percipient/raven-python,nikolas/raven-python,getsentry/raven-python,ronaldevers/raven-python,johansteffner/raven-python,akheron/raven-python,hzy/raven-python,ewdurbin/raven-python,dirtycoder/opbeat_python,percipient/raven-python,jmagnusson/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,nikolas/raven-python,johansteffner/raven-python,icereval/raven-python,hzy/raven-python,smarkets/raven-python,beniwohli/apm-agent-python,Photonomie/raven-python,Photonomie/raven-python,jmp0xf/raven-python,ticosax/opbeat_python,tarkatronic/opbeat_python,alex/raven,arthurlogilab/raven-python,akalipetis/raven-python,dbravender/raven-python,patrys/opbeat_python
|
python
|
## Code Before:
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from raven.base import Client
class CeleryMixin(object):
def send_encoded(self, message):
"Errors through celery"
self.send_raw.delay(message)
@task(routing_key='sentry')
def send_raw(self, message):
return super(CeleryMixin, self).send_encoded(message)
class CeleryClient(CeleryMixin, Client):
pass
def register_signal(client):
def process_failure_signal(exception, traceback, sender, task_id,
signal, args, kwargs, einfo, **kw):
exc_info = (type(exception), exception, traceback)
client.captureException(
exc_info=exc_info,
extra={
'task_id': task_id,
'sender': sender,
'args': args,
'kwargs': kwargs,
})
task_failure.connect(process_failure_signal)
## Instruction:
Fix celery task_failure signal definition
## Code After:
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from raven.base import Client
class CeleryMixin(object):
def send_encoded(self, message):
"Errors through celery"
self.send_raw.delay(message)
@task(routing_key='sentry')
def send_raw(self, message):
return super(CeleryMixin, self).send_encoded(message)
class CeleryClient(CeleryMixin, Client):
pass
def register_signal(client):
@task_failure.connect(weak=False)
def process_failure_signal(sender, task_id, exception, args, kwargs,
traceback, einfo, **kw):
client.captureException(
exc_info=einfo.exc_info,
extra={
'task_id': task_id,
'task': sender,
'args': args,
'kwargs': kwargs,
})
|
...
def register_signal(client):
@task_failure.connect(weak=False)
def process_failure_signal(sender, task_id, exception, args, kwargs,
traceback, einfo, **kw):
client.captureException(
exc_info=einfo.exc_info,
extra={
'task_id': task_id,
'task': sender,
'args': args,
'kwargs': kwargs,
})
...
|
d57a6cffbee08821982a93586c3a93a0f3d5d82d
|
src/test/java/com/mdsol/mauth/MAuthRequestSignerTest.java
|
src/test/java/com/mdsol/mauth/MAuthRequestSignerTest.java
|
package com.mdsol.mauth;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.lang.SecurityException;
import java.util.UUID;
/**
* Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
*
* @author Jonathan Price <[email protected]>
*/
public class MAuthRequestSignerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public final void constructorWithInvalidKeyStringThrowsException() throws IOException {
UUID appUUID = UUID.randomUUID();
String privateKeyString = "This is not a valid key";
thrown.expect(SecurityException.class);
thrown.expectMessage("Unable to process private key string");
new MAuthRequestSigner(appUUID, privateKeyString);
fail(); // Shouldn't get here - exception will have been thrown
}
}
|
package com.mdsol.mauth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Map;
import java.util.UUID;
/**
* Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
*
* @author Jonathan Price <[email protected]>
*/
public class MAuthRequestSignerTest {
private static final long TEST_EPOCH_TIME = 1424697700L;
private static String privateKeyString;
private final UUID testUUID = UUID.fromString("2a6790ab-f6c6-45be-86fc-9e9be76ec12a");
private MAuthRequestSigner mAuthRequestSigner;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUpClass() throws Exception {
privateKeyString = IOUtils.toString(MAuthRequestSigner.class.getResourceAsStream("privatekey.pem"), "UTF-8");
}
@Before
public void setUp() throws Exception {
mAuthRequestSigner = new MAuthRequestSigner(testUUID,privateKeyString);
EpochTime testEpochTime = new TestEpochTime(TEST_EPOCH_TIME);
MAuthRequestSigner.setEpochTime(testEpochTime);
}
@Test
public final void constructorWithInvalidKeyStringThrowsException() throws Exception {
String privateKeyString = "This is not a valid key";
thrown.expect(SecurityException.class);
thrown.expectMessage("Unable to process private key string");
new MAuthRequestSigner(testUUID, privateKeyString);
fail(); // Shouldn't get here - exception will have been thrown
}
@Test
public final void generateHeadersIncludesTimeHeaderWithCorrectTime() throws Exception {
Map<String, String> headers = mAuthRequestSigner.generateHeaders("GET", "/", "");
assertEquals(String.valueOf(TEST_EPOCH_TIME), headers.get("x-mws-time"));
}
}
|
Add time test and use fixed UUID and key
|
Add time test and use fixed UUID and key
|
Java
|
mit
|
mdsol/mauth-java-client,mdsol/mauth-java-client
|
java
|
## Code Before:
package com.mdsol.mauth;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.lang.SecurityException;
import java.util.UUID;
/**
* Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
*
* @author Jonathan Price <[email protected]>
*/
public class MAuthRequestSignerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public final void constructorWithInvalidKeyStringThrowsException() throws IOException {
UUID appUUID = UUID.randomUUID();
String privateKeyString = "This is not a valid key";
thrown.expect(SecurityException.class);
thrown.expectMessage("Unable to process private key string");
new MAuthRequestSigner(appUUID, privateKeyString);
fail(); // Shouldn't get here - exception will have been thrown
}
}
## Instruction:
Add time test and use fixed UUID and key
## Code After:
package com.mdsol.mauth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Map;
import java.util.UUID;
/**
* Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
*
* @author Jonathan Price <[email protected]>
*/
public class MAuthRequestSignerTest {
private static final long TEST_EPOCH_TIME = 1424697700L;
private static String privateKeyString;
private final UUID testUUID = UUID.fromString("2a6790ab-f6c6-45be-86fc-9e9be76ec12a");
private MAuthRequestSigner mAuthRequestSigner;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUpClass() throws Exception {
privateKeyString = IOUtils.toString(MAuthRequestSigner.class.getResourceAsStream("privatekey.pem"), "UTF-8");
}
@Before
public void setUp() throws Exception {
mAuthRequestSigner = new MAuthRequestSigner(testUUID,privateKeyString);
EpochTime testEpochTime = new TestEpochTime(TEST_EPOCH_TIME);
MAuthRequestSigner.setEpochTime(testEpochTime);
}
@Test
public final void constructorWithInvalidKeyStringThrowsException() throws Exception {
String privateKeyString = "This is not a valid key";
thrown.expect(SecurityException.class);
thrown.expectMessage("Unable to process private key string");
new MAuthRequestSigner(testUUID, privateKeyString);
fail(); // Shouldn't get here - exception will have been thrown
}
@Test
public final void generateHeadersIncludesTimeHeaderWithCorrectTime() throws Exception {
Map<String, String> headers = mAuthRequestSigner.generateHeaders("GET", "/", "");
assertEquals(String.valueOf(TEST_EPOCH_TIME), headers.get("x-mws-time"));
}
}
|
// ... existing code ...
package com.mdsol.mauth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Map;
import java.util.UUID;
// ... modified code ...
*/
public class MAuthRequestSignerTest {
private static final long TEST_EPOCH_TIME = 1424697700L;
private static String privateKeyString;
private final UUID testUUID = UUID.fromString("2a6790ab-f6c6-45be-86fc-9e9be76ec12a");
private MAuthRequestSigner mAuthRequestSigner;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUpClass() throws Exception {
privateKeyString = IOUtils.toString(MAuthRequestSigner.class.getResourceAsStream("privatekey.pem"), "UTF-8");
}
@Before
public void setUp() throws Exception {
mAuthRequestSigner = new MAuthRequestSigner(testUUID,privateKeyString);
EpochTime testEpochTime = new TestEpochTime(TEST_EPOCH_TIME);
MAuthRequestSigner.setEpochTime(testEpochTime);
}
@Test
public final void constructorWithInvalidKeyStringThrowsException() throws Exception {
String privateKeyString = "This is not a valid key";
thrown.expect(SecurityException.class);
thrown.expectMessage("Unable to process private key string");
new MAuthRequestSigner(testUUID, privateKeyString);
fail(); // Shouldn't get here - exception will have been thrown
}
@Test
public final void generateHeadersIncludesTimeHeaderWithCorrectTime() throws Exception {
Map<String, String> headers = mAuthRequestSigner.generateHeaders("GET", "/", "");
assertEquals(String.valueOf(TEST_EPOCH_TIME), headers.get("x-mws-time"));
}
}
// ... rest of the code ...
|
0012564e0256fed9cac624fd6c46de3043649884
|
src/main/java/org/udg/pds/simpleapp_javaee/model/Tag.java
|
src/main/java/org/udg/pds/simpleapp_javaee/model/Tag.java
|
package org.udg.pds.simpleapp_javaee.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
/**
* Default value included to remove warning. Remove or modify at will.
**/
private static final long serialVersionUID = 1L;
public Tag() {
}
public Tag(String name, String description) {
this.name = name;
this.description = description;
}
// This tells JAXB that this field can be used as ID
// Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
@Id
// Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
}
|
package org.udg.pds.simpleapp_javaee.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonDateSerializer;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonTagSerializer;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@JsonSerialize(using = JsonTagSerializer.class)
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
/**
* Default value included to remove warning. Remove or modify at will.
**/
private static final long serialVersionUID = 1L;
public Tag() {
}
public Tag(String name, String description) {
this.name = name;
this.description = description;
}
// This tells JAXB that this field can be used as ID
// Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
@Id
// Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
}
|
Add custom serializer. Add getter for description
|
Add custom serializer. Add getter for description
|
Java
|
mit
|
neich/TODOjavaee
|
java
|
## Code Before:
package org.udg.pds.simpleapp_javaee.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
/**
* Default value included to remove warning. Remove or modify at will.
**/
private static final long serialVersionUID = 1L;
public Tag() {
}
public Tag(String name, String description) {
this.name = name;
this.description = description;
}
// This tells JAXB that this field can be used as ID
// Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
@Id
// Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
}
## Instruction:
Add custom serializer. Add getter for description
## Code After:
package org.udg.pds.simpleapp_javaee.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonDateSerializer;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonTagSerializer;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@JsonSerialize(using = JsonTagSerializer.class)
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
/**
* Default value included to remove warning. Remove or modify at will.
**/
private static final long serialVersionUID = 1L;
public Tag() {
}
public Tag(String name, String description) {
this.name = name;
this.description = description;
}
// This tells JAXB that this field can be used as ID
// Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
@Id
// Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
}
|
# ... existing code ...
package org.udg.pds.simpleapp_javaee.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonDateSerializer;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonTagSerializer;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
# ... modified code ...
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@JsonSerialize(using = JsonTagSerializer.class)
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
...
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
}
# ... rest of the code ...
|
4f6400e9ecf9bbc1cee62567673c619f9a975f95
|
lib/python/opendiamond/bundle.py
|
lib/python/opendiamond/bundle.py
|
import os
import subprocess
import zipfile
def make_zipfile(path, manifest, files):
'''manifest is a string, files is a dict of filename => path pairs'''
if os.path.exists(path):
raise Exception("Refusing to clobber destination file")
zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED)
zip.writestr('opendiamond-manifest.txt', manifest)
for name, path in files.items():
zip.write(path, name)
zip.close()
def bundle_python(out, filter, blob = None):
try:
proc = subprocess.Popen(['python', os.path.realpath(filter),
'--get-manifest'], stdout = subprocess.PIPE)
except OSError:
raise Exception("Couldn't execute filter program")
manifest = proc.communicate()[0]
if proc.returncode != 0:
raise Exception("Couldn't generate filter manifest")
files = {'filter': filter}
if blob is not None:
files['blob'] = blob
make_zipfile(out, manifest, files)
|
import os
import subprocess
import zipfile
def make_zipfile(path, manifest, files):
'''manifest is a string, files is a dict of filename => path pairs'''
zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED)
zip.writestr('opendiamond-manifest.txt', manifest)
for name, path in files.items():
zip.write(path, name)
zip.close()
def bundle_python(out, filter, blob = None):
try:
proc = subprocess.Popen(['python', os.path.realpath(filter),
'--get-manifest'], stdout = subprocess.PIPE)
except OSError:
raise Exception("Couldn't execute filter program")
manifest = proc.communicate()[0]
if proc.returncode != 0:
raise Exception("Couldn't generate filter manifest")
files = {'filter': filter}
if blob is not None:
files['blob'] = blob
make_zipfile(out, manifest, files)
|
Allow make_zipfile() to clobber the destination file
|
Allow make_zipfile() to clobber the destination file
|
Python
|
epl-1.0
|
cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond
|
python
|
## Code Before:
import os
import subprocess
import zipfile
def make_zipfile(path, manifest, files):
'''manifest is a string, files is a dict of filename => path pairs'''
if os.path.exists(path):
raise Exception("Refusing to clobber destination file")
zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED)
zip.writestr('opendiamond-manifest.txt', manifest)
for name, path in files.items():
zip.write(path, name)
zip.close()
def bundle_python(out, filter, blob = None):
try:
proc = subprocess.Popen(['python', os.path.realpath(filter),
'--get-manifest'], stdout = subprocess.PIPE)
except OSError:
raise Exception("Couldn't execute filter program")
manifest = proc.communicate()[0]
if proc.returncode != 0:
raise Exception("Couldn't generate filter manifest")
files = {'filter': filter}
if blob is not None:
files['blob'] = blob
make_zipfile(out, manifest, files)
## Instruction:
Allow make_zipfile() to clobber the destination file
## Code After:
import os
import subprocess
import zipfile
def make_zipfile(path, manifest, files):
'''manifest is a string, files is a dict of filename => path pairs'''
zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED)
zip.writestr('opendiamond-manifest.txt', manifest)
for name, path in files.items():
zip.write(path, name)
zip.close()
def bundle_python(out, filter, blob = None):
try:
proc = subprocess.Popen(['python', os.path.realpath(filter),
'--get-manifest'], stdout = subprocess.PIPE)
except OSError:
raise Exception("Couldn't execute filter program")
manifest = proc.communicate()[0]
if proc.returncode != 0:
raise Exception("Couldn't generate filter manifest")
files = {'filter': filter}
if blob is not None:
files['blob'] = blob
make_zipfile(out, manifest, files)
|
...
def make_zipfile(path, manifest, files):
'''manifest is a string, files is a dict of filename => path pairs'''
zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED)
zip.writestr('opendiamond-manifest.txt', manifest)
for name, path in files.items():
...
|
a9d5ac428044304e3402f80b2b4eb3cd9efbb9ac
|
sdl_android/src/androidTest/java/com/smartdevicelink/test/util/DeviceUtil.java
|
sdl_android/src/androidTest/java/com/smartdevicelink/test/util/DeviceUtil.java
|
package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
}
|
package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
}
|
Add Genymotion to isEmulator() method
|
Add Genymotion to isEmulator() method
|
Java
|
bsd-3-clause
|
jthrun/sdl_android,smartdevicelink/sdl_android,anildahiya/sdl_android,jthrun/sdl_android
|
java
|
## Code Before:
package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
}
## Instruction:
Add Genymotion to isEmulator() method
## Code After:
package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
|| "google_sdk".equals(Build.PRODUCT);
}
}
|
# ... existing code ...
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
|| (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
# ... rest of the code ...
|
fb5c2e5df4f700fb19663bbe96e7aa2710e627ca
|
osprey/execute_dump.py
|
osprey/execute_dump.py
|
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
value = json.dumps(items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
|
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
new_items = []
# Instead of saving the parameters on their own nested dict,
# save them along the rest of elements
for item in items:
parameters = item.pop('parameters') # remove dict
item.update(parameters) # update original dict with the parameters
new_items.append(item)
value = json.dumps(new_items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
|
Store hyperparameters with the other settings
|
Store hyperparameters with the other settings
Instead of storing them in their own 'parameters' directory.
|
Python
|
apache-2.0
|
msmbuilder/osprey,msultan/osprey,pandegroup/osprey,msultan/osprey,msmbuilder/osprey,pandegroup/osprey
|
python
|
## Code Before:
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
value = json.dumps(items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
## Instruction:
Store hyperparameters with the other settings
Instead of storing them in their own 'parameters' directory.
## Code After:
from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
new_items = []
# Instead of saving the parameters on their own nested dict,
# save them along the rest of elements
for item in items:
parameters = item.pop('parameters') # remove dict
item.update(parameters) # update original dict with the parameters
new_items.append(item)
value = json.dumps(new_items)
elif args.output == 'csv':
buf = cStringIO()
outcsv = csv.writer(buf)
outcsv.writerow([column.name for column in columns])
for curr in session.query(Trial).all():
row = [getattr(curr, column.name) for column in columns]
outcsv.writerow(row)
value = buf.getvalue()
print(value)
return value
|
# ... existing code ...
if args.output == 'json':
items = [curr.to_dict() for curr in session.query(Trial).all()]
new_items = []
# Instead of saving the parameters on their own nested dict,
# save them along the rest of elements
for item in items:
parameters = item.pop('parameters') # remove dict
item.update(parameters) # update original dict with the parameters
new_items.append(item)
value = json.dumps(new_items)
elif args.output == 'csv':
buf = cStringIO()
# ... rest of the code ...
|
020e8db7ed28c3c6e6968d2d107b23e1fa8eb284
|
pcapfile/test/__main__.py
|
pcapfile/test/__main__.py
|
import unittest
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest
from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest
from pcapfile.test.protocols_network_ip import TestCase as IpTest
from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest
if __name__ == '__main__':
TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest]
SUITE = unittest.TestSuite()
LOADER = unittest.TestLoader()
for test_class in TEST_CLASSES:
SUITE.addTests(LOADER.loadTestsFromTestCase(test_class))
unittest.TextTestRunner(verbosity=2).run(SUITE)
|
import unittest
import sys
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest
from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest
from pcapfile.test.protocols_network_ip import TestCase as IpTest
from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest
if __name__ == '__main__':
TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest]
SUITE = unittest.TestSuite()
LOADER = unittest.TestLoader()
for test_class in TEST_CLASSES:
SUITE.addTests(LOADER.loadTestsFromTestCase(test_class))
result = unittest.TextTestRunner(verbosity=2).run(SUITE)
if not result.wasSuccessful():
sys.exit(1)
|
Return -1 when tests fail
|
Return -1 when tests fail
|
Python
|
isc
|
kisom/pypcapfile
|
python
|
## Code Before:
import unittest
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest
from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest
from pcapfile.test.protocols_network_ip import TestCase as IpTest
from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest
if __name__ == '__main__':
TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest]
SUITE = unittest.TestSuite()
LOADER = unittest.TestLoader()
for test_class in TEST_CLASSES:
SUITE.addTests(LOADER.loadTestsFromTestCase(test_class))
unittest.TextTestRunner(verbosity=2).run(SUITE)
## Instruction:
Return -1 when tests fail
## Code After:
import unittest
import sys
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
from pcapfile.test.savefile_test import TestCase as SavefileTest
from pcapfile.test.protocols_linklayer_ethernet import TestCase as EthernetTest
from pcapfile.test.protocols_linklayer_wifi import TestCase as WifiTest
from pcapfile.test.protocols_network_ip import TestCase as IpTest
from pcapfile.test.protocols_transport_tcp import TestCase as TcpTest
if __name__ == '__main__':
TEST_CLASSES = [SavefileTest, LinklayerTest, EthernetTest, WifiTest, IpTest, TcpTest]
SUITE = unittest.TestSuite()
LOADER = unittest.TestLoader()
for test_class in TEST_CLASSES:
SUITE.addTests(LOADER.loadTestsFromTestCase(test_class))
result = unittest.TextTestRunner(verbosity=2).run(SUITE)
if not result.wasSuccessful():
sys.exit(1)
|
# ... existing code ...
import unittest
import sys
from pcapfile.test.linklayer_test import TestCase as LinklayerTest
# ... modified code ...
LOADER = unittest.TestLoader()
for test_class in TEST_CLASSES:
SUITE.addTests(LOADER.loadTestsFromTestCase(test_class))
result = unittest.TextTestRunner(verbosity=2).run(SUITE)
if not result.wasSuccessful():
sys.exit(1)
# ... rest of the code ...
|
d463708dd79dc9c1689a8ec5aa6ae6fc4d84d8c8
|
planck-c/timers.c
|
planck-c/timers.c
|
struct timer_data_t {
long millis;
timer_callback_t timer_callback;
void* data;
};
void *timer_thread(void *data) {
struct timer_data_t *timer_data = data;
struct timespec t;
t.tv_sec = timer_data->millis / 1000;
t.tv_nsec = 1000 * 1000 * (timer_data->millis % 1000);
nanosleep(&t, NULL);
timer_data->timer_callback(timer_data->data);
free(data);
return NULL;
}
void start_timer(long millis, timer_callback_t timer_callback, void *data) {
struct timer_data_t *timer_data = malloc(sizeof(struct timer_data_t));
timer_data->millis = millis;
timer_data->timer_callback = timer_callback;
timer_data->data = data;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, timer_thread, timer_data);
}
|
struct timer_data_t {
long millis;
timer_callback_t timer_callback;
void* data;
};
void *timer_thread(void *data) {
struct timer_data_t *timer_data = data;
struct timespec t;
t.tv_sec = timer_data->millis / 1000;
t.tv_nsec = 1000 * 1000 * (timer_data->millis % 1000);
if (t.tv_sec == 0 && t.tv_nsec == 0) {
t.tv_nsec = 1; /* Evidently needed on Ubuntu 14.04 */
}
nanosleep(&t, NULL);
timer_data->timer_callback(timer_data->data);
free(data);
return NULL;
}
void start_timer(long millis, timer_callback_t timer_callback, void *data) {
struct timer_data_t *timer_data = malloc(sizeof(struct timer_data_t));
timer_data->millis = millis;
timer_data->timer_callback = timer_callback;
timer_data->data = data;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, timer_thread, timer_data);
}
|
Fix bug if timer executed with 0 ms
|
Fix bug if timer executed with 0 ms
|
C
|
epl-1.0
|
mfikes/planck,slipset/planck,mfikes/planck,mfikes/planck,slipset/planck,slipset/planck,slipset/planck,mfikes/planck,mfikes/planck,mfikes/planck,slipset/planck
|
c
|
## Code Before:
struct timer_data_t {
long millis;
timer_callback_t timer_callback;
void* data;
};
void *timer_thread(void *data) {
struct timer_data_t *timer_data = data;
struct timespec t;
t.tv_sec = timer_data->millis / 1000;
t.tv_nsec = 1000 * 1000 * (timer_data->millis % 1000);
nanosleep(&t, NULL);
timer_data->timer_callback(timer_data->data);
free(data);
return NULL;
}
void start_timer(long millis, timer_callback_t timer_callback, void *data) {
struct timer_data_t *timer_data = malloc(sizeof(struct timer_data_t));
timer_data->millis = millis;
timer_data->timer_callback = timer_callback;
timer_data->data = data;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, timer_thread, timer_data);
}
## Instruction:
Fix bug if timer executed with 0 ms
## Code After:
struct timer_data_t {
long millis;
timer_callback_t timer_callback;
void* data;
};
void *timer_thread(void *data) {
struct timer_data_t *timer_data = data;
struct timespec t;
t.tv_sec = timer_data->millis / 1000;
t.tv_nsec = 1000 * 1000 * (timer_data->millis % 1000);
if (t.tv_sec == 0 && t.tv_nsec == 0) {
t.tv_nsec = 1; /* Evidently needed on Ubuntu 14.04 */
}
nanosleep(&t, NULL);
timer_data->timer_callback(timer_data->data);
free(data);
return NULL;
}
void start_timer(long millis, timer_callback_t timer_callback, void *data) {
struct timer_data_t *timer_data = malloc(sizeof(struct timer_data_t));
timer_data->millis = millis;
timer_data->timer_callback = timer_callback;
timer_data->data = data;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, timer_thread, timer_data);
}
|
...
struct timespec t;
t.tv_sec = timer_data->millis / 1000;
t.tv_nsec = 1000 * 1000 * (timer_data->millis % 1000);
if (t.tv_sec == 0 && t.tv_nsec == 0) {
t.tv_nsec = 1; /* Evidently needed on Ubuntu 14.04 */
}
nanosleep(&t, NULL);
timer_data->timer_callback(timer_data->data);
...
|
65dcbf46e385a121cd1862fc7c4b612c6a8034e5
|
client/core/test/NetworkTest.java
|
client/core/test/NetworkTest.java
|
/**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import com.mygdx.game.controllers.PlayerNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
@Test
public void testGameInitialization() throws InterruptedException {
GameNetworkController game1 = new GameNetworkController();
GameNetworkController game2 = new GameNetworkController();
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
|
/**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
private GameNetworkController game1;
private GameNetworkController game2;
@Before
public void setup() {
game1 = new GameNetworkController();
game2 = new GameNetworkController();
}
@Test
public void testGameInitialization() throws InterruptedException {
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(11);
assertEquals("The opponent of player 1 should player 2", "mats", game1.getPlayerController().getOpponent().getUsername());
assertEquals("The opponent of player 2 should player 1", "andybb", game2.getPlayerController().getOpponent().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
|
Add test to check that the opponent is set correctly
|
Add test to check that the opponent is set correctly
|
Java
|
mit
|
andereld/progark,andereld/progark
|
java
|
## Code Before:
/**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import com.mygdx.game.controllers.PlayerNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
@Test
public void testGameInitialization() throws InterruptedException {
GameNetworkController game1 = new GameNetworkController();
GameNetworkController game2 = new GameNetworkController();
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
## Instruction:
Add test to check that the opponent is set correctly
## Code After:
/**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
private GameNetworkController game1;
private GameNetworkController game2;
@Before
public void setup() {
game1 = new GameNetworkController();
game2 = new GameNetworkController();
}
@Test
public void testGameInitialization() throws InterruptedException {
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(11);
assertEquals("The opponent of player 1 should player 2", "mats", game1.getPlayerController().getOpponent().getUsername());
assertEquals("The opponent of player 2 should player 1", "andybb", game2.getPlayerController().getOpponent().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
|
...
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
private GameNetworkController game1;
private GameNetworkController game2;
@Before
public void setup() {
game1 = new GameNetworkController();
game2 = new GameNetworkController();
}
@Test
public void testGameInitialization() throws InterruptedException {
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
...
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(11);
assertEquals("The opponent of player 1 should player 2", "mats", game1.getPlayerController().getOpponent().getUsername());
assertEquals("The opponent of player 2 should player 1", "andybb", game2.getPlayerController().getOpponent().getUsername());
}
@Test
...
|
1c48eff853f917943d43b7f24b1e18daecc50c0a
|
src/main/java/com/grayben/riskExtractor/headingMarker/nominator/NominatedText.java
|
src/main/java/com/grayben/riskExtractor/headingMarker/nominator/NominatedText.java
|
package com.grayben.riskExtractor.headingMarker.nominator;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.UnmodifiableText;
public class NominatedText
extends UnmodifiableText
implements NomineesRetrievable {
private List<Integer> nominees;
public NominatedText(List<String> stringList, List<Integer> nominees) {
super(stringList);
this.nominees = nominees;
}
public NominatedText(
UnmodifiableText unmodifiableText,
List<Integer> nominees){
super(unmodifiableText);
this.nominees = nominees;
}
public NominatedText(NominatedText nominatedText){
this(nominatedText, nominatedText.getNominees());
}
@Override
public List<Integer> getNominees() {
return nominees;
}
}
|
package com.grayben.riskExtractor.headingMarker.nominator;
import java.util.Collections;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.UnmodifiableText;
public class NominatedText
extends UnmodifiableText
implements NomineesRetrievable {
private List<Integer> nominees;
public NominatedText(List<String> stringList, List<Integer> nominees) {
super(stringList);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
public NominatedText(
UnmodifiableText unmodifiableText,
List<Integer> nominees){
super(unmodifiableText);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
public NominatedText(NominatedText nominatedText){
this(nominatedText, nominatedText.getNominees());
}
@Override
public List<Integer> getNominees() {
return Collections.unmodifiableList(this.nominees);
}
}
|
Add argument checks to pass tests
|
Add argument checks to pass tests
|
Java
|
mit
|
grayben/10K-item-extractor,grayben/10K-item-extractor
|
java
|
## Code Before:
package com.grayben.riskExtractor.headingMarker.nominator;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.UnmodifiableText;
public class NominatedText
extends UnmodifiableText
implements NomineesRetrievable {
private List<Integer> nominees;
public NominatedText(List<String> stringList, List<Integer> nominees) {
super(stringList);
this.nominees = nominees;
}
public NominatedText(
UnmodifiableText unmodifiableText,
List<Integer> nominees){
super(unmodifiableText);
this.nominees = nominees;
}
public NominatedText(NominatedText nominatedText){
this(nominatedText, nominatedText.getNominees());
}
@Override
public List<Integer> getNominees() {
return nominees;
}
}
## Instruction:
Add argument checks to pass tests
## Code After:
package com.grayben.riskExtractor.headingMarker.nominator;
import java.util.Collections;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.UnmodifiableText;
public class NominatedText
extends UnmodifiableText
implements NomineesRetrievable {
private List<Integer> nominees;
public NominatedText(List<String> stringList, List<Integer> nominees) {
super(stringList);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
public NominatedText(
UnmodifiableText unmodifiableText,
List<Integer> nominees){
super(unmodifiableText);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
public NominatedText(NominatedText nominatedText){
this(nominatedText, nominatedText.getNominees());
}
@Override
public List<Integer> getNominees() {
return Collections.unmodifiableList(this.nominees);
}
}
|
...
package com.grayben.riskExtractor.headingMarker.nominator;
import java.util.Collections;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.UnmodifiableText;
...
public NominatedText(List<String> stringList, List<Integer> nominees) {
super(stringList);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
...
UnmodifiableText unmodifiableText,
List<Integer> nominees){
super(unmodifiableText);
if (nominees == null) {
throw new NullPointerException("Attempted to pass null argument");
}
this.nominees = nominees;
}
...
@Override
public List<Integer> getNominees() {
return Collections.unmodifiableList(this.nominees);
}
}
...
|
bb1883ff25f52e7f65b31ea9582842b18af0c336
|
file4.c
|
file4.c
|
file4.c - r1
Test checkin in master1-updated
Test checkin in master2
|
file4.c - r1
Test checkin in master1-updated - updated_by_master
Test checkin in master2
Test checkin in master3
Test checkin in master4
|
Test commit in master4 branch
|
Test commit in master4 branch
|
C
|
apache-2.0
|
shahedmolla/test
|
c
|
## Code Before:
file4.c - r1
Test checkin in master1-updated
Test checkin in master2
## Instruction:
Test commit in master4 branch
## Code After:
file4.c - r1
Test checkin in master1-updated - updated_by_master
Test checkin in master2
Test checkin in master3
Test checkin in master4
|
...
file4.c - r1
Test checkin in master1-updated - updated_by_master
Test checkin in master2
Test checkin in master3
Test checkin in master4
...
|
cf6ddfdac8a56194ad1297921a390be541d773cc
|
app_info.py
|
app_info.py
|
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in version)
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCarthy <[email protected]>"
company_name = "Iogopro Software"
url = "http://iogopro.com/devo"
|
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in (version if version[2] != 0 else version[:2]))
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCarthy <[email protected]>"
company_name = "Iogopro Software"
url = "http://iogopro.com/devo"
|
Remove last digit of version number if it's 0.
|
Remove last digit of version number if it's 0.
|
Python
|
mit
|
shaurz/devo
|
python
|
## Code Before:
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in version)
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCarthy <[email protected]>"
company_name = "Iogopro Software"
url = "http://iogopro.com/devo"
## Instruction:
Remove last digit of version number if it's 0.
## Code After:
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in (version if version[2] != 0 else version[:2]))
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCarthy <[email protected]>"
company_name = "Iogopro Software"
url = "http://iogopro.com/devo"
|
// ... existing code ...
version = (1, 0, 0)
version_string = ".".join(str(x) for x in (version if version[2] != 0 else version[:2]))
identifier = "com.iogopro.devo"
// ... rest of the code ...
|
aa825fdba34b67c700d6b14695cd0dcb6d868a74
|
extensions/smallrye-context-propagation/runtime/src/main/java/io/quarkus/smallrye/context/runtime/SmallRyeContextPropagationProvider.java
|
extensions/smallrye-context-propagation/runtime/src/main/java/io/quarkus/smallrye/context/runtime/SmallRyeContextPropagationProvider.java
|
package io.quarkus.smallrye.context.runtime;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;
import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;
@ApplicationScoped
public class SmallRyeContextPropagationProvider {
private volatile ManagedExecutorImpl managedExecutor;
void initialize(ExecutorService executorService) {
managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip");
}
@Produces
@Singleton
public ThreadContext getAllThreadContext() {
return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
@Produces
@Singleton
public ManagedExecutor getAllManagedExecutor() {
return managedExecutor;
}
}
|
package io.quarkus.smallrye.context.runtime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;
import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;
@ApplicationScoped
public class SmallRyeContextPropagationProvider {
private volatile ManagedExecutorImpl managedExecutor;
void initialize(ExecutorService executorService) {
managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip") {
@Override
public void shutdown() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
@Override
public List<Runnable> shutdownNow() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
};
}
@Produces
@Singleton
public ThreadContext getAllThreadContext() {
return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
@Produces
@Singleton
public ManagedExecutor getAllManagedExecutor() {
return managedExecutor;
}
}
|
Make sure we follow the MP-CP spec and disallow our container-managed executor to be shut down
|
Make sure we follow the MP-CP spec and disallow our container-managed executor to be shut down
Since it's the underlying executor service which must be shut down, by Quarkus
|
Java
|
apache-2.0
|
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
|
java
|
## Code Before:
package io.quarkus.smallrye.context.runtime;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;
import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;
@ApplicationScoped
public class SmallRyeContextPropagationProvider {
private volatile ManagedExecutorImpl managedExecutor;
void initialize(ExecutorService executorService) {
managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip");
}
@Produces
@Singleton
public ThreadContext getAllThreadContext() {
return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
@Produces
@Singleton
public ManagedExecutor getAllManagedExecutor() {
return managedExecutor;
}
}
## Instruction:
Make sure we follow the MP-CP spec and disallow our container-managed executor to be shut down
Since it's the underlying executor service which must be shut down, by Quarkus
## Code After:
package io.quarkus.smallrye.context.runtime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;
import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;
@ApplicationScoped
public class SmallRyeContextPropagationProvider {
private volatile ManagedExecutorImpl managedExecutor;
void initialize(ExecutorService executorService) {
managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip") {
@Override
public void shutdown() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
@Override
public List<Runnable> shutdownNow() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
};
}
@Produces
@Singleton
public ThreadContext getAllThreadContext() {
return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
@Produces
@Singleton
public ManagedExecutor getAllManagedExecutor() {
return managedExecutor;
}
}
|
...
package io.quarkus.smallrye.context.runtime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
...
private volatile ManagedExecutorImpl managedExecutor;
void initialize(ExecutorService executorService) {
managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip") {
@Override
public void shutdown() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
@Override
public List<Runnable> shutdownNow() {
throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
}
};
}
@Produces
...
|
5a6fd2eb438daa1c821f970e9708d8ff5dd10115
|
src/main/java/com/simplyian/easydb/EasyDBPlugin.java
|
src/main/java/com/simplyian/easydb/EasyDBPlugin.java
|
package com.simplyian.easydb;
import com.simplyian.easydb.command.DBReloadCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* EasyDBPlugin Main class.
*/
public class EasyDBPlugin extends JavaPlugin {
private Database db;
@Override
public void onEnable() {
reloadDb();
getCommand("dbreload").setExecutor(new DBReloadCommand(this));
}
/**
* Loads the database.
*/
public void reloadDb() {
String dbUser = getConfig().getString("db.user");
String dbPass = getConfig().getString("db.pass", "");
String dbHost = getConfig().getString("db.host");
int dbPort = getConfig().getInt("db.port");
String dbName = getConfig().getString("db.name");
db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName);
}
/**
* Gets the database.
*
* @return
*/
public Database getDb() {
return db;
}
}
|
package com.simplyian.easydb;
import com.simplyian.easydb.command.DBReloadCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* EasyDBPlugin Main class.
*/
public class EasyDBPlugin extends JavaPlugin {
private Database db;
@Override
public void onEnable() {
// Make sure the config has been made
saveDefaultConfig();
reloadDb();
getCommand("dbreload").setExecutor(new DBReloadCommand(this));
}
/**
* Loads the database.
*/
public void reloadDb() {
String dbUser = getConfig().getString("db.user");
String dbPass = getConfig().getString("db.pass", "");
String dbHost = getConfig().getString("db.host");
int dbPort = getConfig().getInt("db.port");
String dbName = getConfig().getString("db.name");
db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName);
}
/**
* Gets the database.
*
* @return
*/
public Database getDb() {
return db;
}
}
|
Save the default plugin configuration.
|
Save the default plugin configuration.
Signed-off-by: Ian Macalinao <[email protected]>
|
Java
|
mit
|
simplyianm/easydb
|
java
|
## Code Before:
package com.simplyian.easydb;
import com.simplyian.easydb.command.DBReloadCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* EasyDBPlugin Main class.
*/
public class EasyDBPlugin extends JavaPlugin {
private Database db;
@Override
public void onEnable() {
reloadDb();
getCommand("dbreload").setExecutor(new DBReloadCommand(this));
}
/**
* Loads the database.
*/
public void reloadDb() {
String dbUser = getConfig().getString("db.user");
String dbPass = getConfig().getString("db.pass", "");
String dbHost = getConfig().getString("db.host");
int dbPort = getConfig().getInt("db.port");
String dbName = getConfig().getString("db.name");
db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName);
}
/**
* Gets the database.
*
* @return
*/
public Database getDb() {
return db;
}
}
## Instruction:
Save the default plugin configuration.
Signed-off-by: Ian Macalinao <[email protected]>
## Code After:
package com.simplyian.easydb;
import com.simplyian.easydb.command.DBReloadCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* EasyDBPlugin Main class.
*/
public class EasyDBPlugin extends JavaPlugin {
private Database db;
@Override
public void onEnable() {
// Make sure the config has been made
saveDefaultConfig();
reloadDb();
getCommand("dbreload").setExecutor(new DBReloadCommand(this));
}
/**
* Loads the database.
*/
public void reloadDb() {
String dbUser = getConfig().getString("db.user");
String dbPass = getConfig().getString("db.pass", "");
String dbHost = getConfig().getString("db.host");
int dbPort = getConfig().getInt("db.port");
String dbName = getConfig().getString("db.name");
db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName);
}
/**
* Gets the database.
*
* @return
*/
public Database getDb() {
return db;
}
}
|
...
@Override
public void onEnable() {
// Make sure the config has been made
saveDefaultConfig();
reloadDb();
getCommand("dbreload").setExecutor(new DBReloadCommand(this));
...
|
d71921a3dff82b038311b15fc9b56926521eaefb
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='[email protected], [email protected]',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'pycparser',
'cffi',
'numpy',
'wheel',
#'pyopencl'
],
zip_safe=False)
|
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='[email protected], [email protected]',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'numpy',
'pyopencl'
],
zip_safe=False)
|
Modify required package list to minimal pakcages.
|
Modify required package list to minimal pakcages.
|
Python
|
mit
|
PyOCL/OpenCLGA,PyOCL/oclGA,PyOCL/oclGA,PyOCL/TSP,PyOCL/TSP,PyOCL/oclGA,PyOCL/oclGA,PyOCL/OpenCLGA,PyOCL/OpenCLGA
|
python
|
## Code Before:
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='[email protected], [email protected]',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'pycparser',
'cffi',
'numpy',
'wheel',
#'pyopencl'
],
zip_safe=False)
## Instruction:
Modify required package list to minimal pakcages.
## Code After:
import os
from setuptools import setup, find_packages
package_files_paths = []
def package_files(directory):
global package_files_paths
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
if filename == '.gitignore':
continue
print(filename)
package_files_paths.append(os.path.join('..', path, filename))
package_files('OpenCLGA/ui')
package_files('OpenCLGA/kernel')
setup(name='OpenCLGA',
version='0.1',
description='Run a general purpose genetic algorithm on top of pyopencl.',
url='https://github.com/PyOCL/OpenCLGA.git',
author='John Hu(胡訓誠), Kilik Kuo(郭彥廷)',
author_email='[email protected], [email protected]',
license='MIT',
include_package_data=True,
packages=find_packages(),
package_data={
'OpenCLGA': package_files_paths,
},
install_requires=[
'numpy',
'pyopencl'
],
zip_safe=False)
|
# ... existing code ...
'OpenCLGA': package_files_paths,
},
install_requires=[
'numpy',
'pyopencl'
],
zip_safe=False)
# ... rest of the code ...
|
8653f2c0e63fecd5617dfa063878c846ddafcf97
|
tests/test_add_language/test_update_language_list.py
|
tests/test_add_language/test_update_language_list.py
|
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
kln_language_id = 'kln'
kln_language_name = 'Klingon'
add_lang.update_language_list(kln_language_id, kln_language_name)
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
kln_lang = None
for lang in langs:
if lang['id'] == kln_language_id:
kln_lang = lang
nose.assert_is_not_none(kln_lang)
nose.assert_equal(kln_lang['name'], kln_language_name)
|
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
new_language_id = 'kln'
new_language_name = 'Klingon'
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
orig_num_langs = len(langs)
add_lang.update_language_list(new_language_id, new_language_name)
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
num_langs = len(langs)
nose.assert_equal(num_langs, orig_num_langs + 1)
new_lang = None
for lang in langs:
if lang['id'] == new_language_id:
new_lang = lang
nose.assert_is_not_none(new_lang)
nose.assert_equal(new_lang['name'], new_language_name)
|
Add additional checks to update_language_list test
|
Add additional checks to update_language_list test
Also make language variable names independent of their actual values.
|
Python
|
mit
|
caleb531/youversion-suggest,caleb531/youversion-suggest
|
python
|
## Code Before:
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
kln_language_id = 'kln'
kln_language_name = 'Klingon'
add_lang.update_language_list(kln_language_id, kln_language_name)
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
kln_lang = None
for lang in langs:
if lang['id'] == kln_language_id:
kln_lang = lang
nose.assert_is_not_none(kln_lang)
nose.assert_equal(kln_lang['name'], kln_language_name)
## Instruction:
Add additional checks to update_language_list test
Also make language variable names independent of their actual values.
## Code After:
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
new_language_id = 'kln'
new_language_name = 'Klingon'
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
orig_num_langs = len(langs)
add_lang.update_language_list(new_language_id, new_language_name)
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
num_langs = len(langs)
nose.assert_equal(num_langs, orig_num_langs + 1)
new_lang = None
for lang in langs:
if lang['id'] == new_language_id:
new_lang = lang
nose.assert_is_not_none(new_lang)
nose.assert_equal(new_lang['name'], new_language_name)
|
// ... existing code ...
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
new_language_id = 'kln'
new_language_name = 'Klingon'
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
orig_num_langs = len(langs)
add_lang.update_language_list(new_language_id, new_language_name)
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
num_langs = len(langs)
nose.assert_equal(num_langs, orig_num_langs + 1)
new_lang = None
for lang in langs:
if lang['id'] == new_language_id:
new_lang = lang
nose.assert_is_not_none(new_lang)
nose.assert_equal(new_lang['name'], new_language_name)
// ... rest of the code ...
|
e84d8a8e6f6c4b1e788194d0a9a7112981294ea6
|
src/main/java/xyz/brassgoggledcoders/moarlibs/MoarLibModBase.java
|
src/main/java/xyz/brassgoggledcoders/moarlibs/MoarLibModBase.java
|
package xyz.brassgoggledcoders.moarlibs;
import net.minecraft.creativetab.CreativeTabs;
import xyz.brassgoggledcoders.boilerplate.BoilerplateModBase;
import xyz.brassgoggledcoders.moarlibs.api.IMoarRegister;
import xyz.brassgoggledcoders.moarlibs.registries.BlockContainerRegistry;
public abstract class MoarLibModBase extends BoilerplateModBase
{
public MoarLibModBase(String modid, String name, String version, CreativeTabs creativeTab)
{
super(modid, name, version, creativeTab);
}
@Override
protected void afterModuleConstruct()
{
this.getMoarRegister().registerItems(BlockContainerRegistry.getAllBlockContainers());
this.getMoarRegister().registerEntities();
}
public abstract IMoarRegister getMoarRegister();
}
|
package xyz.brassgoggledcoders.moarlibs;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import xyz.brassgoggledcoders.boilerplate.BoilerplateModBase;
import xyz.brassgoggledcoders.moarlibs.api.IMoarRegister;
import xyz.brassgoggledcoders.moarlibs.registries.BlockContainerRegistry;
public abstract class MoarLibModBase extends BoilerplateModBase
{
public MoarLibModBase(String modid, String name, String version, CreativeTabs creativeTab)
{
super(modid, name, version, creativeTab);
}
@Override
protected void afterModuleConstruct(FMLPreInitializationEvent event)
{
MoarLibs.INSTANCE.createHandlers(event);
this.getMoarRegister().registerItems(BlockContainerRegistry.getAllBlockContainers());
this.getMoarRegister().registerEntities();
}
public abstract IMoarRegister getMoarRegister();
}
|
Change MoarLibsModBase to force loading of ModuleHandler
|
Change MoarLibsModBase to force loading of ModuleHandler
|
Java
|
mit
|
BrassGoggledCoders/OpenTransport,BrassGoggledCoders/MoarLibs
|
java
|
## Code Before:
package xyz.brassgoggledcoders.moarlibs;
import net.minecraft.creativetab.CreativeTabs;
import xyz.brassgoggledcoders.boilerplate.BoilerplateModBase;
import xyz.brassgoggledcoders.moarlibs.api.IMoarRegister;
import xyz.brassgoggledcoders.moarlibs.registries.BlockContainerRegistry;
public abstract class MoarLibModBase extends BoilerplateModBase
{
public MoarLibModBase(String modid, String name, String version, CreativeTabs creativeTab)
{
super(modid, name, version, creativeTab);
}
@Override
protected void afterModuleConstruct()
{
this.getMoarRegister().registerItems(BlockContainerRegistry.getAllBlockContainers());
this.getMoarRegister().registerEntities();
}
public abstract IMoarRegister getMoarRegister();
}
## Instruction:
Change MoarLibsModBase to force loading of ModuleHandler
## Code After:
package xyz.brassgoggledcoders.moarlibs;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import xyz.brassgoggledcoders.boilerplate.BoilerplateModBase;
import xyz.brassgoggledcoders.moarlibs.api.IMoarRegister;
import xyz.brassgoggledcoders.moarlibs.registries.BlockContainerRegistry;
public abstract class MoarLibModBase extends BoilerplateModBase
{
public MoarLibModBase(String modid, String name, String version, CreativeTabs creativeTab)
{
super(modid, name, version, creativeTab);
}
@Override
protected void afterModuleConstruct(FMLPreInitializationEvent event)
{
MoarLibs.INSTANCE.createHandlers(event);
this.getMoarRegister().registerItems(BlockContainerRegistry.getAllBlockContainers());
this.getMoarRegister().registerEntities();
}
public abstract IMoarRegister getMoarRegister();
}
|
// ... existing code ...
package xyz.brassgoggledcoders.moarlibs;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import xyz.brassgoggledcoders.boilerplate.BoilerplateModBase;
import xyz.brassgoggledcoders.moarlibs.api.IMoarRegister;
import xyz.brassgoggledcoders.moarlibs.registries.BlockContainerRegistry;
// ... modified code ...
}
@Override
protected void afterModuleConstruct(FMLPreInitializationEvent event)
{
MoarLibs.INSTANCE.createHandlers(event);
this.getMoarRegister().registerItems(BlockContainerRegistry.getAllBlockContainers());
this.getMoarRegister().registerEntities();
}
// ... rest of the code ...
|
0b9c49410e6f0b4d360bac02afeadd7c1bfaecd2
|
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/model/StudyFileSummary.java
|
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/model/StudyFileSummary.java
|
package uk.ac.ebi.spot.goci.curation.model;
/**
* Created by emma on 15/04/2016.
*
* @author emma
* <p>
* An object to represent details we have about a study file
*/
public class StudyFileSummary {
private String fileName;
public StudyFileSummary(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
|
package uk.ac.ebi.spot.goci.curation.model;
/**
* Created by emma on 15/04/2016.
*
* @author emma
* <p>
* An object to represent details we have about a study file
*/
public class StudyFileSummary {
private String fileName;
private String link;
public StudyFileSummary(String fileName, String link) {
this.fileName = fileName;
this.link = link;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
|
Add file link as attribute
|
Add file link as attribute
|
Java
|
apache-2.0
|
EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci
|
java
|
## Code Before:
package uk.ac.ebi.spot.goci.curation.model;
/**
* Created by emma on 15/04/2016.
*
* @author emma
* <p>
* An object to represent details we have about a study file
*/
public class StudyFileSummary {
private String fileName;
public StudyFileSummary(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
## Instruction:
Add file link as attribute
## Code After:
package uk.ac.ebi.spot.goci.curation.model;
/**
* Created by emma on 15/04/2016.
*
* @author emma
* <p>
* An object to represent details we have about a study file
*/
public class StudyFileSummary {
private String fileName;
private String link;
public StudyFileSummary(String fileName, String link) {
this.fileName = fileName;
this.link = link;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
|
# ... existing code ...
private String fileName;
private String link;
public StudyFileSummary(String fileName, String link) {
this.fileName = fileName;
this.link = link;
}
public String getFileName() {
# ... modified code ...
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
# ... rest of the code ...
|
d9ac537f90c992c4525e6b32de9bc02c4994ef2b
|
src/test/java/com/springapp/batch/CompareEntryTest.java
|
src/test/java/com/springapp/batch/CompareEntryTest.java
|
package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-08T12:30:49+05:30"));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-09T15:30:49+05:30"));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
|
package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
public static final String BILL_DOB = "1970-01-08T12:30:49+05:30";
public static final String PAUL_DOB = "1970-01-09T15:30:49+05:30";
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse(BILL_DOB));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse(PAUL_DOB));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
|
Refactor mocked DOB to constants
|
Refactor mocked DOB to constants
|
Java
|
mit
|
rafelbev/address-book
|
java
|
## Code Before:
package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-08T12:30:49+05:30"));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-09T15:30:49+05:30"));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
## Instruction:
Refactor mocked DOB to constants
## Code After:
package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
public static final String BILL_DOB = "1970-01-08T12:30:49+05:30";
public static final String PAUL_DOB = "1970-01-09T15:30:49+05:30";
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse(BILL_DOB));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse(PAUL_DOB));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
|
...
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
public static final String BILL_DOB = "1970-01-08T12:30:49+05:30";
public static final String PAUL_DOB = "1970-01-09T15:30:49+05:30";
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse(BILL_DOB));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse(PAUL_DOB));
Assert.assertEquals(1, bill.compareTo(paul));
}
...
|
31ec9a0ae45c42c79f0e2edba3f11fc0578f33c4
|
orchard/errors/e500.py
|
orchard/errors/e500.py
|
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
"""
trailing_slash = False
@blueprint.app_errorhandler(500)
@blueprint.app_errorhandler(Exception)
def index(self) -> str:
"""
Display the error page.
:return: A page explaining the error.
"""
return flask.render_template('errors/500.html')
Error500View.register(blueprint)
|
import datetime
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
"""
trailing_slash = False
@blueprint.app_errorhandler(500)
@blueprint.app_errorhandler(Exception)
def index(self) -> str:
"""
Display the error page for internal errors and send a mail to all administrators
information them of this error.
:return: A page explaining the error.
"""
message = ('Time: {time}\n' +
'Request: {method} {path}\n' +
'Agent: {agent_platform} | {agent_browser} {agent_browser_version}\n' +
'Raw Agent: {agent}\n\n'
).format(time = datetime.datetime.now(),
method = flask.request.method,
path = flask.request.path,
agent_platform = flask.request.user_agent.platform,
agent_browser = flask.request.user_agent.browser,
agent_browser_version = flask.request.user_agent.version,
agent = flask.request.user_agent.string)
flask.current_app.logger.exception(message)
return flask.render_template('errors/500.html')
Error500View.register(blueprint)
|
Send mail to admins on all internal server errors.
|
Send mail to admins on all internal server errors.
|
Python
|
mit
|
BMeu/Orchard,BMeu/Orchard
|
python
|
## Code Before:
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
"""
trailing_slash = False
@blueprint.app_errorhandler(500)
@blueprint.app_errorhandler(Exception)
def index(self) -> str:
"""
Display the error page.
:return: A page explaining the error.
"""
return flask.render_template('errors/500.html')
Error500View.register(blueprint)
## Instruction:
Send mail to admins on all internal server errors.
## Code After:
import datetime
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
"""
trailing_slash = False
@blueprint.app_errorhandler(500)
@blueprint.app_errorhandler(Exception)
def index(self) -> str:
"""
Display the error page for internal errors and send a mail to all administrators
information them of this error.
:return: A page explaining the error.
"""
message = ('Time: {time}\n' +
'Request: {method} {path}\n' +
'Agent: {agent_platform} | {agent_browser} {agent_browser_version}\n' +
'Raw Agent: {agent}\n\n'
).format(time = datetime.datetime.now(),
method = flask.request.method,
path = flask.request.path,
agent_platform = flask.request.user_agent.platform,
agent_browser = flask.request.user_agent.browser,
agent_browser_version = flask.request.user_agent.version,
agent = flask.request.user_agent.string)
flask.current_app.logger.exception(message)
return flask.render_template('errors/500.html')
Error500View.register(blueprint)
|
// ... existing code ...
import datetime
import flask
import flask_classful
// ... modified code ...
@blueprint.app_errorhandler(Exception)
def index(self) -> str:
"""
Display the error page for internal errors and send a mail to all administrators
information them of this error.
:return: A page explaining the error.
"""
message = ('Time: {time}\n' +
'Request: {method} {path}\n' +
'Agent: {agent_platform} | {agent_browser} {agent_browser_version}\n' +
'Raw Agent: {agent}\n\n'
).format(time = datetime.datetime.now(),
method = flask.request.method,
path = flask.request.path,
agent_platform = flask.request.user_agent.platform,
agent_browser = flask.request.user_agent.browser,
agent_browser_version = flask.request.user_agent.version,
agent = flask.request.user_agent.string)
flask.current_app.logger.exception(message)
return flask.render_template('errors/500.html')
Error500View.register(blueprint)
// ... rest of the code ...
|
c50051bd8699589c20acb32764b13bdb1473ff23
|
itsy/utils.py
|
itsy/utils.py
|
from . import Task, client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
|
from datetime import datetime
from decimal import Decimal
from . import Task
from .client import Client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
client = Client()
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
|
Update test_handler() to use Client() class
|
Update test_handler() to use Client() class
|
Python
|
mit
|
storborg/itsy
|
python
|
## Code Before:
from . import Task, client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
## Instruction:
Update test_handler() to use Client() class
## Code After:
from datetime import datetime
from decimal import Decimal
from . import Task
from .client import Client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
client = Client()
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
|
# ... existing code ...
from datetime import datetime
from decimal import Decimal
from . import Task
from .client import Client
from .document import Document
# ... modified code ...
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
client = Client()
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
# ... rest of the code ...
|
e3db38f0de04ab3e1126f3417fcdd99ab7d2e81c
|
flask_ldap_login/check.py
|
flask_ldap_login/check.py
|
from argparse import ArgumentParser
from pprint import pprint
from werkzeug.utils import import_string
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('app_module',
metavar='APP_MODULE',
help='Python importible flask application e.g. my.module:app')
parser.add_argument('-u', '--username', required=True,
help='Ldap login with this username')
parser.add_argument('-p', '--password', required=True,
help='Ldap login with this password')
args = parser.parse_args()
if ':' in args.app_module:
import_name, appname = args.app_module.split(':', 1)
else:
import_name, appname = args.app_module, 'app'
module = import_string(import_name)
app = getattr(module, appname)
app.ldap_login_manager.set_raise_errors()
try:
userdata = app.ldap_login_manager.ldap_login(args.username, args.password)
print("Got userdata for %s" % args.username)
pprint(userdata)
except Exception as e:
print("User not found")
pprint(e)
if __name__ == '__main__':
main()
|
from argparse import ArgumentParser
from pprint import pprint
import getpass
from werkzeug.utils import import_string
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('app_module',
metavar='APP_MODULE',
help='Python importible flask application e.g. my.module:app')
parser.add_argument('-u', '--username', help='Ldap login with this username')
parser.add_argument('-p', '--password', help='Ldap login with this password')
args = parser.parse_args()
if ':' in args.app_module:
import_name, appname = args.app_module.split(':', 1)
else:
import_name, appname = args.app_module, 'app'
module = import_string(import_name)
app = getattr(module, appname)
username = args.username or raw_input('Username: ')
password = args.password or getpass.getpass()
app.ldap_login_manager.set_raise_errors()
try:
userdata = app.ldap_login_manager.ldap_login(username, password)
print("Got userdata for %s" % username)
pprint(userdata)
except Exception as e:
print("User not found")
pprint(e)
if __name__ == '__main__':
main()
|
Use getpass to get password
|
Use getpass to get password
|
Python
|
bsd-2-clause
|
ContinuumIO/flask-ldap-login,ContinuumIO/flask-ldap-login
|
python
|
## Code Before:
from argparse import ArgumentParser
from pprint import pprint
from werkzeug.utils import import_string
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('app_module',
metavar='APP_MODULE',
help='Python importible flask application e.g. my.module:app')
parser.add_argument('-u', '--username', required=True,
help='Ldap login with this username')
parser.add_argument('-p', '--password', required=True,
help='Ldap login with this password')
args = parser.parse_args()
if ':' in args.app_module:
import_name, appname = args.app_module.split(':', 1)
else:
import_name, appname = args.app_module, 'app'
module = import_string(import_name)
app = getattr(module, appname)
app.ldap_login_manager.set_raise_errors()
try:
userdata = app.ldap_login_manager.ldap_login(args.username, args.password)
print("Got userdata for %s" % args.username)
pprint(userdata)
except Exception as e:
print("User not found")
pprint(e)
if __name__ == '__main__':
main()
## Instruction:
Use getpass to get password
## Code After:
from argparse import ArgumentParser
from pprint import pprint
import getpass
from werkzeug.utils import import_string
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('app_module',
metavar='APP_MODULE',
help='Python importible flask application e.g. my.module:app')
parser.add_argument('-u', '--username', help='Ldap login with this username')
parser.add_argument('-p', '--password', help='Ldap login with this password')
args = parser.parse_args()
if ':' in args.app_module:
import_name, appname = args.app_module.split(':', 1)
else:
import_name, appname = args.app_module, 'app'
module = import_string(import_name)
app = getattr(module, appname)
username = args.username or raw_input('Username: ')
password = args.password or getpass.getpass()
app.ldap_login_manager.set_raise_errors()
try:
userdata = app.ldap_login_manager.ldap_login(username, password)
print("Got userdata for %s" % username)
pprint(userdata)
except Exception as e:
print("User not found")
pprint(e)
if __name__ == '__main__':
main()
|
// ... existing code ...
from argparse import ArgumentParser
from pprint import pprint
import getpass
from werkzeug.utils import import_string
// ... modified code ...
parser.add_argument('app_module',
metavar='APP_MODULE',
help='Python importible flask application e.g. my.module:app')
parser.add_argument('-u', '--username', help='Ldap login with this username')
parser.add_argument('-p', '--password', help='Ldap login with this password')
args = parser.parse_args()
if ':' in args.app_module:
...
module = import_string(import_name)
app = getattr(module, appname)
username = args.username or raw_input('Username: ')
password = args.password or getpass.getpass()
app.ldap_login_manager.set_raise_errors()
try:
userdata = app.ldap_login_manager.ldap_login(username, password)
print("Got userdata for %s" % username)
pprint(userdata)
except Exception as e:
print("User not found")
// ... rest of the code ...
|
116d3837aa817dee6e15bdc24f20eac1e56066dd
|
buildtools/__init__.py
|
buildtools/__init__.py
|
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd']
from buildtools.config import Config, Properties, replace_vars
from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv
from buildtools.bt_logging import log
|
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv']
from buildtools.config import Config, Properties, replace_vars
from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv
from buildtools.bt_logging import log
|
Add BuildEnv and ENV to __all__
|
Add BuildEnv and ENV to __all__
|
Python
|
mit
|
N3X15/python-build-tools,N3X15/python-build-tools,N3X15/python-build-tools
|
python
|
## Code Before:
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd']
from buildtools.config import Config, Properties, replace_vars
from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv
from buildtools.bt_logging import log
## Instruction:
Add BuildEnv and ENV to __all__
## Code After:
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv']
from buildtools.config import Config, Properties, replace_vars
from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv
from buildtools.bt_logging import log
|
// ... existing code ...
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv']
from buildtools.config import Config, Properties, replace_vars
from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv
// ... rest of the code ...
|
8b33cfa3e7fc39446f634d6ab45585e589a3cc85
|
marrow/mongo/core/document.py
|
marrow/mongo/core/document.py
|
from collections import OrderedDict as odict, MutableMapping
from itertools import chain
from marrow.schema import Container, Attribute
class Document(Container):
__foreign__ = 'object'
|
from collections import OrderedDict as odict, MutableMapping
from itertools import chain
from marrow.schema import Container, Attribute
from .util import py2, SENTINEL, adjust_attribute_sequence
class Document(Container):
__foreign__ = 'object'
# Mapping Protocol
def __getitem__(self, name):
return self.__data__[name]
def __setitem__(self, name, value):
self.__data__[name] = value
def __delitem__(self, name):
del self.__data__[name]
def __iter__(self):
return iter(self.__data__.keys())
def __len__(self):
return len(self.__data__)
if py2:
def keys(self):
return self.__data__.iterkeys()
def items(self):
return self.__data__.iteritems()
def values(self):
return self.__data__.itervalues()
else:
def keys(self):
return self.__data__.keys()
def items(self):
return self.__data__.items()
def values(self):
return self.__data__.values()
def __contains__(self, key):
return key in self.__data__
def __eq__(self, other):
return self.__data__ == other
def __ne__(self, other):
return self.__data__ != other
def get(self, key, default=None):
return self.__data__.get(key, default)
def clear(self):
self.__data__.clear()
def pop(self, name, default=SENTINEL):
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default)
def popitem(self):
return self.__data__.popitem()
def update(self, *args, **kw):
self.__data__.update(*args, **kw)
def setdefault(self, key, value=None):
return self.__data__.setdefault(key, value)
MutableMapping.register(Document) # Metaclass conflict if we subclass.
|
Make compatible with direct use by pymongo.
|
Make compatible with direct use by pymongo.
I.e. for direct passing to collection.insert()
|
Python
|
mit
|
marrow/mongo,djdduty/mongo,djdduty/mongo
|
python
|
## Code Before:
from collections import OrderedDict as odict, MutableMapping
from itertools import chain
from marrow.schema import Container, Attribute
class Document(Container):
__foreign__ = 'object'
## Instruction:
Make compatible with direct use by pymongo.
I.e. for direct passing to collection.insert()
## Code After:
from collections import OrderedDict as odict, MutableMapping
from itertools import chain
from marrow.schema import Container, Attribute
from .util import py2, SENTINEL, adjust_attribute_sequence
class Document(Container):
__foreign__ = 'object'
# Mapping Protocol
def __getitem__(self, name):
return self.__data__[name]
def __setitem__(self, name, value):
self.__data__[name] = value
def __delitem__(self, name):
del self.__data__[name]
def __iter__(self):
return iter(self.__data__.keys())
def __len__(self):
return len(self.__data__)
if py2:
def keys(self):
return self.__data__.iterkeys()
def items(self):
return self.__data__.iteritems()
def values(self):
return self.__data__.itervalues()
else:
def keys(self):
return self.__data__.keys()
def items(self):
return self.__data__.items()
def values(self):
return self.__data__.values()
def __contains__(self, key):
return key in self.__data__
def __eq__(self, other):
return self.__data__ == other
def __ne__(self, other):
return self.__data__ != other
def get(self, key, default=None):
return self.__data__.get(key, default)
def clear(self):
self.__data__.clear()
def pop(self, name, default=SENTINEL):
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default)
def popitem(self):
return self.__data__.popitem()
def update(self, *args, **kw):
self.__data__.update(*args, **kw)
def setdefault(self, key, value=None):
return self.__data__.setdefault(key, value)
MutableMapping.register(Document) # Metaclass conflict if we subclass.
|
// ... existing code ...
from marrow.schema import Container, Attribute
from .util import py2, SENTINEL, adjust_attribute_sequence
class Document(Container):
__foreign__ = 'object'
# Mapping Protocol
def __getitem__(self, name):
return self.__data__[name]
def __setitem__(self, name, value):
self.__data__[name] = value
def __delitem__(self, name):
del self.__data__[name]
def __iter__(self):
return iter(self.__data__.keys())
def __len__(self):
return len(self.__data__)
if py2:
def keys(self):
return self.__data__.iterkeys()
def items(self):
return self.__data__.iteritems()
def values(self):
return self.__data__.itervalues()
else:
def keys(self):
return self.__data__.keys()
def items(self):
return self.__data__.items()
def values(self):
return self.__data__.values()
def __contains__(self, key):
return key in self.__data__
def __eq__(self, other):
return self.__data__ == other
def __ne__(self, other):
return self.__data__ != other
def get(self, key, default=None):
return self.__data__.get(key, default)
def clear(self):
self.__data__.clear()
def pop(self, name, default=SENTINEL):
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default)
def popitem(self):
return self.__data__.popitem()
def update(self, *args, **kw):
self.__data__.update(*args, **kw)
def setdefault(self, key, value=None):
return self.__data__.setdefault(key, value)
MutableMapping.register(Document) # Metaclass conflict if we subclass.
// ... rest of the code ...
|
c88efde14ea79419a69a3459b5ba9ba19332fffd
|
python/algorithms/sorting/quicksort.py
|
python/algorithms/sorting/quicksort.py
|
import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
if len(items) < 2:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
|
import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if len(items) < 2:
return
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
|
Move redundant check to first point of contact
|
Move redundant check to first point of contact
|
Python
|
mit
|
vilisimo/ads,vilisimo/ads
|
python
|
## Code Before:
import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
if len(items) < 2:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
## Instruction:
Move redundant check to first point of contact
## Code After:
import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if len(items) < 2:
return
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
|
// ... existing code ...
def quicksort(items):
""" In-place quicksort with random pivot """
if len(items) < 2:
return
if items is None:
raise TypeError("Collection cannot be of type None")
// ... modified code ...
def _quicksort(items, first, last):
if first >= last:
return
pivot = items[random.randint(first, last)]
// ... rest of the code ...
|
540273ac75880925934e69275c9da1de61fbd699
|
PyBingWallpaper.py
|
PyBingWallpaper.py
|
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
#Variables:
saveDir = 'C:\BingWallPaper\\'
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
except:
i = 0
else:
i = 1
xmldoc = minidom.parse(usock)
num = 1
#Parsing the XML File
for element in xmldoc.getElementsByTagName('url'):
url = 'http://www.bing.com' + element.firstChild.nodeValue
#Get Current Date as fileName for the downloaded Picture
picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg'
urlretrieve(url, picPath)
#Convert Image
picData = Image.open(picPath)
picData.save(picPath.replace('jpg','bmp'))
picPath = picPath.replace('jpg','bmp')
num = num+1
#Set Wallpaper:
win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
|
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
if __name__=="__main__":
#Variables:
saveDir = "C:\\BingWallPaper\\"
if (not os.path.exists(saveDir)):
os.mkdir(saveDir)
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
except:
i = 0
else:
i = 1
xmldoc = minidom.parse(usock)
num = 1
#Parsing the XML File
for element in xmldoc.getElementsByTagName('url'):
url = 'http://www.bing.com' + element.firstChild.nodeValue
#Get Current Date as fileName for the downloaded Picture
picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg'
urlretrieve(url, picPath)
#Convert Image
picData = Image.open(picPath)
picData.save(picPath.replace('jpg','bmp'))
picPath = picPath.replace('jpg','bmp')
num = num+1
#Set Wallpaper:
win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
|
Create directory in case not exist
|
Create directory in case not exist
|
Python
|
mit
|
adamadanandy/PyBingWallpaper
|
python
|
## Code Before:
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
#Variables:
saveDir = 'C:\BingWallPaper\\'
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
except:
i = 0
else:
i = 1
xmldoc = minidom.parse(usock)
num = 1
#Parsing the XML File
for element in xmldoc.getElementsByTagName('url'):
url = 'http://www.bing.com' + element.firstChild.nodeValue
#Get Current Date as fileName for the downloaded Picture
picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg'
urlretrieve(url, picPath)
#Convert Image
picData = Image.open(picPath)
picData.save(picPath.replace('jpg','bmp'))
picPath = picPath.replace('jpg','bmp')
num = num+1
#Set Wallpaper:
win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
## Instruction:
Create directory in case not exist
## Code After:
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
if __name__=="__main__":
#Variables:
saveDir = "C:\\BingWallPaper\\"
if (not os.path.exists(saveDir)):
os.mkdir(saveDir)
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
except:
i = 0
else:
i = 1
xmldoc = minidom.parse(usock)
num = 1
#Parsing the XML File
for element in xmldoc.getElementsByTagName('url'):
url = 'http://www.bing.com' + element.firstChild.nodeValue
#Get Current Date as fileName for the downloaded Picture
picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg'
urlretrieve(url, picPath)
#Convert Image
picData = Image.open(picPath)
picData.save(picPath.replace('jpg','bmp'))
picPath = picPath.replace('jpg','bmp')
num = num+1
#Set Wallpaper:
win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
|
// ... existing code ...
from PIL import Image
import os
if __name__=="__main__":
#Variables:
saveDir = "C:\\BingWallPaper\\"
if (not os.path.exists(saveDir)):
os.mkdir(saveDir)
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
except:
i = 0
else:
i = 1
xmldoc = minidom.parse(usock)
num = 1
#Parsing the XML File
for element in xmldoc.getElementsByTagName('url'):
url = 'http://www.bing.com' + element.firstChild.nodeValue
#Get Current Date as fileName for the downloaded Picture
picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg'
urlretrieve(url, picPath)
#Convert Image
picData = Image.open(picPath)
picData.save(picPath.replace('jpg','bmp'))
picPath = picPath.replace('jpg','bmp')
num = num+1
#Set Wallpaper:
win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
// ... rest of the code ...
|
1d03917856c193e41b4a1622f8297e88fec00ab2
|
damn/templatetags/damn.py
|
damn/templatetags/damn.py
|
from django import template
from damn.processors import find_processor
from damn.utils import AssetRegistry, DepNode
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].items())
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simpletag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and name is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if name is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args)
return ''
|
from django import template
from ..processors import find_processor, AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].items())
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simple_tag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and name is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if name is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args)
return ''
|
Fix simpletag -> simple_tag Fix imports
|
Fix simpletag -> simple_tag
Fix imports
|
Python
|
bsd-2-clause
|
funkybob/django-amn
|
python
|
## Code Before:
from django import template
from damn.processors import find_processor
from damn.utils import AssetRegistry, DepNode
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].items())
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simpletag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and name is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if name is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args)
return ''
## Instruction:
Fix simpletag -> simple_tag
Fix imports
## Code After:
from django import template
from ..processors import find_processor, AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].items())
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simple_tag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and name is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if name is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args)
return ''
|
...
from django import template
from ..processors import find_processor, AssetRegistry
register = template.Library()
...
return AssetsNode(nodelist)
@register.simple_tag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
...
|
abce8024f998dd62a3f0bfac57391c3aebe647fa
|
setup.py
|
setup.py
|
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="[email protected]",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
from setuptools import setup
from ipyrmd import __version__
with open("README.md") as f:
long_desc = f.read()
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
long_description=long_desc,
author="Gordon Ball",
author_email="[email protected]",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
Use contents of README as long_description
|
Use contents of README as long_description
|
Python
|
mit
|
chronitis/ipyrmd
|
python
|
## Code Before:
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="[email protected]",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
## Instruction:
Use contents of README as long_description
## Code After:
from setuptools import setup
from ipyrmd import __version__
with open("README.md") as f:
long_desc = f.read()
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
long_description=long_desc,
author="Gordon Ball",
author_email="[email protected]",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
// ... existing code ...
from setuptools import setup
from ipyrmd import __version__
with open("README.md") as f:
long_desc = f.read()
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
long_description=long_desc,
author="Gordon Ball",
author_email="[email protected]",
url="https://github.com/chronitis/ipyrmd",
// ... rest of the code ...
|
698d14a2d060a3606f43116b879d773a0446d315
|
src/com/gh4a/loader/IsCollaboratorLoader.java
|
src/com/gh4a/loader/IsCollaboratorLoader.java
|
package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, app.getAuthLogin());
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
|
package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
String login = app.getAuthLogin();
if (login == null) {
return false;
}
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, login);
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
|
Fix load failure if not logged in.
|
Fix load failure if not logged in.
|
Java
|
apache-2.0
|
edyesed/gh4a,DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,Bloody-Badboy/gh4a,Bloody-Badboy/gh4a,shineM/gh4a,edyesed/gh4a,slapperwan/gh4a,slapperwan/gh4a,shekibobo/gh4a,AKiniyalocts/gh4a,sauloaguiar/gh4a,shineM/gh4a,AKiniyalocts/gh4a,sauloaguiar/gh4a,DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,shekibobo/gh4a
|
java
|
## Code Before:
package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, app.getAuthLogin());
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
## Instruction:
Fix load failure if not logged in.
## Code After:
package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
String login = app.getAuthLogin();
if (login == null) {
return false;
}
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, login);
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
|
# ... existing code ...
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
String login = app.getAuthLogin();
if (login == null) {
return false;
}
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, login);
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
# ... rest of the code ...
|
2b0a11a1adf4167fb55f9b90fc87a8b8518a24a7
|
atmo/apps.py
|
atmo/apps.py
|
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
Fix rq jobs registration check
|
Fix rq jobs registration check
|
Python
|
mpl-2.0
|
mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service
|
python
|
## Code Before:
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
## Instruction:
Fix rq jobs registration check
## Code After:
from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
# ... existing code ...
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# ... rest of the code ...
|
8f9615ebd7ae4802b1e44d6b8243aafb785a7fa3
|
pamqp/__init__.py
|
pamqp/__init__.py
|
"""AMQP Specifications and Classes"""
__author__ = 'Gavin M. Roy'
__email__ = '[email protected]'
__since__ = '2011-09-23'
__version__ '1.0.1'
from header import ProtocolHeader
from header import ContentHeader
import body
import codec
import frame
import specification
|
"""AMQP Specifications and Classes"""
__author__ = 'Gavin M. Roy'
__email__ = '[email protected]'
__since__ = '2011-09-23'
__version__ = '1.0.1'
from pamqp.header import ProtocolHeader
from pamqp.header import ContentHeader
from pamqp import body
from pamqp import codec
from pamqp import frame
from pamqp import specification
|
Use absolute imports and fix the version string
|
Use absolute imports and fix the version string
|
Python
|
bsd-3-clause
|
gmr/pamqp
|
python
|
## Code Before:
"""AMQP Specifications and Classes"""
__author__ = 'Gavin M. Roy'
__email__ = '[email protected]'
__since__ = '2011-09-23'
__version__ '1.0.1'
from header import ProtocolHeader
from header import ContentHeader
import body
import codec
import frame
import specification
## Instruction:
Use absolute imports and fix the version string
## Code After:
"""AMQP Specifications and Classes"""
__author__ = 'Gavin M. Roy'
__email__ = '[email protected]'
__since__ = '2011-09-23'
__version__ = '1.0.1'
from pamqp.header import ProtocolHeader
from pamqp.header import ContentHeader
from pamqp import body
from pamqp import codec
from pamqp import frame
from pamqp import specification
|
// ... existing code ...
__author__ = 'Gavin M. Roy'
__email__ = '[email protected]'
__since__ = '2011-09-23'
__version__ = '1.0.1'
from pamqp.header import ProtocolHeader
from pamqp.header import ContentHeader
from pamqp import body
from pamqp import codec
from pamqp import frame
from pamqp import specification
// ... rest of the code ...
|
c61e595098cd4b03828a81db98fb1e2b91b2eec0
|
anna/model/utils.py
|
anna/model/utils.py
|
import tensorflow as tf
def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None):
dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0
cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse)
if dropout > 0.0:
keep_prop = (1.0 - dropout)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell=cell,
input_keep_prob=keep_prop,
output_keep_prob=keep_prop,
state_keep_prob=keep_prop
)
if residual:
cell = tf.nn.rnn_cell.ResidualWrapper(cell)
return cell
|
import tensorflow as tf
def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None):
dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0
cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse)
if dropout > 0.0:
keep_prop = (1.0 - dropout)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell=cell,
input_keep_prob=keep_prop,
)
if residual:
cell = tf.nn.rnn_cell.ResidualWrapper(cell)
return cell
|
Remove dropout from output/state in rnn cells
|
Remove dropout from output/state in rnn cells
|
Python
|
mit
|
jpbottaro/anna
|
python
|
## Code Before:
import tensorflow as tf
def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None):
dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0
cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse)
if dropout > 0.0:
keep_prop = (1.0 - dropout)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell=cell,
input_keep_prob=keep_prop,
output_keep_prob=keep_prop,
state_keep_prob=keep_prop
)
if residual:
cell = tf.nn.rnn_cell.ResidualWrapper(cell)
return cell
## Instruction:
Remove dropout from output/state in rnn cells
## Code After:
import tensorflow as tf
def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None):
dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0
cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse)
if dropout > 0.0:
keep_prop = (1.0 - dropout)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell=cell,
input_keep_prob=keep_prop,
)
if residual:
cell = tf.nn.rnn_cell.ResidualWrapper(cell)
return cell
|
...
cell = tf.nn.rnn_cell.DropoutWrapper(
cell=cell,
input_keep_prob=keep_prop,
)
if residual:
...
|
4663d6c80d0a4f036dfb8a78623e5db54383fb3b
|
to.etc.domui/src/to/etc/domui/component/ntbl/IRowEditorEvent.java
|
to.etc.domui/src/to/etc/domui/component/ntbl/IRowEditorEvent.java
|
package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E extends NodeContainer & IEditor> {
/**
* Called after a row has been edited in an editable table component, when editing is (somehow) marked
* as complete. When called the editor's contents has been moved to the model by using the bindings. This method
* can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
*
* @param tablecomponent
* @param editor
* @param instance
* @return false to refuse the change.
* @throws Exception
*/
boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}
|
package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E extends NodeContainer> {
/**
* Called after a row has been edited in an editable table component, when editing is (somehow) marked
* as complete. When called the editor's contents has been moved to the model by using the bindings. This method
* can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
*
* @param tablecomponent
* @param editor
* @param instance
* @return false to refuse the change.
* @throws Exception
*/
boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}
|
Reduce bounds on generic: Java lacks most of the stuff to actually use it.
|
Reduce bounds on generic: Java lacks most of the stuff to actually use it.
|
Java
|
lgpl-2.1
|
fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui
|
java
|
## Code Before:
package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E extends NodeContainer & IEditor> {
/**
* Called after a row has been edited in an editable table component, when editing is (somehow) marked
* as complete. When called the editor's contents has been moved to the model by using the bindings. This method
* can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
*
* @param tablecomponent
* @param editor
* @param instance
* @return false to refuse the change.
* @throws Exception
*/
boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}
## Instruction:
Reduce bounds on generic: Java lacks most of the stuff to actually use it.
## Code After:
package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E extends NodeContainer> {
/**
* Called after a row has been edited in an editable table component, when editing is (somehow) marked
* as complete. When called the editor's contents has been moved to the model by using the bindings. This method
* can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
*
* @param tablecomponent
* @param editor
* @param instance
* @return false to refuse the change.
* @throws Exception
*/
boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}
|
# ... existing code ...
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E extends NodeContainer> {
/**
* Called after a row has been edited in an editable table component, when editing is (somehow) marked
* as complete. When called the editor's contents has been moved to the model by using the bindings. This method
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.