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
633f84411e26201233e3c68c584b236363f79f62
server/conf/vhosts/available/token.py
server/conf/vhosts/available/token.py
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree)
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child)
Allow access to root leaves.
Allow access to root leaves.
Python
mit
slaff/attachix,slaff/attachix,slaff/attachix
python
## Code Before: import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) ## Instruction: Allow access to root leaves. ## Code After: import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child)
... xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( ... userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child) ...
8e3abcd310b7e932d769f05fa0a7135cc1a53b76
setup.py
setup.py
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "excludes": [ "numpy" ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "includes": [ "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
Include missing numpy modules in build
Include missing numpy modules in build
Python
mit
igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool
python
## Code Before: from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "excludes": [ "numpy" ], "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options) ## Instruction: Include missing numpy modules in build ## Code After: from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "includes": [ "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "encodings", "idna", "motor", "packaging", "raven", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] setup(name='virtool', executables=executables, options=options)
... # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "bin_includes": [ "libcrypto.so.1.0.0", "libssl.so.1.0.0" ], "includes": [ "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format" ], "packages": [ "_cffi_backend", ...
c7ec6be4fb2c243155bcba7a41262fe683933ea9
sys/sys/snoop.h
sys/sys/snoop.h
/* * Copyright (c) 1995 Ugen J.S.Antsilevich * * Redistribution and use in source forms, with and without modification, * are permitted provided that this entire comment appears intact. * * Redistribution in binary form may occur without any restrictions. * Obviously, it would be nice if you gave credit where credit is due * but requiring it would be too onerous. * * This software is provided ``AS IS'' without any warranties of any kind. * * Snoop stuff. * * $FreeBSD$ */ #ifndef _SYS_SNOOP_H_ #define _SYS_SNOOP_H_ #include <sys/ioccom.h> /* * Theese are snoop io controls * SNPSTTY accepts 'struct snptty' as input. * If ever type or unit set to -1,snoop device * detached from its current tty. */ #define SNPSTTY _IOW('T', 90, dev_t) #define SNPGTTY _IOR('T', 89, dev_t) /* * Theese values would be returned by FIONREAD ioctl * instead of number of characters in buffer in case * of specific errors. */ #define SNP_OFLOW -1 #define SNP_TTYCLOSE -2 #define SNP_DETACH -3 #endif /* !_SYS_SNOOP_H_ */
/* * Copyright (c) 1995 Ugen J.S.Antsilevich * * Redistribution and use in source forms, with and without modification, * are permitted provided that this entire comment appears intact. * * Redistribution in binary form may occur without any restrictions. * Obviously, it would be nice if you gave credit where credit is due * but requiring it would be too onerous. * * This software is provided ``AS IS'' without any warranties of any kind. * * Snoop stuff. * * $FreeBSD$ */ #ifndef _SYS_SNOOP_H_ #define _SYS_SNOOP_H_ #ifndef _KERNEL #include <sys/types.h> #endif #include <sys/ioccom.h> /* * Theese are snoop io controls * SNPSTTY accepts 'struct snptty' as input. * If ever type or unit set to -1,snoop device * detached from its current tty. */ #define SNPSTTY _IOW('T', 90, dev_t) #define SNPGTTY _IOR('T', 89, dev_t) /* * Theese values would be returned by FIONREAD ioctl * instead of number of characters in buffer in case * of specific errors. */ #define SNP_OFLOW -1 #define SNP_TTYCLOSE -2 #define SNP_DETACH -3 #endif /* !_SYS_SNOOP_H_ */
Include <sys/types.h> in the !_KERNEL case so that this file is self-sufficient in that case (it needs dev_t). This is normal pollution for most headers that define ioctl numbers.
Include <sys/types.h> in the !_KERNEL case so that this file is self-sufficient in that case (it needs dev_t). This is normal pollution for most headers that define ioctl numbers.
C
bsd-3-clause
jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase
c
## Code Before: /* * Copyright (c) 1995 Ugen J.S.Antsilevich * * Redistribution and use in source forms, with and without modification, * are permitted provided that this entire comment appears intact. * * Redistribution in binary form may occur without any restrictions. * Obviously, it would be nice if you gave credit where credit is due * but requiring it would be too onerous. * * This software is provided ``AS IS'' without any warranties of any kind. * * Snoop stuff. * * $FreeBSD$ */ #ifndef _SYS_SNOOP_H_ #define _SYS_SNOOP_H_ #include <sys/ioccom.h> /* * Theese are snoop io controls * SNPSTTY accepts 'struct snptty' as input. * If ever type or unit set to -1,snoop device * detached from its current tty. */ #define SNPSTTY _IOW('T', 90, dev_t) #define SNPGTTY _IOR('T', 89, dev_t) /* * Theese values would be returned by FIONREAD ioctl * instead of number of characters in buffer in case * of specific errors. */ #define SNP_OFLOW -1 #define SNP_TTYCLOSE -2 #define SNP_DETACH -3 #endif /* !_SYS_SNOOP_H_ */ ## Instruction: Include <sys/types.h> in the !_KERNEL case so that this file is self-sufficient in that case (it needs dev_t). This is normal pollution for most headers that define ioctl numbers. ## Code After: /* * Copyright (c) 1995 Ugen J.S.Antsilevich * * Redistribution and use in source forms, with and without modification, * are permitted provided that this entire comment appears intact. * * Redistribution in binary form may occur without any restrictions. * Obviously, it would be nice if you gave credit where credit is due * but requiring it would be too onerous. * * This software is provided ``AS IS'' without any warranties of any kind. * * Snoop stuff. * * $FreeBSD$ */ #ifndef _SYS_SNOOP_H_ #define _SYS_SNOOP_H_ #ifndef _KERNEL #include <sys/types.h> #endif #include <sys/ioccom.h> /* * Theese are snoop io controls * SNPSTTY accepts 'struct snptty' as input. * If ever type or unit set to -1,snoop device * detached from its current tty. */ #define SNPSTTY _IOW('T', 90, dev_t) #define SNPGTTY _IOR('T', 89, dev_t) /* * Theese values would be returned by FIONREAD ioctl * instead of number of characters in buffer in case * of specific errors. */ #define SNP_OFLOW -1 #define SNP_TTYCLOSE -2 #define SNP_DETACH -3 #endif /* !_SYS_SNOOP_H_ */
// ... existing code ... #ifndef _SYS_SNOOP_H_ #define _SYS_SNOOP_H_ #ifndef _KERNEL #include <sys/types.h> #endif #include <sys/ioccom.h> /* // ... rest of the code ...
96b554bcf2409c179a17f250aa5b95f2af0bbcf0
src/edu/northwestern/bioinformatics/studycalendar/utils/accesscontrol/StudyCalendarProtectionGroup.java
src/edu/northwestern/bioinformatics/studycalendar/utils/accesscontrol/StudyCalendarProtectionGroup.java
package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol; /** * @author Rhett Sutphin */ public enum StudyCalendarProtectionGroup { BASE("BaseAccess"), STUDY_COORDINATOR("CreateStudyAccess"), // Note that this is the spelling (missing 'e') in the protection group // TODO: change to AdministrativeAccess STUDY_ADMINISTRATOR("MarkTemplatCompleteAccess"), PARTICIPANT_COORDINATOR("ParticipantAssignmentAccess"), SITE_COORDINATOR("SiteCoordinatorAccess") ; private String csmProtectionGroupName; private StudyCalendarProtectionGroup(String csmName) { this.csmProtectionGroupName = csmName; } public String csmName() { return csmProtectionGroupName; } }
package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol; /** * @author Rhett Sutphin */ public enum StudyCalendarProtectionGroup { BASE("BaseAccess"), STUDY_COORDINATOR("CreateStudyAccess"), STUDY_ADMINISTRATOR("AdministrativeAccess"), PARTICIPANT_COORDINATOR("ParticipantAssignmentAccess"), SITE_COORDINATOR("SiteCoordinatorAccess") ; private String csmProtectionGroupName; private StudyCalendarProtectionGroup(String csmName) { this.csmProtectionGroupName = csmName; } public String csmName() { return csmProtectionGroupName; } }
Update group name for STUDY_ADMINISTRATOR to match Padmaja's change
Update group name for STUDY_ADMINISTRATOR to match Padmaja's change git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@727 0d517254-b314-0410-acde-c619094fa49f
Java
bsd-3-clause
NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror
java
## Code Before: package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol; /** * @author Rhett Sutphin */ public enum StudyCalendarProtectionGroup { BASE("BaseAccess"), STUDY_COORDINATOR("CreateStudyAccess"), // Note that this is the spelling (missing 'e') in the protection group // TODO: change to AdministrativeAccess STUDY_ADMINISTRATOR("MarkTemplatCompleteAccess"), PARTICIPANT_COORDINATOR("ParticipantAssignmentAccess"), SITE_COORDINATOR("SiteCoordinatorAccess") ; private String csmProtectionGroupName; private StudyCalendarProtectionGroup(String csmName) { this.csmProtectionGroupName = csmName; } public String csmName() { return csmProtectionGroupName; } } ## Instruction: Update group name for STUDY_ADMINISTRATOR to match Padmaja's change git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@727 0d517254-b314-0410-acde-c619094fa49f ## Code After: package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol; /** * @author Rhett Sutphin */ public enum StudyCalendarProtectionGroup { BASE("BaseAccess"), STUDY_COORDINATOR("CreateStudyAccess"), STUDY_ADMINISTRATOR("AdministrativeAccess"), PARTICIPANT_COORDINATOR("ParticipantAssignmentAccess"), SITE_COORDINATOR("SiteCoordinatorAccess") ; private String csmProtectionGroupName; private StudyCalendarProtectionGroup(String csmName) { this.csmProtectionGroupName = csmName; } public String csmName() { return csmProtectionGroupName; } }
# ... existing code ... public enum StudyCalendarProtectionGroup { BASE("BaseAccess"), STUDY_COORDINATOR("CreateStudyAccess"), STUDY_ADMINISTRATOR("AdministrativeAccess"), PARTICIPANT_COORDINATOR("ParticipantAssignmentAccess"), SITE_COORDINATOR("SiteCoordinatorAccess") ; # ... rest of the code ...
c5fb6fc400e19cdeac3b2cf21ec94893b1c2e92d
srw/plotting.py
srw/plotting.py
import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour)
import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
Add show on image function
Add show on image function
Python
mit
mindriot101/srw
python
## Code Before: import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) ## Instruction: Add show on image function ## Code After: import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
... import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): ... phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8') ...
7eae3515be77d87d54f7a1b42cc53cb936e3ede3
components/DataportTest/src/client.c
components/DataportTest/src/client.c
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <camkes.h> #include <stdio.h> #include <string.h> #include <sel4/sel4.h> int run(void) { char *shello = "hello world"; printf("Starting...\n"); printf("-----------\n"); strcpy((void*)DataOut, shello); while(!*((char*)DataIn)) seL4_Yield(); printf("%s read %s\n", get_instance_name(), (char*)DataIn); return 0; }
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <camkes.h> #include <stdio.h> #include <string.h> int run(void) { char *shello = "hello world"; printf("Starting...\n"); printf("-----------\n"); strcpy((void*)DataOut, shello); while(!*((volatile char*)DataIn)); printf("%s read %s\n", get_instance_name(), (char*)DataIn); return 0; }
Remove casting away of volatile and explicit call to seL4_Yield.
Remove casting away of volatile and explicit call to seL4_Yield. This commit removes some bad style in this example. In particular, calling a seL4 system call directly from a CAmkES component is not intended. Additionally this example cast away the volatility of the dataport pointer. From what I can see, the only reason the compiler did not optimise away the repeated read of this pointer was because the loop contained a system call with a contained unrestricted memory clobber. Related to JIRA CAMKES-436
C
bsd-2-clause
seL4/camkes-apps-dataport--devel
c
## Code Before: /* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <camkes.h> #include <stdio.h> #include <string.h> #include <sel4/sel4.h> int run(void) { char *shello = "hello world"; printf("Starting...\n"); printf("-----------\n"); strcpy((void*)DataOut, shello); while(!*((char*)DataIn)) seL4_Yield(); printf("%s read %s\n", get_instance_name(), (char*)DataIn); return 0; } ## Instruction: Remove casting away of volatile and explicit call to seL4_Yield. This commit removes some bad style in this example. In particular, calling a seL4 system call directly from a CAmkES component is not intended. Additionally this example cast away the volatility of the dataport pointer. From what I can see, the only reason the compiler did not optimise away the repeated read of this pointer was because the loop contained a system call with a contained unrestricted memory clobber. Related to JIRA CAMKES-436 ## Code After: /* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <camkes.h> #include <stdio.h> #include <string.h> int run(void) { char *shello = "hello world"; printf("Starting...\n"); printf("-----------\n"); strcpy((void*)DataOut, shello); while(!*((volatile char*)DataIn)); printf("%s read %s\n", get_instance_name(), (char*)DataIn); return 0; }
# ... existing code ... #include <camkes.h> #include <stdio.h> #include <string.h> int run(void) { char *shello = "hello world"; # ... modified code ... printf("-----------\n"); strcpy((void*)DataOut, shello); while(!*((volatile char*)DataIn)); printf("%s read %s\n", get_instance_name(), (char*)DataIn); return 0; } # ... rest of the code ...
f20b984aa6bffeaccdd9b789fc543c93f20271f9
protocols/groupwise/libgroupwise/tasks/getdetailstask.h
protocols/groupwise/libgroupwise/tasks/getdetailstask.h
// // C++ Interface: getdetailstask // // Description: // // // Author: SUSE AG <>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #ifndef GETDETAILSTASK_H #define GETDETAILSTASK_H #include "gwerror.h" #include "requesttask.h" /** This task fetches the details for a set of user IDs from the server. Sometimes we get an event that only has a DN, and we need other details before showing the event to the user. @author SUSE AG */ using namespace GroupWise; class GetDetailsTask : public RequestTask { Q_OBJECT public: GetDetailsTask( Task * parent ); ~GetDetailsTask(); bool take( Transfer * transfer ); void userDNs( const QStringList & userDNs ); signals: void gotContactUserDetails( const ContactDetails & ); protected: GroupWise::ContactDetails extractUserDetails( Field::MultiField * details ); }; #endif
// // C++ Interface: getdetailstask // // Description: // // // Author: SUSE AG <>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #ifndef GETDETAILSTASK_H #define GETDETAILSTASK_H #include "gwerror.h" #include "requesttask.h" /** This task fetches the details for a set of user IDs from the server. Sometimes we get an event that only has a DN, and we need other details before showing the event to the user. @author SUSE AG */ using namespace GroupWise; class GetDetailsTask : public RequestTask { Q_OBJECT public: GetDetailsTask( Task * parent ); ~GetDetailsTask(); bool take( Transfer * transfer ); void userDNs( const QStringList & userDNs ); signals: void gotContactUserDetails( const GroupWise::ContactDetails & ); protected: GroupWise::ContactDetails extractUserDetails( Field::MultiField * details ); }; #endif
Fix broken signal connection CVS_SILENT
Fix broken signal connection CVS_SILENT svn path=/branches/groupwise_in_anger/kdenetwork/kopete/; revision=344030
C
lgpl-2.1
josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete
c
## Code Before: // // C++ Interface: getdetailstask // // Description: // // // Author: SUSE AG <>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #ifndef GETDETAILSTASK_H #define GETDETAILSTASK_H #include "gwerror.h" #include "requesttask.h" /** This task fetches the details for a set of user IDs from the server. Sometimes we get an event that only has a DN, and we need other details before showing the event to the user. @author SUSE AG */ using namespace GroupWise; class GetDetailsTask : public RequestTask { Q_OBJECT public: GetDetailsTask( Task * parent ); ~GetDetailsTask(); bool take( Transfer * transfer ); void userDNs( const QStringList & userDNs ); signals: void gotContactUserDetails( const ContactDetails & ); protected: GroupWise::ContactDetails extractUserDetails( Field::MultiField * details ); }; #endif ## Instruction: Fix broken signal connection CVS_SILENT svn path=/branches/groupwise_in_anger/kdenetwork/kopete/; revision=344030 ## Code After: // // C++ Interface: getdetailstask // // Description: // // // Author: SUSE AG <>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #ifndef GETDETAILSTASK_H #define GETDETAILSTASK_H #include "gwerror.h" #include "requesttask.h" /** This task fetches the details for a set of user IDs from the server. Sometimes we get an event that only has a DN, and we need other details before showing the event to the user. @author SUSE AG */ using namespace GroupWise; class GetDetailsTask : public RequestTask { Q_OBJECT public: GetDetailsTask( Task * parent ); ~GetDetailsTask(); bool take( Transfer * transfer ); void userDNs( const QStringList & userDNs ); signals: void gotContactUserDetails( const GroupWise::ContactDetails & ); protected: GroupWise::ContactDetails extractUserDetails( Field::MultiField * details ); }; #endif
# ... existing code ... bool take( Transfer * transfer ); void userDNs( const QStringList & userDNs ); signals: void gotContactUserDetails( const GroupWise::ContactDetails & ); protected: GroupWise::ContactDetails extractUserDetails( Field::MultiField * details ); # ... rest of the code ...
1530d35baba1c35be251cfa62082bc3da02bdab5
skype-reporting/src/main/java/org/asg/report/CleanJob.java
skype-reporting/src/main/java/org/asg/report/CleanJob.java
package org.asg.report; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CleanJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { App.statuses.clear(); } }
package org.asg.report; import org.apache.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CleanJob implements Job { private final static Logger LOGGER = Logger.getLogger(CleanJob.class); public void execute(JobExecutionContext context) throws JobExecutionException { App.statuses.clear(); LOGGER.info("Status Queue was just cleared"); } }
Add logging to status queue clearing
Add logging to status queue clearing
Java
apache-2.0
Akceptor/skype-reporting
java
## Code Before: package org.asg.report; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CleanJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { App.statuses.clear(); } } ## Instruction: Add logging to status queue clearing ## Code After: package org.asg.report; import org.apache.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CleanJob implements Job { private final static Logger LOGGER = Logger.getLogger(CleanJob.class); public void execute(JobExecutionContext context) throws JobExecutionException { App.statuses.clear(); LOGGER.info("Status Queue was just cleared"); } }
# ... existing code ... package org.asg.report; import org.apache.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CleanJob implements Job { private final static Logger LOGGER = Logger.getLogger(CleanJob.class); public void execute(JobExecutionContext context) throws JobExecutionException { App.statuses.clear(); LOGGER.info("Status Queue was just cleared"); } # ... rest of the code ...
2ecdd2feb18ef23610e55242b70b64ce0d6f6fe9
src/sentry/app.py
src/sentry/app.py
from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
Raise an import error when import_string fails on get_buffer
Raise an import error when import_string fails on get_buffer
Python
bsd-3-clause
mvaled/sentry,llonchj/sentry,argonemyth/sentry,songyi199111/sentry,1tush/sentry,fotinakis/sentry,BayanGroup/sentry,alexm92/sentry,NickPresta/sentry,fotinakis/sentry,jokey2k/sentry,looker/sentry,fuziontech/sentry,imankulov/sentry,felixbuenemann/sentry,boneyao/sentry,Kryz/sentry,drcapulet/sentry,rdio/sentry,SilentCircle/sentry,Natim/sentry,jean/sentry,kevinastone/sentry,gencer/sentry,gg7/sentry,zenefits/sentry,gencer/sentry,jokey2k/sentry,ifduyue/sentry,ngonzalvez/sentry,kevinastone/sentry,nicholasserra/sentry,wujuguang/sentry,alexm92/sentry,rdio/sentry,felixbuenemann/sentry,pauloschilling/sentry,JTCunning/sentry,hongliang5623/sentry,JamesMura/sentry,mvaled/sentry,ngonzalvez/sentry,JamesMura/sentry,daevaorn/sentry,mvaled/sentry,imankulov/sentry,wujuguang/sentry,korealerts1/sentry,argonemyth/sentry,JTCunning/sentry,drcapulet/sentry,BuildingLink/sentry,zenefits/sentry,kevinlondon/sentry,NickPresta/sentry,jokey2k/sentry,beeftornado/sentry,1tush/sentry,songyi199111/sentry,mvaled/sentry,Kryz/sentry,ewdurbin/sentry,llonchj/sentry,rdio/sentry,boneyao/sentry,Natim/sentry,BuildingLink/sentry,JackDanger/sentry,ewdurbin/sentry,mitsuhiko/sentry,Natim/sentry,korealerts1/sentry,camilonova/sentry,SilentCircle/sentry,beni55/sentry,jean/sentry,TedaLIEz/sentry,SilentCircle/sentry,daevaorn/sentry,nicholasserra/sentry,looker/sentry,mvaled/sentry,1tush/sentry,ewdurbin/sentry,wujuguang/sentry,SilentCircle/sentry,alexm92/sentry,felixbuenemann/sentry,hongliang5623/sentry,Kryz/sentry,JTCunning/sentry,NickPresta/sentry,fotinakis/sentry,TedaLIEz/sentry,mitsuhiko/sentry,vperron/sentry,beni55/sentry,vperron/sentry,zenefits/sentry,JamesMura/sentry,kevinlondon/sentry,TedaLIEz/sentry,camilonova/sentry,fotinakis/sentry,wong2/sentry,BayanGroup/sentry,nicholasserra/sentry,BuildingLink/sentry,wong2/sentry,beeftornado/sentry,zenefits/sentry,boneyao/sentry,songyi199111/sentry,drcapulet/sentry,ifduyue/sentry,gencer/sentry,llonchj/sentry,JackDanger/sentry,BuildingLink/sentry,pauloschilling/sentry,daevaorn/sentry,beeftornado/sentry,ifduyue/sentry,gg7/sentry,ifduyue/sentry,beni55/sentry,argonemyth/sentry,kevinlondon/sentry,JamesMura/sentry,BuildingLink/sentry,kevinastone/sentry,ifduyue/sentry,jean/sentry,NickPresta/sentry,ngonzalvez/sentry,jean/sentry,pauloschilling/sentry,fuziontech/sentry,korealerts1/sentry,imankulov/sentry,looker/sentry,hongliang5623/sentry,mvaled/sentry,vperron/sentry,daevaorn/sentry,fuziontech/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,looker/sentry,jean/sentry,wong2/sentry,BayanGroup/sentry,rdio/sentry,zenefits/sentry,looker/sentry,camilonova/sentry,gg7/sentry,gencer/sentry
python
## Code Before: from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() ## Instruction: Raise an import error when import_string fails on get_buffer ## Code After: from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
... def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) ...
b990ce64de70f9aec3bc4480b1a7714aa5701a45
aiohttp/__init__.py
aiohttp/__init__.py
__version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .errors import * # noqa from .helpers import * # noqa from .parsers import * # noqa from .streams import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa __all__ = (client.__all__ + # noqa client_reqrep.__all__ + # noqa errors.__all__ + # noqa helpers.__all__ + # noqa parsers.__all__ + # noqa protocol.__all__ + # noqa connector.__all__ + # noqa streams.__all__ + # noqa multidict.__all__ + # noqa multipart.__all__ + # noqa websocket_client.__all__ + # noqa ('hdrs', '__version__'))
__version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .errors import * # noqa from .helpers import * # noqa from .parsers import * # noqa from .streams import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa from .file_sender import FileSender # noqa __all__ = (client.__all__ + # noqa client_reqrep.__all__ + # noqa errors.__all__ + # noqa helpers.__all__ + # noqa parsers.__all__ + # noqa protocol.__all__ + # noqa connector.__all__ + # noqa streams.__all__ + # noqa multidict.__all__ + # noqa multipart.__all__ + # noqa websocket_client.__all__ + # noqa ('hdrs', '__version__', 'FileSender'))
Add FileSender to top level
Add FileSender to top level
Python
apache-2.0
KeepSafe/aiohttp,jettify/aiohttp,pfreixes/aiohttp,z2v/aiohttp,panda73111/aiohttp,rutsky/aiohttp,mind1master/aiohttp,singulared/aiohttp,z2v/aiohttp,juliatem/aiohttp,KeepSafe/aiohttp,Eyepea/aiohttp,arthurdarcet/aiohttp,jettify/aiohttp,moden-py/aiohttp,arthurdarcet/aiohttp,alex-eri/aiohttp-1,KeepSafe/aiohttp,panda73111/aiohttp,esaezgil/aiohttp,arthurdarcet/aiohttp,pfreixes/aiohttp,singulared/aiohttp,jettify/aiohttp,hellysmile/aiohttp,AraHaanOrg/aiohttp,esaezgil/aiohttp,esaezgil/aiohttp,z2v/aiohttp,moden-py/aiohttp,mind1master/aiohttp,panda73111/aiohttp,singulared/aiohttp,AraHaanOrg/aiohttp,juliatem/aiohttp,alex-eri/aiohttp-1,hellysmile/aiohttp,rutsky/aiohttp,playpauseandstop/aiohttp,mind1master/aiohttp,rutsky/aiohttp,moden-py/aiohttp,alex-eri/aiohttp-1
python
## Code Before: __version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .errors import * # noqa from .helpers import * # noqa from .parsers import * # noqa from .streams import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa __all__ = (client.__all__ + # noqa client_reqrep.__all__ + # noqa errors.__all__ + # noqa helpers.__all__ + # noqa parsers.__all__ + # noqa protocol.__all__ + # noqa connector.__all__ + # noqa streams.__all__ + # noqa multidict.__all__ + # noqa multipart.__all__ + # noqa websocket_client.__all__ + # noqa ('hdrs', '__version__')) ## Instruction: Add FileSender to top level ## Code After: __version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .errors import * # noqa from .helpers import * # noqa from .parsers import * # noqa from .streams import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa from .file_sender import FileSender # noqa __all__ = (client.__all__ + # noqa client_reqrep.__all__ + # noqa errors.__all__ + # noqa helpers.__all__ + # noqa parsers.__all__ + # noqa protocol.__all__ + # noqa connector.__all__ + # noqa streams.__all__ + # noqa multidict.__all__ + # noqa multipart.__all__ + # noqa websocket_client.__all__ + # noqa ('hdrs', '__version__', 'FileSender'))
# ... existing code ... from .streams import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa from .file_sender import FileSender # noqa __all__ = (client.__all__ + # noqa # ... modified code ... multidict.__all__ + # noqa multipart.__all__ + # noqa websocket_client.__all__ + # noqa ('hdrs', '__version__', 'FileSender')) # ... rest of the code ...
44514a724fc8eff464d4c26a7e9c213644c99e53
elasticsearch_flex/tasks.py
elasticsearch_flex/tasks.py
from celery import shared_task @shared_task def update_indexed_document(index, created, pk): indexed_doc = index.init_using_pk(pk) indexed_doc.prepare() indexed_doc.save() @shared_task def delete_indexed_document(index, pk): indexed_doc = index.get(id=pk) indexed_doc.delete() __all__ = ('update_indexed_document', 'delete_indexed_document')
from celery import shared_task @shared_task(rate_limit='50/m') def update_indexed_document(index, created, pk): indexed_doc = index.init_using_pk(pk) indexed_doc.prepare() indexed_doc.save() @shared_task def delete_indexed_document(index, pk): indexed_doc = index.get(id=pk) indexed_doc.delete() __all__ = ('update_indexed_document', 'delete_indexed_document')
Add rate-limit to update_indexed_document task
Add rate-limit to update_indexed_document task
Python
mit
prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex
python
## Code Before: from celery import shared_task @shared_task def update_indexed_document(index, created, pk): indexed_doc = index.init_using_pk(pk) indexed_doc.prepare() indexed_doc.save() @shared_task def delete_indexed_document(index, pk): indexed_doc = index.get(id=pk) indexed_doc.delete() __all__ = ('update_indexed_document', 'delete_indexed_document') ## Instruction: Add rate-limit to update_indexed_document task ## Code After: from celery import shared_task @shared_task(rate_limit='50/m') def update_indexed_document(index, created, pk): indexed_doc = index.init_using_pk(pk) indexed_doc.prepare() indexed_doc.save() @shared_task def delete_indexed_document(index, pk): indexed_doc = index.get(id=pk) indexed_doc.delete() __all__ = ('update_indexed_document', 'delete_indexed_document')
// ... existing code ... from celery import shared_task @shared_task(rate_limit='50/m') def update_indexed_document(index, created, pk): indexed_doc = index.init_using_pk(pk) indexed_doc.prepare() // ... rest of the code ...
0a1d7a76407f834a40d8cb96312cf6a5d322c65c
datastage/web/user/models.py
datastage/web/user/models.py
import pam from django.contrib.auth import models as auth_models class User(auth_models.User): class Meta: proxy = True def check_password(self, raw_password): return pam.authenticate(self.username, raw_password) # Monkey-patch User model auth_models.User = User
import dpam.pam from django.contrib.auth import models as auth_models class User(auth_models.User): class Meta: proxy = True def check_password(self, raw_password): return dpam.pam.authenticate(self.username, raw_password) # Monkey-patch User model auth_models.User = User
Use django_pams pam.authenticate, instead of some other pam module.
Use django_pams pam.authenticate, instead of some other pam module.
Python
mit
dataflow/DataStage,dataflow/DataStage,dataflow/DataStage
python
## Code Before: import pam from django.contrib.auth import models as auth_models class User(auth_models.User): class Meta: proxy = True def check_password(self, raw_password): return pam.authenticate(self.username, raw_password) # Monkey-patch User model auth_models.User = User ## Instruction: Use django_pams pam.authenticate, instead of some other pam module. ## Code After: import dpam.pam from django.contrib.auth import models as auth_models class User(auth_models.User): class Meta: proxy = True def check_password(self, raw_password): return dpam.pam.authenticate(self.username, raw_password) # Monkey-patch User model auth_models.User = User
// ... existing code ... import dpam.pam from django.contrib.auth import models as auth_models // ... modified code ... class Meta: proxy = True def check_password(self, raw_password): return dpam.pam.authenticate(self.username, raw_password) # Monkey-patch User model // ... rest of the code ...
103648d2cf0299c8411589608deb103fb69e0ea7
subprojects/core/src/main/groovy/org/gradle/api/artifacts/cache/ResolutionRules.java
subprojects/core/src/main/groovy/org/gradle/api/artifacts/cache/ResolutionRules.java
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.artifacts.cache; import org.gradle.api.Action; /** * Represents a set of rules/actions that can be applied during dependency resolution. * Currently these are restricted to controlling caching, but these could possibly be extended in the future to include other manipulations. */ public interface ResolutionRules { /** * Apply a rule to control resolution of dependencies. * @param rule the rule to apply */ void eachDependency(Action<? super DependencyResolutionControl> rule); /** * Apply a rule to control resolution of modules. * @param rule the rule to apply */ void eachModule(Action<? super ModuleResolutionControl> rule); /** * Apply a rule to control resolution of artifacts. * @param rule the rule to apply */ void eachArtifact(Action<? super ArtifactResolutionControl> rule); }
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.artifacts.cache; import org.gradle.api.Action; import org.gradle.api.Experimental; /** * Represents a set of rules/actions that can be applied during dependency resolution. * Currently these are restricted to controlling caching, but these could possibly be extended in the future to include other manipulations. */ @Experimental public interface ResolutionRules { /** * Apply a rule to control resolution of dependencies. * @param rule the rule to apply */ void eachDependency(Action<? super DependencyResolutionControl> rule); /** * Apply a rule to control resolution of modules. * @param rule the rule to apply */ void eachModule(Action<? super ModuleResolutionControl> rule); /** * Apply a rule to control resolution of artifacts. * @param rule the rule to apply */ void eachArtifact(Action<? super ArtifactResolutionControl> rule); }
Mark cache-control DSL entry point as @Experimental
Mark cache-control DSL entry point as @Experimental
Java
apache-2.0
robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle
java
## Code Before: /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.artifacts.cache; import org.gradle.api.Action; /** * Represents a set of rules/actions that can be applied during dependency resolution. * Currently these are restricted to controlling caching, but these could possibly be extended in the future to include other manipulations. */ public interface ResolutionRules { /** * Apply a rule to control resolution of dependencies. * @param rule the rule to apply */ void eachDependency(Action<? super DependencyResolutionControl> rule); /** * Apply a rule to control resolution of modules. * @param rule the rule to apply */ void eachModule(Action<? super ModuleResolutionControl> rule); /** * Apply a rule to control resolution of artifacts. * @param rule the rule to apply */ void eachArtifact(Action<? super ArtifactResolutionControl> rule); } ## Instruction: Mark cache-control DSL entry point as @Experimental ## Code After: /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.artifacts.cache; import org.gradle.api.Action; import org.gradle.api.Experimental; /** * Represents a set of rules/actions that can be applied during dependency resolution. * Currently these are restricted to controlling caching, but these could possibly be extended in the future to include other manipulations. */ @Experimental public interface ResolutionRules { /** * Apply a rule to control resolution of dependencies. * @param rule the rule to apply */ void eachDependency(Action<? super DependencyResolutionControl> rule); /** * Apply a rule to control resolution of modules. * @param rule the rule to apply */ void eachModule(Action<? super ModuleResolutionControl> rule); /** * Apply a rule to control resolution of artifacts. * @param rule the rule to apply */ void eachArtifact(Action<? super ArtifactResolutionControl> rule); }
... package org.gradle.api.artifacts.cache; import org.gradle.api.Action; import org.gradle.api.Experimental; /** * Represents a set of rules/actions that can be applied during dependency resolution. * Currently these are restricted to controlling caching, but these could possibly be extended in the future to include other manipulations. */ @Experimental public interface ResolutionRules { /** * Apply a rule to control resolution of dependencies. ...
90c5c9db788c0450483d71c38155fcf0a9d56220
sc2reader/engine/plugins/apm.py
sc2reader/engine/plugins/apm.py
from collections import Counter class APMTracker(object): def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.apm.values())/float(player.seconds_played)*60 else: player.avg_apm = 0
from collections import Counter class APMTracker(object): """ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is any Selection, Hotkey, or Ability event. Also provides ``player.avg_apm`` which is defined as the sum of all the above actions divided by the number of seconds played by the player (not necessarily the whole game) multiplied by 60. APM is 0 for games under 1 minute in length. """ def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.aps.values())/float(player.seconds_played)*60 else: player.avg_apm = 0
Fix the engine's APM plugin and add some documentation.
Fix the engine's APM plugin and add some documentation.
Python
mit
StoicLoofah/sc2reader,vlaufer/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,GraylinKim/sc2reader,vlaufer/sc2reader,ggtracker/sc2reader,StoicLoofah/sc2reader
python
## Code Before: from collections import Counter class APMTracker(object): def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.apm.values())/float(player.seconds_played)*60 else: player.avg_apm = 0 ## Instruction: Fix the engine's APM plugin and add some documentation. ## Code After: from collections import Counter class APMTracker(object): """ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is any Selection, Hotkey, or Ability event. Also provides ``player.avg_apm`` which is defined as the sum of all the above actions divided by the number of seconds played by the player (not necessarily the whole game) multiplied by 60. APM is 0 for games under 1 minute in length. """ def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.aps.values())/float(player.seconds_played)*60 else: player.avg_apm = 0
# ... existing code ... from collections import Counter class APMTracker(object): """ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is any Selection, Hotkey, or Ability event. Also provides ``player.avg_apm`` which is defined as the sum of all the above actions divided by the number of seconds played by the player (not necessarily the whole game) multiplied by 60. APM is 0 for games under 1 minute in length. """ def handleInitGame(self, event, replay): for player in replay.players: # ... modified code ... print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.aps.values())/float(player.seconds_played)*60 else: player.avg_apm = 0 # ... rest of the code ...
87424729061ecc77af70ea1d2213b20ed97aeec8
src/net/otfeg/itemedit/AddEchantment.java
src/net/otfeg/itemedit/AddEchantment.java
package net.otfeg.itemedit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; public class AddEchantment implements CommandExecutor { private Enchant enchant; public AddEchantment(Enchant enchant) { this.enchant = enchant; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int level = 0; if(!(sender instanceof Player)){ sender.sendMessage("Can only be used by a player"); return false; } Enchantment enchantment = this.enchant.getEnchantment(args[0]); if(enchantment==null){ sender.sendMessage("Invalid Enchantment"); return false; } try{ level = Integer.parseInt(args[1]); }catch(NumberFormatException e){ sender.sendMessage("Level must be a number."); } Player player = (Player) sender; player.getItemInHand().addUnsafeEnchantment(enchantment, level); return false; } }
package net.otfeg.itemedit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import java.lang.NumberFormatException; import java.lang.Override; public class AddEchantment implements CommandExecutor { private Enchant enchant; public AddEchantment(Enchant enchant) { this.enchant = enchant; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int level = 1; if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You can't do that!"); return true; } Player player = (Player)sender; if (args.length < 1 || args.length > 2) { return false; } Enchantment enchantment = this.enchant.getEnchantment(args[0]); if (enchantment == null) { sender.sendMessage(ChatColor.RED + "Invalid enchantment"); return true; } try { level = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Level must be a number"); return true; } player.getItemInHand().addUnsafeEnchantment(enchantment, level); } }
Fix misc errors, add some input parsing
Fix misc errors, add some input parsing
Java
mit
OTFEG/ItemEdit
java
## Code Before: package net.otfeg.itemedit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; public class AddEchantment implements CommandExecutor { private Enchant enchant; public AddEchantment(Enchant enchant) { this.enchant = enchant; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int level = 0; if(!(sender instanceof Player)){ sender.sendMessage("Can only be used by a player"); return false; } Enchantment enchantment = this.enchant.getEnchantment(args[0]); if(enchantment==null){ sender.sendMessage("Invalid Enchantment"); return false; } try{ level = Integer.parseInt(args[1]); }catch(NumberFormatException e){ sender.sendMessage("Level must be a number."); } Player player = (Player) sender; player.getItemInHand().addUnsafeEnchantment(enchantment, level); return false; } } ## Instruction: Fix misc errors, add some input parsing ## Code After: package net.otfeg.itemedit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import java.lang.NumberFormatException; import java.lang.Override; public class AddEchantment implements CommandExecutor { private Enchant enchant; public AddEchantment(Enchant enchant) { this.enchant = enchant; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int level = 1; if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You can't do that!"); return true; } Player player = (Player)sender; if (args.length < 1 || args.length > 2) { return false; } Enchantment enchantment = this.enchant.getEnchantment(args[0]); if (enchantment == null) { sender.sendMessage(ChatColor.RED + "Invalid enchantment"); return true; } try { level = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Level must be a number"); return true; } player.getItemInHand().addUnsafeEnchantment(enchantment, level); } }
... package net.otfeg.itemedit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import java.lang.NumberFormatException; import java.lang.Override; public class AddEchantment implements CommandExecutor { ... this.enchant = enchant; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int level = 1; if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You can't do that!"); return true; } Player player = (Player)sender; if (args.length < 1 || args.length > 2) { return false; } Enchantment enchantment = this.enchant.getEnchantment(args[0]); if (enchantment == null) { sender.sendMessage(ChatColor.RED + "Invalid enchantment"); return true; } try { level = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Level must be a number"); return true; } player.getItemInHand().addUnsafeEnchantment(enchantment, level); } } ...
e58c78fea4b604905333b490a22e640477d5e2d5
django_pytest/test_runner.py
django_pytest/test_runner.py
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): import sys from pkg_resources import load_entry_point sys.argv[1:] = sys.argv[2:] # Remove stop word (--) from argument list again. This separates Django # command options from py.test ones. try: del sys.argv[sys.argv.index('--')] except ValueError: pass try: entry_point = load_entry_point('py>=1.0.0', 'console_scripts', 'py.test') except ImportError: entry_point = load_entry_point('pytest>=2.0', 'console_scripts', 'py.test') sys.exit(entry_point())
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels)
Add a new TestRunner class to remove Django deprecation warnings
Add a new TestRunner class to remove Django deprecation warnings
Python
bsd-3-clause
buchuki/django-pytest,0101/django-pytest
python
## Code Before: def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): import sys from pkg_resources import load_entry_point sys.argv[1:] = sys.argv[2:] # Remove stop word (--) from argument list again. This separates Django # command options from py.test ones. try: del sys.argv[sys.argv.index('--')] except ValueError: pass try: entry_point = load_entry_point('py>=1.0.0', 'console_scripts', 'py.test') except ImportError: entry_point = load_entry_point('pytest>=2.0', 'console_scripts', 'py.test') sys.exit(entry_point()) ## Instruction: Add a new TestRunner class to remove Django deprecation warnings ## Code After: class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels)
// ... existing code ... class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is None: print ('Not yet implemented: py.test is still not able to ' 'discover the tests in all the INSTALLED_APPS as Django ' 'requires.') exit(1) pytest_args = [] if self.failfast: pytest_args.append('--exitfirst') if self.verbosity == 0: pytest_args.append('--quiet') elif self.verbosity > 1: pytest_args.append('--verbose') # Remove arguments before (--). This separates Django command options # from py.test ones. try: pytest_args_index = sys.argv.index('--') + 1 pytest_args.extend(sys.argv[pytest_args_index:]) except ValueError: pass sys.exit(pytest.main(pytest_args)) # Keep the old name to be backwards-compatible def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): runner = TestRunner(verbosity, interactive, failfast=False) runner.run_tests(test_labels) // ... rest of the code ...
cc0c43c3131161902de3a8a68688766cacd637b9
lowercasing_test/src/tests/lowercasing/fetchletters.py
lowercasing_test/src/tests/lowercasing/fetchletters.py
import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw) image = [unichr(int(c[0], 16)) for c in characters] output = u"\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
Migrate script ot Python 3
Migrate script ot Python 3
Python
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
python
## Code Before: import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw) image = [unichr(int(c[0], 16)) for c in characters] output = u"\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout) ## Instruction: Migrate script ot Python 3 ## Code After: import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
# ... existing code ... def main(raw, out): # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) # ... rest of the code ...
88a5a74ee1e3d3f3fe9e6a43bacd73b2f3f5bb96
tests/test_mongo.py
tests/test_mongo.py
import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main()
import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
Test does start a mongo instance.
Test does start a mongo instance.
Python
bsd-3-clause
jshum/dd-agent,mderomph-coolblue/dd-agent,AniruddhaSAtre/dd-agent,remh/dd-agent,lookout/dd-agent,PagerDuty/dd-agent,Mashape/dd-agent,indeedops/dd-agent,GabrielNicolasAvellaneda/dd-agent,AntoCard/powerdns-recursor_check,citrusleaf/dd-agent,benmccann/dd-agent,gphat/dd-agent,mderomph-coolblue/dd-agent,zendesk/dd-agent,huhongbo/dd-agent,a20012251/dd-agent,joelvanvelden/dd-agent,huhongbo/dd-agent,jshum/dd-agent,truthbk/dd-agent,AniruddhaSAtre/dd-agent,brettlangdon/dd-agent,jraede/dd-agent,jvassev/dd-agent,zendesk/dd-agent,jshum/dd-agent,darron/dd-agent,Mashape/dd-agent,polynomial/dd-agent,ess/dd-agent,amalakar/dd-agent,mderomph-coolblue/dd-agent,jyogi/purvar-agent,huhongbo/dd-agent,GabrielNicolasAvellaneda/dd-agent,urosgruber/dd-agent,gphat/dd-agent,cberry777/dd-agent,Mashape/dd-agent,urosgruber/dd-agent,citrusleaf/dd-agent,pfmooney/dd-agent,pmav99/praktoras,amalakar/dd-agent,a20012251/dd-agent,manolama/dd-agent,cberry777/dd-agent,JohnLZeller/dd-agent,yuecong/dd-agent,citrusleaf/dd-agent,packetloop/dd-agent,brettlangdon/dd-agent,Shopify/dd-agent,eeroniemi/dd-agent,pmav99/praktoras,darron/dd-agent,PagerDuty/dd-agent,c960657/dd-agent,JohnLZeller/dd-agent,jraede/dd-agent,benmccann/dd-agent,AniruddhaSAtre/dd-agent,pfmooney/dd-agent,ess/dd-agent,takus/dd-agent,PagerDuty/dd-agent,polynomial/dd-agent,tebriel/dd-agent,takus/dd-agent,oneandoneis2/dd-agent,AntoCard/powerdns-recursor_check,zendesk/dd-agent,joelvanvelden/dd-agent,jamesandariese/dd-agent,tebriel/dd-agent,oneandoneis2/dd-agent,guruxu/dd-agent,jraede/dd-agent,yuecong/dd-agent,oneandoneis2/dd-agent,PagerDuty/dd-agent,pmav99/praktoras,lookout/dd-agent,relateiq/dd-agent,jamesandariese/dd-agent,Shopify/dd-agent,truthbk/dd-agent,manolama/dd-agent,eeroniemi/dd-agent,indeedops/dd-agent,gphat/dd-agent,jvassev/dd-agent,urosgruber/dd-agent,jraede/dd-agent,indeedops/dd-agent,a20012251/dd-agent,huhongbo/dd-agent,mderomph-coolblue/dd-agent,Wattpad/dd-agent,remh/dd-agent,Shopify/dd-agent,takus/dd-agent,joelvanvelden/dd-agent,Mashape/dd-agent,pmav99/praktoras,relateiq/dd-agent,amalakar/dd-agent,ess/dd-agent,truthbk/dd-agent,relateiq/dd-agent,jshum/dd-agent,lookout/dd-agent,brettlangdon/dd-agent,jvassev/dd-agent,darron/dd-agent,manolama/dd-agent,eeroniemi/dd-agent,yuecong/dd-agent,ess/dd-agent,c960657/dd-agent,AntoCard/powerdns-recursor_check,zendesk/dd-agent,urosgruber/dd-agent,tebriel/dd-agent,jamesandariese/dd-agent,truthbk/dd-agent,jshum/dd-agent,relateiq/dd-agent,benmccann/dd-agent,guruxu/dd-agent,jvassev/dd-agent,pfmooney/dd-agent,packetloop/dd-agent,ess/dd-agent,amalakar/dd-agent,yuecong/dd-agent,guruxu/dd-agent,a20012251/dd-agent,polynomial/dd-agent,oneandoneis2/dd-agent,gphat/dd-agent,indeedops/dd-agent,Shopify/dd-agent,zendesk/dd-agent,AniruddhaSAtre/dd-agent,darron/dd-agent,citrusleaf/dd-agent,oneandoneis2/dd-agent,tebriel/dd-agent,packetloop/dd-agent,a20012251/dd-agent,Wattpad/dd-agent,jyogi/purvar-agent,jamesandariese/dd-agent,jamesandariese/dd-agent,JohnLZeller/dd-agent,relateiq/dd-agent,pfmooney/dd-agent,indeedops/dd-agent,jvassev/dd-agent,PagerDuty/dd-agent,brettlangdon/dd-agent,darron/dd-agent,Wattpad/dd-agent,remh/dd-agent,eeroniemi/dd-agent,c960657/dd-agent,GabrielNicolasAvellaneda/dd-agent,gphat/dd-agent,tebriel/dd-agent,guruxu/dd-agent,brettlangdon/dd-agent,benmccann/dd-agent,takus/dd-agent,remh/dd-agent,Mashape/dd-agent,manolama/dd-agent,JohnLZeller/dd-agent,JohnLZeller/dd-agent,takus/dd-agent,truthbk/dd-agent,pfmooney/dd-agent,polynomial/dd-agent,citrusleaf/dd-agent,yuecong/dd-agent,cberry777/dd-agent,c960657/dd-agent,urosgruber/dd-agent,manolama/dd-agent,AntoCard/powerdns-recursor_check,jyogi/purvar-agent,Wattpad/dd-agent,GabrielNicolasAvellaneda/dd-agent,remh/dd-agent,jyogi/purvar-agent,pmav99/praktoras,jyogi/purvar-agent,cberry777/dd-agent,mderomph-coolblue/dd-agent,lookout/dd-agent,benmccann/dd-agent,polynomial/dd-agent,amalakar/dd-agent,huhongbo/dd-agent,joelvanvelden/dd-agent,packetloop/dd-agent,packetloop/dd-agent,GabrielNicolasAvellaneda/dd-agent,AntoCard/powerdns-recursor_check,guruxu/dd-agent,AniruddhaSAtre/dd-agent,c960657/dd-agent,cberry777/dd-agent,eeroniemi/dd-agent,joelvanvelden/dd-agent,Wattpad/dd-agent,jraede/dd-agent,lookout/dd-agent,Shopify/dd-agent
python
## Code Before: import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main() ## Instruction: Test does start a mongo instance. ## Code After: import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
... import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main() ...
306bf63728015d7171a5540d89a243f0f16389df
examples/ex08_materials/include/materials/ExampleMaterial.h
examples/ex08_materials/include/materials/ExampleMaterial.h
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Material.h" #ifndef EXAMPLEMATERIAL_H #define EXAMPLEMATERIAL_H //Forward Declarations class ExampleMaterial; template<> InputParameters validParams<ExampleMaterial>(); /** * Example material class that defines a few properties. */ class ExampleMaterial : public Material { public: ExampleMaterial(const std::string & name, InputParameters parameters); protected: virtual void computeQpProperties(); private: /** * Holds a value from the input file. */ Real _diffusivity_baseline; /** * Holds the values of a coupled variable. */ VariableValue & _some_variable; /** * This is the member reference that will hold the * computed values from this material class. */ MaterialProperty<Real> & _diffusivity; }; #endif //EXAMPLEMATERIAL_H
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef EXAMPLEMATERIAL_H #define EXAMPLEMATERIAL_H #include "Material.h" //Forward Declarations class ExampleMaterial; template<> InputParameters validParams<ExampleMaterial>(); /** * Example material class that defines a few properties. */ class ExampleMaterial : public Material { public: ExampleMaterial(const std::string & name, InputParameters parameters); protected: virtual void computeQpProperties(); private: /** * Holds a value from the input file. */ Real _diffusivity_baseline; /** * Holds the values of a coupled variable. */ VariableValue & _some_variable; /** * This is the member reference that will hold the * computed values from this material class. */ MaterialProperty<Real> & _diffusivity; }; #endif //EXAMPLEMATERIAL_H
Move include statement inside include guards.
Move include statement inside include guards. r4098
C
lgpl-2.1
adamLange/moose,jinmm1992/moose,friedmud/moose,shanestafford/moose,idaholab/moose,laagesen/moose,markr622/moose,sapitts/moose,harterj/moose,jbair34/moose,tonkmr/moose,markr622/moose,permcody/moose,cpritam/moose,harterj/moose,laagesen/moose,idaholab/moose,wgapl/moose,backmari/moose,xy515258/moose,bwspenc/moose,jinmm1992/moose,yipenggao/moose,wgapl/moose,andrsd/moose,stimpsonsg/moose,jasondhales/moose,lindsayad/moose,xy515258/moose,joshua-cogliati-inl/moose,permcody/moose,shanestafford/moose,liuwenf/moose,joshua-cogliati-inl/moose,jasondhales/moose,SudiptaBiswas/moose,zzyfisherman/moose,YaqiWang/moose,cpritam/moose,liuwenf/moose,jinmm1992/moose,Chuban/moose,raghavaggarwal/moose,WilkAndy/moose,backmari/moose,joshua-cogliati-inl/moose,xy515258/moose,Chuban/moose,jiangwen84/moose,waxmanr/moose,roystgnr/moose,harterj/moose,stimpsonsg/moose,tonkmr/moose,WilkAndy/moose,waxmanr/moose,friedmud/moose,zzyfisherman/moose,adamLange/moose,zzyfisherman/moose,capitalaslash/moose,raghavaggarwal/moose,nuclear-wizard/moose,shanestafford/moose,kasra83/moose,roystgnr/moose,xy515258/moose,jhbradley/moose,YaqiWang/moose,yipenggao/moose,lindsayad/moose,bwspenc/moose,dschwen/moose,giopastor/moose,shanestafford/moose,capitalaslash/moose,danielru/moose,SudiptaBiswas/moose,permcody/moose,kasra83/moose,Chuban/moose,apc-llc/moose,mellis13/moose,nuclear-wizard/moose,cpritam/moose,idaholab/moose,wgapl/moose,waxmanr/moose,nuclear-wizard/moose,laagesen/moose,yipenggao/moose,jbair34/moose,apc-llc/moose,liuwenf/moose,andrsd/moose,roystgnr/moose,friedmud/moose,yipenggao/moose,WilkAndy/moose,backmari/moose,apc-llc/moose,katyhuff/moose,mellis13/moose,permcody/moose,bwspenc/moose,liuwenf/moose,mellis13/moose,cpritam/moose,jessecarterMOOSE/moose,tonkmr/moose,Chuban/moose,backmari/moose,joshua-cogliati-inl/moose,harterj/moose,bwspenc/moose,adamLange/moose,roystgnr/moose,danielru/moose,roystgnr/moose,tonkmr/moose,waxmanr/moose,dschwen/moose,milljm/moose,stimpsonsg/moose,kasra83/moose,markr622/moose,bwspenc/moose,liuwenf/moose,zzyfisherman/moose,tonkmr/moose,jinmm1992/moose,lindsayad/moose,laagesen/moose,milljm/moose,roystgnr/moose,jasondhales/moose,wgapl/moose,tonkmr/moose,nuclear-wizard/moose,jiangwen84/moose,WilkAndy/moose,mellis13/moose,dschwen/moose,apc-llc/moose,jiangwen84/moose,idaholab/moose,sapitts/moose,andrsd/moose,giopastor/moose,SudiptaBiswas/moose,dschwen/moose,jhbradley/moose,katyhuff/moose,lindsayad/moose,zzyfisherman/moose,adamLange/moose,sapitts/moose,sapitts/moose,jhbradley/moose,zzyfisherman/moose,shanestafford/moose,dschwen/moose,WilkAndy/moose,YaqiWang/moose,jessecarterMOOSE/moose,giopastor/moose,andrsd/moose,andrsd/moose,lindsayad/moose,jhbradley/moose,idaholab/moose,milljm/moose,SudiptaBiswas/moose,harterj/moose,milljm/moose,WilkAndy/moose,raghavaggarwal/moose,stimpsonsg/moose,markr622/moose,capitalaslash/moose,katyhuff/moose,roystgnr/moose,cpritam/moose,jasondhales/moose,friedmud/moose,capitalaslash/moose,jbair34/moose,milljm/moose,liuwenf/moose,YaqiWang/moose,cpritam/moose,jessecarterMOOSE/moose,raghavaggarwal/moose,SudiptaBiswas/moose,jessecarterMOOSE/moose,danielru/moose,danielru/moose,kasra83/moose,sapitts/moose,jessecarterMOOSE/moose,jbair34/moose,shanestafford/moose,katyhuff/moose,giopastor/moose,jiangwen84/moose,laagesen/moose
c
## Code Before: /****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Material.h" #ifndef EXAMPLEMATERIAL_H #define EXAMPLEMATERIAL_H //Forward Declarations class ExampleMaterial; template<> InputParameters validParams<ExampleMaterial>(); /** * Example material class that defines a few properties. */ class ExampleMaterial : public Material { public: ExampleMaterial(const std::string & name, InputParameters parameters); protected: virtual void computeQpProperties(); private: /** * Holds a value from the input file. */ Real _diffusivity_baseline; /** * Holds the values of a coupled variable. */ VariableValue & _some_variable; /** * This is the member reference that will hold the * computed values from this material class. */ MaterialProperty<Real> & _diffusivity; }; #endif //EXAMPLEMATERIAL_H ## Instruction: Move include statement inside include guards. r4098 ## Code After: /****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef EXAMPLEMATERIAL_H #define EXAMPLEMATERIAL_H #include "Material.h" //Forward Declarations class ExampleMaterial; template<> InputParameters validParams<ExampleMaterial>(); /** * Example material class that defines a few properties. */ class ExampleMaterial : public Material { public: ExampleMaterial(const std::string & name, InputParameters parameters); protected: virtual void computeQpProperties(); private: /** * Holds a value from the input file. */ Real _diffusivity_baseline; /** * Holds the values of a coupled variable. */ VariableValue & _some_variable; /** * This is the member reference that will hold the * computed values from this material class. */ MaterialProperty<Real> & _diffusivity; }; #endif //EXAMPLEMATERIAL_H
// ... existing code ... /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef EXAMPLEMATERIAL_H #define EXAMPLEMATERIAL_H #include "Material.h" //Forward Declarations class ExampleMaterial; // ... rest of the code ...
bf961cf69386404b03d46ebc3ab34b7da804f016
test/test_ttt.py
test/test_ttt.py
import unittest from ttt import ttt class TestPat(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_000_something(self): pass if __name__ == '__main__': import sys sys.exit(unittest.main())
class Test: def setup(self): pass def teardown(self): pass def test_(self): pass
Use pytest instead of unittest
Use pytest instead of unittest
Python
isc
yerejm/ttt,yerejm/ttt
python
## Code Before: import unittest from ttt import ttt class TestPat(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_000_something(self): pass if __name__ == '__main__': import sys sys.exit(unittest.main()) ## Instruction: Use pytest instead of unittest ## Code After: class Test: def setup(self): pass def teardown(self): pass def test_(self): pass
// ... existing code ... class Test: def setup(self): pass def teardown(self): pass def test_(self): pass // ... rest of the code ...
fea9c44be08719f0fcca98a1d531a83c9db4c6af
tests/test_urls.py
tests/test_urls.py
import pytest from django.conf import settings from pytest_django_test.compat import force_text pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden') try: from django.core.urlresolvers import is_valid_path except ImportError: from django.core.urlresolvers import resolve, Resolver404 def is_valid_path(path, urlconf=None): """Return True if path resolves against default URL resolver This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!'
import pytest from django.conf import settings from pytest_django_test.compat import force_text try: from django.core.urlresolvers import is_valid_path except ImportError: from django.core.urlresolvers import resolve, Resolver404 def is_valid_path(path, urlconf=None): """Return True if path resolves against default URL resolver This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!' def test_urls_cache_is_cleared(testdir): testdir.makepyfile(myurls=""" from django.conf.urls import patterns, url def fake_view(request): pass urlpatterns = patterns('', url(r'first/$', fake_view, name='first')) """) testdir.makepyfile(""" from django.core.urlresolvers import reverse, NoReverseMatch import pytest @pytest.mark.urls('myurls') def test_something(): reverse('first') def test_something_else(): with pytest.raises(NoReverseMatch): reverse('first') """) result = testdir.runpytest() assert result.ret == 0
Add test to confirm url cache is cleared
Add test to confirm url cache is cleared
Python
bsd-3-clause
pombredanne/pytest_django,thedrow/pytest-django,ktosiek/pytest-django,tomviner/pytest-django
python
## Code Before: import pytest from django.conf import settings from pytest_django_test.compat import force_text pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden') try: from django.core.urlresolvers import is_valid_path except ImportError: from django.core.urlresolvers import resolve, Resolver404 def is_valid_path(path, urlconf=None): """Return True if path resolves against default URL resolver This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!' ## Instruction: Add test to confirm url cache is cleared ## Code After: import pytest from django.conf import settings from pytest_django_test.compat import force_text try: from django.core.urlresolvers import is_valid_path except ImportError: from django.core.urlresolvers import resolve, Resolver404 def is_valid_path(path, urlconf=None): """Return True if path resolves against default URL resolver This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!' def test_urls_cache_is_cleared(testdir): testdir.makepyfile(myurls=""" from django.conf.urls import patterns, url def fake_view(request): pass urlpatterns = patterns('', url(r'first/$', fake_view, name='first')) """) testdir.makepyfile(""" from django.core.urlresolvers import reverse, NoReverseMatch import pytest @pytest.mark.urls('myurls') def test_something(): reverse('first') def test_something_else(): with pytest.raises(NoReverseMatch): reverse('first') """) result = testdir.runpytest() assert result.ret == 0
// ... existing code ... from pytest_django_test.compat import force_text try: from django.core.urlresolvers import is_valid_path // ... modified code ... return False @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls(): assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden' assert is_valid_path('/overridden_url/') @pytest.mark.urls('pytest_django_test.urls_overridden') def test_urls_client(client): response = client.get('/overridden_url/') assert force_text(response.content) == 'Overridden urlconf works!' def test_urls_cache_is_cleared(testdir): testdir.makepyfile(myurls=""" from django.conf.urls import patterns, url def fake_view(request): pass urlpatterns = patterns('', url(r'first/$', fake_view, name='first')) """) testdir.makepyfile(""" from django.core.urlresolvers import reverse, NoReverseMatch import pytest @pytest.mark.urls('myurls') def test_something(): reverse('first') def test_something_else(): with pytest.raises(NoReverseMatch): reverse('first') """) result = testdir.runpytest() assert result.ret == 0 // ... rest of the code ...
6d635a94121a9038c7c5b80b9851a086e69728b6
scripts/wiggle_to_binned_array.py
scripts/wiggle_to_binned_array.py
from __future__ import division import sys import psyco_full import bx.wiggle from bx.binned_array import BinnedArray from fpconst import isNaN import cookbook.doc_optparse import misc def read_scores( f ): scores_by_chrom = dict() return scores_by_chrom def main(): # Parse command line options, args = cookbook.doc_optparse.parse( __doc__ ) try: score_fname = args[0] out_fname = args[1] except: cookbook.doc_optparse.exit() scores = BinnedArray() ## last_chrom = None for i, ( chrom, pos, val ) in enumerate( bx.wiggle.Reader( misc.open_compressed( score_fname ) ) ): #if last_chrom is None: # last_chrom = chrom #else: # assert chrom == last_chrom, "This script expects a 'wiggle' input on only one chromosome" scores[pos] = val # Status if i % 10000 == 0: print i, "scores processed" out = open( out_fname, "w" ) scores.to_file( out ) out.close() if __name__ == "__main__": main()
from __future__ import division import sys import psyco_full import bx.wiggle from bx.binned_array import BinnedArray from fpconst import isNaN import cookbook.doc_optparse import misc def main(): # Parse command line options, args = cookbook.doc_optparse.parse( __doc__ ) try: if options.comp: comp_type = options.comp else: comp_type = None score_fname = args[0] out_fname = args[1] except: cookbook.doc_optparse.exit() scores = BinnedArray() ## last_chrom = None for i, ( chrom, pos, val ) in enumerate( bx.wiggle.Reader( misc.open_compressed( score_fname ) ) ): #if last_chrom is None: # last_chrom = chrom #else: # assert chrom == last_chrom, "This script expects a 'wiggle' input on only one chromosome" scores[pos] = val # Status if i % 10000 == 0: print i, "scores processed" out = open( out_fname, "w" ) if comp_type: scores.to_file( out, comp_type=comp_type ) else: scores.to_file( out ) out.close() if __name__ == "__main__": main()
Allow specifying compression type on command line.
Allow specifying compression type on command line.
Python
mit
uhjish/bx-python,uhjish/bx-python,uhjish/bx-python
python
## Code Before: from __future__ import division import sys import psyco_full import bx.wiggle from bx.binned_array import BinnedArray from fpconst import isNaN import cookbook.doc_optparse import misc def read_scores( f ): scores_by_chrom = dict() return scores_by_chrom def main(): # Parse command line options, args = cookbook.doc_optparse.parse( __doc__ ) try: score_fname = args[0] out_fname = args[1] except: cookbook.doc_optparse.exit() scores = BinnedArray() ## last_chrom = None for i, ( chrom, pos, val ) in enumerate( bx.wiggle.Reader( misc.open_compressed( score_fname ) ) ): #if last_chrom is None: # last_chrom = chrom #else: # assert chrom == last_chrom, "This script expects a 'wiggle' input on only one chromosome" scores[pos] = val # Status if i % 10000 == 0: print i, "scores processed" out = open( out_fname, "w" ) scores.to_file( out ) out.close() if __name__ == "__main__": main() ## Instruction: Allow specifying compression type on command line. ## Code After: from __future__ import division import sys import psyco_full import bx.wiggle from bx.binned_array import BinnedArray from fpconst import isNaN import cookbook.doc_optparse import misc def main(): # Parse command line options, args = cookbook.doc_optparse.parse( __doc__ ) try: if options.comp: comp_type = options.comp else: comp_type = None score_fname = args[0] out_fname = args[1] except: cookbook.doc_optparse.exit() scores = BinnedArray() ## last_chrom = None for i, ( chrom, pos, val ) in enumerate( bx.wiggle.Reader( misc.open_compressed( score_fname ) ) ): #if last_chrom is None: # last_chrom = chrom #else: # assert chrom == last_chrom, "This script expects a 'wiggle' input on only one chromosome" scores[pos] = val # Status if i % 10000 == 0: print i, "scores processed" out = open( out_fname, "w" ) if comp_type: scores.to_file( out, comp_type=comp_type ) else: scores.to_file( out ) out.close() if __name__ == "__main__": main()
// ... existing code ... import cookbook.doc_optparse import misc def main(): # Parse command line options, args = cookbook.doc_optparse.parse( __doc__ ) try: if options.comp: comp_type = options.comp else: comp_type = None score_fname = args[0] out_fname = args[1] except: // ... modified code ... cookbook.doc_optparse.exit() scores = BinnedArray() ## last_chrom = None for i, ( chrom, pos, val ) in enumerate( bx.wiggle.Reader( misc.open_compressed( score_fname ) ) ): #if last_chrom is None: ... if i % 10000 == 0: print i, "scores processed" out = open( out_fname, "w" ) if comp_type: scores.to_file( out, comp_type=comp_type ) else: scores.to_file( out ) out.close() if __name__ == "__main__": main() // ... rest of the code ...
798ac11f35717200acf9ed5b0b28ae8a781f629c
baselibrary/src/main/java/com/kogimobile/android/baselibrary/navigation/FragmentNavigator.java
baselibrary/src/main/java/com/kogimobile/android/baselibrary/navigation/FragmentNavigator.java
package com.kogimobile.android.baselibrary.navigation; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class FragmentNavigator { public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), false, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), addToBackStack, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId, String fragmentTag, boolean addToBackStack, boolean allowCommitStateLoss){ FragmentTransaction ft = manager.beginTransaction(); ft.addToBackStack(fragmentTag); ft.replace(containerId, fragment,fragmentTag); if(allowCommitStateLoss){ ft.commitAllowingStateLoss(); } else { ft.commit(); } if(addToBackStack) { } } public static void cleanFragmentStack(FragmentManager fm) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } }
package com.kogimobile.android.baselibrary.navigation; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class FragmentNavigator { public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), false, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), addToBackStack, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId, String fragmentTag, boolean addToBackStack, boolean allowCommitStateLoss){ FragmentTransaction ft = manager.beginTransaction(); ft.replace(containerId, fragment,fragmentTag); if(addToBackStack) { ft.addToBackStack(fragmentTag); } if(allowCommitStateLoss){ ft.commitAllowingStateLoss(); } else { ft.commit(); } } public static void cleanFragmentStack(FragmentManager fm) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } }
Fix problem with fragment backstack
[Fix]: Fix problem with fragment backstack Resolves: # See also: #
Java
apache-2.0
KogiMobileSAS/AndroidBaseLibrary
java
## Code Before: package com.kogimobile.android.baselibrary.navigation; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class FragmentNavigator { public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), false, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), addToBackStack, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId, String fragmentTag, boolean addToBackStack, boolean allowCommitStateLoss){ FragmentTransaction ft = manager.beginTransaction(); ft.addToBackStack(fragmentTag); ft.replace(containerId, fragment,fragmentTag); if(allowCommitStateLoss){ ft.commitAllowingStateLoss(); } else { ft.commit(); } if(addToBackStack) { } } public static void cleanFragmentStack(FragmentManager fm) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } ## Instruction: [Fix]: Fix problem with fragment backstack Resolves: # See also: # ## Code After: package com.kogimobile.android.baselibrary.navigation; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class FragmentNavigator { public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), false, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){ navigateTo( manager, fragment, containerId, fragment.getClass().getSimpleName(), addToBackStack, false ); } public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId, String fragmentTag, boolean addToBackStack, boolean allowCommitStateLoss){ FragmentTransaction ft = manager.beginTransaction(); ft.replace(containerId, fragment,fragmentTag); if(addToBackStack) { ft.addToBackStack(fragmentTag); } if(allowCommitStateLoss){ ft.commitAllowingStateLoss(); } else { ft.commit(); } } public static void cleanFragmentStack(FragmentManager fm) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } }
# ... existing code ... package com.kogimobile.android.baselibrary.navigation; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; # ... modified code ... boolean addToBackStack, boolean allowCommitStateLoss){ FragmentTransaction ft = manager.beginTransaction(); ft.replace(containerId, fragment,fragmentTag); if(addToBackStack) { ft.addToBackStack(fragmentTag); } if(allowCommitStateLoss){ ft.commitAllowingStateLoss(); } else { ft.commit(); } } # ... rest of the code ...
8ddcabe29dfaa6716578664224620fc5a0116a2b
tests/test_cli_eigenvals.py
tests/test_cli_eigenvals.py
import os import pytest import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner import tbmodels from tbmodels._cli import cli def test_cli_eigenvals(sample): samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
import os import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner from tbmodels._cli import cli def test_cli_eigenvals(sample): """ Test the 'eigenvals' command. """ samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
Fix pre-commit issue for the cli_eigenvals test.
Fix pre-commit issue for the cli_eigenvals test.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
python
## Code Before: import os import pytest import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner import tbmodels from tbmodels._cli import cli def test_cli_eigenvals(sample): samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10) ## Instruction: Fix pre-commit issue for the cli_eigenvals test. ## Code After: import os import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner from tbmodels._cli import cli def test_cli_eigenvals(sample): """ Test the 'eigenvals' command. """ samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
# ... existing code ... import os import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner from tbmodels._cli import cli def test_cli_eigenvals(sample): """ Test the 'eigenvals' command. """ samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: # ... rest of the code ...
e289c48727573a43a062213fd52bc43a2781bd8b
indra/trips/trips_api.py
indra/trips/trips_api.py
import sys import trips_client from processor import TripsProcessor def process_text(text): html = trips_client.send_query(text) xml = trips_client.get_xml(html) trips_client.save_xml(xml, 'test.xml') return process_xml(xml) def process_xml(xml_string): tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation() tp.get_activating_mods() tp.get_activations() return tp if __name__ == '__main__': input_fname = 'phosphorylate.xml' if len(sys.argv) > 1: input_fname = sys.argv[1] try: fh = open(input_fname, 'rt') except IOError: print 'Could not open file %s' % input_fname sys.exit() xml_string = fh.read() tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation()
import sys import trips_client from processor import TripsProcessor def process_text(text, save_xml_name='trips_output.xml'): html = trips_client.send_query(text) xml = trips_client.get_xml(html) if save_xml_name: trips_client.save_xml(xml, save_xml_name) return process_xml(xml) def process_xml(xml_string): tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation() tp.get_activating_mods() tp.get_activations() return tp if __name__ == '__main__': input_fname = 'phosphorylate.xml' if len(sys.argv) > 1: input_fname = sys.argv[1] try: fh = open(input_fname, 'rt') except IOError: print 'Could not open file %s' % input_fname sys.exit() xml_string = fh.read() tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation()
Add save xml name argument to TRIPS API
Add save xml name argument to TRIPS API
Python
bsd-2-clause
jmuhlich/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra
python
## Code Before: import sys import trips_client from processor import TripsProcessor def process_text(text): html = trips_client.send_query(text) xml = trips_client.get_xml(html) trips_client.save_xml(xml, 'test.xml') return process_xml(xml) def process_xml(xml_string): tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation() tp.get_activating_mods() tp.get_activations() return tp if __name__ == '__main__': input_fname = 'phosphorylate.xml' if len(sys.argv) > 1: input_fname = sys.argv[1] try: fh = open(input_fname, 'rt') except IOError: print 'Could not open file %s' % input_fname sys.exit() xml_string = fh.read() tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation() ## Instruction: Add save xml name argument to TRIPS API ## Code After: import sys import trips_client from processor import TripsProcessor def process_text(text, save_xml_name='trips_output.xml'): html = trips_client.send_query(text) xml = trips_client.get_xml(html) if save_xml_name: trips_client.save_xml(xml, save_xml_name) return process_xml(xml) def process_xml(xml_string): tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation() tp.get_activating_mods() tp.get_activations() return tp if __name__ == '__main__': input_fname = 'phosphorylate.xml' if len(sys.argv) > 1: input_fname = sys.argv[1] try: fh = open(input_fname, 'rt') except IOError: print 'Could not open file %s' % input_fname sys.exit() xml_string = fh.read() tp = TripsProcessor(xml_string) tp.get_complexes() tp.get_phosphorylation()
... from processor import TripsProcessor def process_text(text, save_xml_name='trips_output.xml'): html = trips_client.send_query(text) xml = trips_client.get_xml(html) if save_xml_name: trips_client.save_xml(xml, save_xml_name) return process_xml(xml) ...
1c8674029a1f1fa4a8f9545f540402ba418bd693
docs/generate_documentation.py
docs/generate_documentation.py
import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.join(os.path.dirname(__file__)) p1 = Popen(u'sphinx-build -M html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, u'_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0] if not result or u'build succeeded' not in result: raise RuntimeError(u'sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, u'documentation') shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, u'_build', u'html') , final_folder_path)
import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.abspath(os.path.dirname(__file__)) p1 = Popen('python -m sphinx -v -b html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, '_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0].decode('utf-8') if not result or 'build succeeded' not in result: raise RuntimeError('sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, 'documentation') if os.path.isdir(final_folder_path): shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, '_build') , final_folder_path)
Fix documentation generating script to work with Python 3
Fix documentation generating script to work with Python 3
Python
agpl-3.0
nabla-c0d3/sslyze
python
## Code Before: import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.join(os.path.dirname(__file__)) p1 = Popen(u'sphinx-build -M html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, u'_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0] if not result or u'build succeeded' not in result: raise RuntimeError(u'sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, u'documentation') shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, u'_build', u'html') , final_folder_path) ## Instruction: Fix documentation generating script to work with Python 3 ## Code After: import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.abspath(os.path.dirname(__file__)) p1 = Popen('python -m sphinx -v -b html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, '_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0].decode('utf-8') if not result or 'build succeeded' not in result: raise RuntimeError('sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, 'documentation') if os.path.isdir(final_folder_path): shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, '_build') , final_folder_path)
// ... existing code ... from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.abspath(os.path.dirname(__file__)) p1 = Popen('python -m sphinx -v -b html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, '_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0].decode('utf-8') if not result or 'build succeeded' not in result: raise RuntimeError('sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, 'documentation') if os.path.isdir(final_folder_path): shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, '_build') , final_folder_path) // ... rest of the code ...
e466da4f26d8cbac45476e8c00e009e004cd4baa
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
# Expose the tag library in the site. # If `django.contrib.comments` is not used, this library can provide stubs instead. # Currently, the real tags are exposed as the template already checks for `object.comments_are_open`. # When a custom template is used, authors likely choose the desired commenting library instead. from django.contrib.comments.templatetags.comments import register
from django.template import Library from fluent_utils.django_compat import is_installed # Expose the tag library in the site. # If `django.contrib.comments` is not used, this library can provide stubs instead. # Currently, the real tags are exposed as the template already checks for `object.comments_are_open`. # When a custom template is used, authors likely choose the desired commenting library instead. if is_installed('django.contrib.comments'): from django.contrib.comments.templatetags.comments import register elif is_installed('django_comments'): from django_comments.templatetags.comments import register else: register = Library()
Support django-contrib-comments instead of django.contrib.comments for Django 1.8
Support django-contrib-comments instead of django.contrib.comments for Django 1.8
Python
apache-2.0
edoburu/django-fluent-blogs,edoburu/django-fluent-blogs
python
## Code Before: # Expose the tag library in the site. # If `django.contrib.comments` is not used, this library can provide stubs instead. # Currently, the real tags are exposed as the template already checks for `object.comments_are_open`. # When a custom template is used, authors likely choose the desired commenting library instead. from django.contrib.comments.templatetags.comments import register ## Instruction: Support django-contrib-comments instead of django.contrib.comments for Django 1.8 ## Code After: from django.template import Library from fluent_utils.django_compat import is_installed # Expose the tag library in the site. # If `django.contrib.comments` is not used, this library can provide stubs instead. # Currently, the real tags are exposed as the template already checks for `object.comments_are_open`. # When a custom template is used, authors likely choose the desired commenting library instead. if is_installed('django.contrib.comments'): from django.contrib.comments.templatetags.comments import register elif is_installed('django_comments'): from django_comments.templatetags.comments import register else: register = Library()
// ... existing code ... from django.template import Library from fluent_utils.django_compat import is_installed # Expose the tag library in the site. # If `django.contrib.comments` is not used, this library can provide stubs instead. // ... modified code ... # Currently, the real tags are exposed as the template already checks for `object.comments_are_open`. # When a custom template is used, authors likely choose the desired commenting library instead. if is_installed('django.contrib.comments'): from django.contrib.comments.templatetags.comments import register elif is_installed('django_comments'): from django_comments.templatetags.comments import register else: register = Library() // ... rest of the code ...
eb25c6900b307792821f7db6bcfa92cc62a80298
lims/pricebook/views.py
lims/pricebook/views.py
from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from lims.permissions.permissions import IsInAdminGroupOrRO from lims.shared.mixins import AuditTrailViewMixin from .models import PriceBook from .serializers import PriceBookSerializer from lims.pricebook.management.commands.getpricebooks import get_pricebooks class PriceBookViewSet(AuditTrailViewMixin, viewsets.ModelViewSet): queryset = PriceBook.objects.all() serializer_class = PriceBookSerializer permission_classes = (IsInAdminGroupOrRO,) filter_fields = ('name', 'identifier',) @list_route() def updateall(self, request): get_pricebooks() return Response({'message': 'Pricebooks updated'})
from django.conf import settings from simple_salesforce import Salesforce from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from lims.permissions.permissions import IsInAdminGroupOrRO from lims.shared.mixins import AuditTrailViewMixin from .models import PriceBook from .serializers import PriceBookSerializer from lims.pricebook.management.commands.getpricebooks import get_pricebooks class PriceBookViewSet(AuditTrailViewMixin, viewsets.ModelViewSet): queryset = PriceBook.objects.all() serializer_class = PriceBookSerializer permission_classes = (IsInAdminGroupOrRO,) filter_fields = ('name', 'identifier',) def perform_create(self, serializer): serializer.save() get_pricebooks() @list_route(methods=['POST']) def updateall(self, request): get_pricebooks() return Response({'message': 'Pricebooks updated'}) @list_route() def on_crm(self, request): """ List of all pricebooks available on thr CRM """ sf = Salesforce(instance_url=settings.SALESFORCE_URL, username=settings.SALESFORCE_USERNAME, password=settings.SALESFORCE_PASSWORD, security_token=settings.SALESFORCE_TOKEN) pricebooks = sf.query("SELECT id,name FROM Pricebook2") return Response(pricebooks['records'])
Add list crm pricebooks endpoint and update pricebook fetching
Add list crm pricebooks endpoint and update pricebook fetching
Python
mit
GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend
python
## Code Before: from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from lims.permissions.permissions import IsInAdminGroupOrRO from lims.shared.mixins import AuditTrailViewMixin from .models import PriceBook from .serializers import PriceBookSerializer from lims.pricebook.management.commands.getpricebooks import get_pricebooks class PriceBookViewSet(AuditTrailViewMixin, viewsets.ModelViewSet): queryset = PriceBook.objects.all() serializer_class = PriceBookSerializer permission_classes = (IsInAdminGroupOrRO,) filter_fields = ('name', 'identifier',) @list_route() def updateall(self, request): get_pricebooks() return Response({'message': 'Pricebooks updated'}) ## Instruction: Add list crm pricebooks endpoint and update pricebook fetching ## Code After: from django.conf import settings from simple_salesforce import Salesforce from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from lims.permissions.permissions import IsInAdminGroupOrRO from lims.shared.mixins import AuditTrailViewMixin from .models import PriceBook from .serializers import PriceBookSerializer from lims.pricebook.management.commands.getpricebooks import get_pricebooks class PriceBookViewSet(AuditTrailViewMixin, viewsets.ModelViewSet): queryset = PriceBook.objects.all() serializer_class = PriceBookSerializer permission_classes = (IsInAdminGroupOrRO,) filter_fields = ('name', 'identifier',) def perform_create(self, serializer): serializer.save() get_pricebooks() @list_route(methods=['POST']) def updateall(self, request): get_pricebooks() return Response({'message': 'Pricebooks updated'}) @list_route() def on_crm(self, request): """ List of all pricebooks available on thr CRM """ sf = Salesforce(instance_url=settings.SALESFORCE_URL, username=settings.SALESFORCE_USERNAME, password=settings.SALESFORCE_PASSWORD, security_token=settings.SALESFORCE_TOKEN) pricebooks = sf.query("SELECT id,name FROM Pricebook2") return Response(pricebooks['records'])
... from django.conf import settings from simple_salesforce import Salesforce from rest_framework import viewsets from rest_framework.decorators import list_route ... permission_classes = (IsInAdminGroupOrRO,) filter_fields = ('name', 'identifier',) def perform_create(self, serializer): serializer.save() get_pricebooks() @list_route(methods=['POST']) def updateall(self, request): get_pricebooks() return Response({'message': 'Pricebooks updated'}) @list_route() def on_crm(self, request): """ List of all pricebooks available on thr CRM """ sf = Salesforce(instance_url=settings.SALESFORCE_URL, username=settings.SALESFORCE_USERNAME, password=settings.SALESFORCE_PASSWORD, security_token=settings.SALESFORCE_TOKEN) pricebooks = sf.query("SELECT id,name FROM Pricebook2") return Response(pricebooks['records']) ...
1fc2e747f1c02d5b8559f03187464eecda008190
fernet_fields/test/testmigrate/migrations/0004_copy_values.py
fernet_fields/test/testmigrate/migrations/0004_copy_values.py
from __future__ import unicode_literals from django.db import migrations def forwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value_dual = obj.value def backwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value = obj.value_dual class Migration(migrations.Migration): dependencies = [ ('testmigrate', '0003_add_value_dual'), ] operations = [ migrations.RunPython(forwards, backwards), ]
from __future__ import unicode_literals from django.db import migrations def forwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value_dual = obj.value obj.save(force_update=True) def backwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value = obj.value_dual obj.save(force_update=True) class Migration(migrations.Migration): dependencies = [ ('testmigrate', '0003_add_value_dual'), ] operations = [ migrations.RunPython(forwards, backwards), ]
Fix test migration to actually save updates.
Fix test migration to actually save updates.
Python
bsd-3-clause
orcasgit/django-fernet-fields
python
## Code Before: from __future__ import unicode_literals from django.db import migrations def forwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value_dual = obj.value def backwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value = obj.value_dual class Migration(migrations.Migration): dependencies = [ ('testmigrate', '0003_add_value_dual'), ] operations = [ migrations.RunPython(forwards, backwards), ] ## Instruction: Fix test migration to actually save updates. ## Code After: from __future__ import unicode_literals from django.db import migrations def forwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value_dual = obj.value obj.save(force_update=True) def backwards(apps, schema_editor): DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value = obj.value_dual obj.save(force_update=True) class Migration(migrations.Migration): dependencies = [ ('testmigrate', '0003_add_value_dual'), ] operations = [ migrations.RunPython(forwards, backwards), ]
# ... existing code ... DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value_dual = obj.value obj.save(force_update=True) def backwards(apps, schema_editor): # ... modified code ... DualText = apps.get_model('testmigrate', 'DualText') for obj in DualText.objects.all(): obj.value = obj.value_dual obj.save(force_update=True) class Migration(migrations.Migration): # ... rest of the code ...
70917a464535e3a559f6256c721c8ab7626b67e3
vm/include/capi/ruby/defines.h
vm/include/capi/ruby/defines.h
/* Stub file provided for C extensions that expect it. All regular * defines and prototypes are in ruby.h */ #define RUBY 1 #define RUBINIUS 1 #define HAVE_STDARG_PROTOTYPES 1 /* These are defines directly related to MRI C-API symbols that the * mkmf.rb discovery code (e.g. have_func("rb_str_set_len")) would * attempt to find by linking against libruby. Rubinius does not * have an appropriate lib to link against, so we are adding these * explicit defines for now. */ #define HAVE_RB_STR_SET_LEN 1 #define HAVE_RB_STR_NEW5 1 #define HAVE_RB_STR_NEW_WITH_CLASS 1 #define HAVE_RB_DEFINE_ALLOC_FUNC 1 #define HAVE_RB_HASH_FOREACH 1 #define HAVE_RB_HASH_ASET 1 #define HAVE_RUBY_ENCODING_H 1 #define HAVE_RB_ENCDB_ALIAS 1 #endif
/* Stub file provided for C extensions that expect it. All regular * defines and prototypes are in ruby.h */ #define RUBY 1 #define RUBINIUS 1 #define HAVE_STDARG_PROTOTYPES 1 /* These are defines directly related to MRI C-API symbols that the * mkmf.rb discovery code (e.g. have_func("rb_str_set_len")) would * attempt to find by linking against libruby. Rubinius does not * have an appropriate lib to link against, so we are adding these * explicit defines for now. */ #define HAVE_RB_STR_SET_LEN 1 #define HAVE_RB_STR_NEW5 1 #define HAVE_RB_STR_NEW_WITH_CLASS 1 #define HAVE_RB_DEFINE_ALLOC_FUNC 1 #define HAVE_RB_HASH_FOREACH 1 #define HAVE_RB_HASH_ASET 1 #define HAVE_RUBY_ENCODING_H 1 #define HAVE_RB_ENCDB_ALIAS 1 #define HAVE_RB_ARY_SUBSEQ 1 #endif
Add explicit define for rb_ary_subseq
Add explicit define for rb_ary_subseq
C
mpl-2.0
mlarraz/rubinius,jemc/rubinius,kachick/rubinius,heftig/rubinius,kachick/rubinius,Azizou/rubinius,jsyeo/rubinius,digitalextremist/rubinius,heftig/rubinius,kachick/rubinius,digitalextremist/rubinius,jemc/rubinius,dblock/rubinius,benlovell/rubinius,ngpestelos/rubinius,ruipserra/rubinius,jemc/rubinius,jsyeo/rubinius,sferik/rubinius,Wirachmat/rubinius,Wirachmat/rubinius,jsyeo/rubinius,dblock/rubinius,Azizou/rubinius,jsyeo/rubinius,kachick/rubinius,benlovell/rubinius,digitalextremist/rubinius,mlarraz/rubinius,sferik/rubinius,ngpestelos/rubinius,mlarraz/rubinius,jsyeo/rubinius,ngpestelos/rubinius,dblock/rubinius,benlovell/rubinius,benlovell/rubinius,digitalextremist/rubinius,kachick/rubinius,ngpestelos/rubinius,ruipserra/rubinius,Wirachmat/rubinius,jemc/rubinius,sferik/rubinius,ngpestelos/rubinius,Wirachmat/rubinius,Azizou/rubinius,kachick/rubinius,heftig/rubinius,ngpestelos/rubinius,ruipserra/rubinius,mlarraz/rubinius,jemc/rubinius,benlovell/rubinius,Wirachmat/rubinius,dblock/rubinius,mlarraz/rubinius,digitalextremist/rubinius,benlovell/rubinius,kachick/rubinius,mlarraz/rubinius,jsyeo/rubinius,Azizou/rubinius,benlovell/rubinius,ruipserra/rubinius,mlarraz/rubinius,dblock/rubinius,ruipserra/rubinius,heftig/rubinius,ngpestelos/rubinius,digitalextremist/rubinius,pH14/rubinius,sferik/rubinius,heftig/rubinius,Azizou/rubinius,sferik/rubinius,jsyeo/rubinius,jemc/rubinius,pH14/rubinius,Wirachmat/rubinius,ruipserra/rubinius,digitalextremist/rubinius,dblock/rubinius,sferik/rubinius,heftig/rubinius,Wirachmat/rubinius,pH14/rubinius,ruipserra/rubinius,jemc/rubinius,pH14/rubinius,kachick/rubinius,heftig/rubinius,dblock/rubinius,pH14/rubinius,pH14/rubinius,Azizou/rubinius,Azizou/rubinius,pH14/rubinius,sferik/rubinius
c
## Code Before: /* Stub file provided for C extensions that expect it. All regular * defines and prototypes are in ruby.h */ #define RUBY 1 #define RUBINIUS 1 #define HAVE_STDARG_PROTOTYPES 1 /* These are defines directly related to MRI C-API symbols that the * mkmf.rb discovery code (e.g. have_func("rb_str_set_len")) would * attempt to find by linking against libruby. Rubinius does not * have an appropriate lib to link against, so we are adding these * explicit defines for now. */ #define HAVE_RB_STR_SET_LEN 1 #define HAVE_RB_STR_NEW5 1 #define HAVE_RB_STR_NEW_WITH_CLASS 1 #define HAVE_RB_DEFINE_ALLOC_FUNC 1 #define HAVE_RB_HASH_FOREACH 1 #define HAVE_RB_HASH_ASET 1 #define HAVE_RUBY_ENCODING_H 1 #define HAVE_RB_ENCDB_ALIAS 1 #endif ## Instruction: Add explicit define for rb_ary_subseq ## Code After: /* Stub file provided for C extensions that expect it. All regular * defines and prototypes are in ruby.h */ #define RUBY 1 #define RUBINIUS 1 #define HAVE_STDARG_PROTOTYPES 1 /* These are defines directly related to MRI C-API symbols that the * mkmf.rb discovery code (e.g. have_func("rb_str_set_len")) would * attempt to find by linking against libruby. Rubinius does not * have an appropriate lib to link against, so we are adding these * explicit defines for now. */ #define HAVE_RB_STR_SET_LEN 1 #define HAVE_RB_STR_NEW5 1 #define HAVE_RB_STR_NEW_WITH_CLASS 1 #define HAVE_RB_DEFINE_ALLOC_FUNC 1 #define HAVE_RB_HASH_FOREACH 1 #define HAVE_RB_HASH_ASET 1 #define HAVE_RUBY_ENCODING_H 1 #define HAVE_RB_ENCDB_ALIAS 1 #define HAVE_RB_ARY_SUBSEQ 1 #endif
# ... existing code ... #define HAVE_RB_ENCDB_ALIAS 1 #define HAVE_RB_ARY_SUBSEQ 1 #endif # ... rest of the code ...
c3b6286361b5e996235f9db4d9a40bcfc83248cc
src/main/java/org/zalando/nakadi/plugin/auth/DefaultAuthorizationService.java
src/main/java/org/zalando/nakadi/plugin/auth/DefaultAuthorizationService.java
package org.zalando.nakadi.plugin.auth; import org.springframework.security.core.context.SecurityContextHolder; import org.zalando.nakadi.plugin.api.PluginException; import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute; import org.zalando.nakadi.plugin.api.authz.AuthorizationService; import org.zalando.nakadi.plugin.api.authz.Resource; import org.zalando.nakadi.plugin.api.authz.Subject; import java.util.List; public class DefaultAuthorizationService implements AuthorizationService { @Override public boolean isAuthorized(final Operation operation, final Resource resource) { return true; } @Override public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) { return true; } @Override public Subject getSubject() { return () -> SecurityContextHolder.getContext().getAuthentication().getName(); } @Override public List<Resource> filter(final List<Resource> input) throws PluginException { return input; } }
package org.zalando.nakadi.plugin.auth; import org.springframework.security.core.context.SecurityContextHolder; import org.zalando.nakadi.plugin.api.PluginException; import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute; import org.zalando.nakadi.plugin.api.authz.AuthorizationService; import org.zalando.nakadi.plugin.api.authz.Resource; import org.zalando.nakadi.plugin.api.authz.Subject; import java.security.Principal; import java.util.List; import java.util.Optional; public class DefaultAuthorizationService implements AuthorizationService { @Override public boolean isAuthorized(final Operation operation, final Resource resource) { return true; } @Override public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) { return true; } @Override public Subject getSubject() { return () -> Optional.ofNullable( SecurityContextHolder.getContext().getAuthentication()).map(Principal::getName).orElse(null); } @Override public List<Resource> filter(final List<Resource> input) throws PluginException { return input; } }
Fix NullPointerException resulting in MalformedChunk in AcceptanceTests
Fix NullPointerException resulting in MalformedChunk in AcceptanceTests
Java
mit
zalando/nakadi,zalando/nakadi
java
## Code Before: package org.zalando.nakadi.plugin.auth; import org.springframework.security.core.context.SecurityContextHolder; import org.zalando.nakadi.plugin.api.PluginException; import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute; import org.zalando.nakadi.plugin.api.authz.AuthorizationService; import org.zalando.nakadi.plugin.api.authz.Resource; import org.zalando.nakadi.plugin.api.authz.Subject; import java.util.List; public class DefaultAuthorizationService implements AuthorizationService { @Override public boolean isAuthorized(final Operation operation, final Resource resource) { return true; } @Override public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) { return true; } @Override public Subject getSubject() { return () -> SecurityContextHolder.getContext().getAuthentication().getName(); } @Override public List<Resource> filter(final List<Resource> input) throws PluginException { return input; } } ## Instruction: Fix NullPointerException resulting in MalformedChunk in AcceptanceTests ## Code After: package org.zalando.nakadi.plugin.auth; import org.springframework.security.core.context.SecurityContextHolder; import org.zalando.nakadi.plugin.api.PluginException; import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute; import org.zalando.nakadi.plugin.api.authz.AuthorizationService; import org.zalando.nakadi.plugin.api.authz.Resource; import org.zalando.nakadi.plugin.api.authz.Subject; import java.security.Principal; import java.util.List; import java.util.Optional; public class DefaultAuthorizationService implements AuthorizationService { @Override public boolean isAuthorized(final Operation operation, final Resource resource) { return true; } @Override public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) { return true; } @Override public Subject getSubject() { return () -> Optional.ofNullable( SecurityContextHolder.getContext().getAuthentication()).map(Principal::getName).orElse(null); } @Override public List<Resource> filter(final List<Resource> input) throws PluginException { return input; } }
// ... existing code ... import org.zalando.nakadi.plugin.api.authz.Resource; import org.zalando.nakadi.plugin.api.authz.Subject; import java.security.Principal; import java.util.List; import java.util.Optional; public class DefaultAuthorizationService implements AuthorizationService { // ... modified code ... @Override public Subject getSubject() { return () -> Optional.ofNullable( SecurityContextHolder.getContext().getAuthentication()).map(Principal::getName).orElse(null); } @Override // ... rest of the code ...
ce3249dea725d40d5e0916b344cdde53ab6d53dc
src/satosa/micro_services/processors/scope_extractor_processor.py
src/satosa/micro_services/processors/scope_extractor_processor.py
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
Make the ScopeExtractorProcessor usable for the Primary Identifier
Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348
Python
apache-2.0
SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA
python
## Code Before: from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break ## Instruction: Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348 ## Code After: from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
# ... existing code ... values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: # ... rest of the code ...
a56195292bc9d68da9b496b253411df2cac40500
021.calling_c/c_code.c
021.calling_c/c_code.c
void PokeBitplanePointers(unsigned short* copper, unsigned char* bitplanes, unsigned offset, unsigned numBitplanes, unsigned screenWidthBytes) { int i; copper += offset; for (i = 0; i < numBitplanes; i++) { *(copper+1) = (unsigned)bitplanes; *(copper+3) = ((unsigned)bitplanes >> 16); bitplanes += screenWidthBytes; copper += 4; } } static unsigned short _copperData; static unsigned char _bitplaneData; void TestCall() { PokeBitplanePointers(&_copperData, &_bitplaneData, 3, 4, 5); }
typedef union { unsigned char* ptr; unsigned short word[2]; } word_extract_t; void PokeBitplanePointers(unsigned short* copper, unsigned char* bitplanes, unsigned offset, unsigned numBitplanes, unsigned screenWidthBytes) { int i; copper += offset; for (i = 0; i < numBitplanes; i++) { word_extract_t extract; extract.ptr = bitplanes; *(copper+1) = extract.word[1]; *(copper+3) = extract.word[0]; bitplanes += screenWidthBytes; copper += 4; } } static unsigned short _copperData; static unsigned char _bitplaneData; void TestCall() { PokeBitplanePointers(&_copperData, &_bitplaneData, 3, 4, 5); }
Make C example more C, less asm
Make C example more C, less asm
C
bsd-2-clause
alpine9000/amiga_examples,alpine9000/amiga_examples,alpine9000/amiga_examples
c
## Code Before: void PokeBitplanePointers(unsigned short* copper, unsigned char* bitplanes, unsigned offset, unsigned numBitplanes, unsigned screenWidthBytes) { int i; copper += offset; for (i = 0; i < numBitplanes; i++) { *(copper+1) = (unsigned)bitplanes; *(copper+3) = ((unsigned)bitplanes >> 16); bitplanes += screenWidthBytes; copper += 4; } } static unsigned short _copperData; static unsigned char _bitplaneData; void TestCall() { PokeBitplanePointers(&_copperData, &_bitplaneData, 3, 4, 5); } ## Instruction: Make C example more C, less asm ## Code After: typedef union { unsigned char* ptr; unsigned short word[2]; } word_extract_t; void PokeBitplanePointers(unsigned short* copper, unsigned char* bitplanes, unsigned offset, unsigned numBitplanes, unsigned screenWidthBytes) { int i; copper += offset; for (i = 0; i < numBitplanes; i++) { word_extract_t extract; extract.ptr = bitplanes; *(copper+1) = extract.word[1]; *(copper+3) = extract.word[0]; bitplanes += screenWidthBytes; copper += 4; } } static unsigned short _copperData; static unsigned char _bitplaneData; void TestCall() { PokeBitplanePointers(&_copperData, &_bitplaneData, 3, 4, 5); }
... typedef union { unsigned char* ptr; unsigned short word[2]; } word_extract_t; void PokeBitplanePointers(unsigned short* copper, unsigned char* bitplanes, unsigned offset, unsigned numBitplanes, unsigned screenWidthBytes) { ... copper += offset; for (i = 0; i < numBitplanes; i++) { word_extract_t extract; extract.ptr = bitplanes; *(copper+1) = extract.word[1]; *(copper+3) = extract.word[0]; bitplanes += screenWidthBytes; copper += 4; } ...
73660f4f539a1aeb520c33112cfc41183e4dd43a
luigi/tasks/rfam/clans_csv.py
luigi/tasks/rfam/clans_csv.py
import operator as op import luigi from databases.rfam.clans import parse from tasks.config import rfam from tasks.utils.fetch import FetchTask from tasks.utils.writers import CsvOutput class RfamClansCSV(luigi.Task): def requires(self): conf = rfam() return FetchTask( remote_path=conf.query('clans.sql'), local_path=conf.raw('clans.tsv'), ) def output(self): conf = rfam() return CsvOutput( conf.clans, ['id', 'name', 'description', 'family_count'], op.methodcaller('writeable'), ) def run(self): with self.requires().output.open('r') as raw: self.output().populate(parse(raw))
import operator as op import luigi from databases.rfam import clans from tasks.config import rfam from tasks.utils.writers import CsvOutput from tasks.utils.mysql import MysqlQueryTask class RfamClansCSV(luigi.Task): def requires(self): conf = rfam() return MysqlQueryTask( db=conf, query=clans.QUERY, local_path=conf.raw('clans.tsv'), ) def output(self): conf = rfam() return CsvOutput( conf.clans, ['id', 'name', 'description', 'family_count'], op.methodcaller('writeable'), ) def run(self): with self.requires().output.open('r') as raw: self.output().populate(clans.parse(raw))
Use MysqlQueryTask for getting clan data
Use MysqlQueryTask for getting clan data
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
python
## Code Before: import operator as op import luigi from databases.rfam.clans import parse from tasks.config import rfam from tasks.utils.fetch import FetchTask from tasks.utils.writers import CsvOutput class RfamClansCSV(luigi.Task): def requires(self): conf = rfam() return FetchTask( remote_path=conf.query('clans.sql'), local_path=conf.raw('clans.tsv'), ) def output(self): conf = rfam() return CsvOutput( conf.clans, ['id', 'name', 'description', 'family_count'], op.methodcaller('writeable'), ) def run(self): with self.requires().output.open('r') as raw: self.output().populate(parse(raw)) ## Instruction: Use MysqlQueryTask for getting clan data ## Code After: import operator as op import luigi from databases.rfam import clans from tasks.config import rfam from tasks.utils.writers import CsvOutput from tasks.utils.mysql import MysqlQueryTask class RfamClansCSV(luigi.Task): def requires(self): conf = rfam() return MysqlQueryTask( db=conf, query=clans.QUERY, local_path=conf.raw('clans.tsv'), ) def output(self): conf = rfam() return CsvOutput( conf.clans, ['id', 'name', 'description', 'family_count'], op.methodcaller('writeable'), ) def run(self): with self.requires().output.open('r') as raw: self.output().populate(clans.parse(raw))
... import luigi from databases.rfam import clans from tasks.config import rfam from tasks.utils.writers import CsvOutput from tasks.utils.mysql import MysqlQueryTask class RfamClansCSV(luigi.Task): ... def requires(self): conf = rfam() return MysqlQueryTask( db=conf, query=clans.QUERY, local_path=conf.raw('clans.tsv'), ) ... def run(self): with self.requires().output.open('r') as raw: self.output().populate(clans.parse(raw)) ...
3edb24604034e1cc4407a46713822512cc28ff47
app/src/main/java/com/red/alert/ui/notifications/AppNotifications.java
app/src/main/java/com/red/alert/ui/notifications/AppNotifications.java
package com.red.alert.ui.notifications; import android.app.NotificationManager; import android.content.Context; import com.red.alert.R; import com.red.alert.services.sound.StopSoundService; public class AppNotifications { public static void clearAll(Context context) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Cancel all notifications notificationManager.cancel(context.getString(R.string.appName).hashCode()); // Stop alert playing StopSoundService.stopSoundService(context); } }
package com.red.alert.ui.notifications; import android.app.NotificationManager; import android.content.Context; import com.red.alert.R; import com.red.alert.services.sound.StopSoundService; public class AppNotifications { public static void clearAll(Context context) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Cancel all notifications notificationManager.cancelAll(); // Stop alert sound if playing StopSoundService.stopSoundService(context); } }
Use NotificationManager.cancelAll() to cancel all app notifications
Use NotificationManager.cancelAll() to cancel all app notifications
Java
apache-2.0
eladnava/redalert-android
java
## Code Before: package com.red.alert.ui.notifications; import android.app.NotificationManager; import android.content.Context; import com.red.alert.R; import com.red.alert.services.sound.StopSoundService; public class AppNotifications { public static void clearAll(Context context) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Cancel all notifications notificationManager.cancel(context.getString(R.string.appName).hashCode()); // Stop alert playing StopSoundService.stopSoundService(context); } } ## Instruction: Use NotificationManager.cancelAll() to cancel all app notifications ## Code After: package com.red.alert.ui.notifications; import android.app.NotificationManager; import android.content.Context; import com.red.alert.R; import com.red.alert.services.sound.StopSoundService; public class AppNotifications { public static void clearAll(Context context) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Cancel all notifications notificationManager.cancelAll(); // Stop alert sound if playing StopSoundService.stopSoundService(context); } }
... NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Cancel all notifications notificationManager.cancelAll(); // Stop alert sound if playing StopSoundService.stopSoundService(context); } } ...
a35a25732159e4c8b5655755ce31ec4c3e6e7975
dummy_robot/dummy_robot_bringup/launch/dummy_robot_bringup.launch.py
dummy_robot/dummy_robot_bringup/launch/dummy_robot_bringup.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
Switch dummy_robot_bringup to use parameter for rsp.
Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <[email protected]>
Python
apache-2.0
ros2/demos,ros2/demos,ros2/demos,ros2/demos
python
## Code Before: import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) ## Instruction: Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <[email protected]> ## Code After: import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
# ... existing code ... import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) # ... rest of the code ...
b4e22f60962a51b36155ffd15260c5be1cf4c931
library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
package org.firezenk.kartographer.library.core import org.junit.Assert.* /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. * Project: Kartographer */ class CoreTest { }
package org.firezenk.kartographer.library.core import org.firezenk.kartographer.library.Logger import org.firezenk.kartographer.library.core.util.TargetRoute import org.firezenk.kartographer.library.dsl.route import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. * Project: Kartographer */ class CoreTest { lateinit var core: Core lateinit var move: Move @Before fun setup() { core = Core(Any(), Logger()) move = Move(core) } @Test fun `given a history with one route on default path, the current route is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE anchor = Any() } move.routeTo(route) val currentRoute = core.current<Any>() assertEquals(route, currentRoute) } @Test fun `given a history with one route on default path, the current route payload is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE params = mapOf("param1" to 1, "param2" to "hi!") anchor = Any() } move.routeTo(route) val currentParam1 = core.payload<Int>("param1") val currentParam2 = core.payload<String>("param2") assertEquals(currentParam1, 1) assertEquals(currentParam2, "hi!") } }
Add a basic Core test
Add a basic Core test
Kotlin
mit
FireZenk/Kartographer
kotlin
## Code Before: package org.firezenk.kartographer.library.core import org.junit.Assert.* /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. * Project: Kartographer */ class CoreTest { } ## Instruction: Add a basic Core test ## Code After: package org.firezenk.kartographer.library.core import org.firezenk.kartographer.library.Logger import org.firezenk.kartographer.library.core.util.TargetRoute import org.firezenk.kartographer.library.dsl.route import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. * Project: Kartographer */ class CoreTest { lateinit var core: Core lateinit var move: Move @Before fun setup() { core = Core(Any(), Logger()) move = Move(core) } @Test fun `given a history with one route on default path, the current route is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE anchor = Any() } move.routeTo(route) val currentRoute = core.current<Any>() assertEquals(route, currentRoute) } @Test fun `given a history with one route on default path, the current route payload is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE params = mapOf("param1" to 1, "param2" to "hi!") anchor = Any() } move.routeTo(route) val currentParam1 = core.payload<Int>("param1") val currentParam2 = core.payload<String>("param2") assertEquals(currentParam1, 1) assertEquals(currentParam2, "hi!") } }
... package org.firezenk.kartographer.library.core import org.firezenk.kartographer.library.Logger import org.firezenk.kartographer.library.core.util.TargetRoute import org.firezenk.kartographer.library.dsl.route import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. ... */ class CoreTest { lateinit var core: Core lateinit var move: Move @Before fun setup() { core = Core(Any(), Logger()) move = Move(core) } @Test fun `given a history with one route on default path, the current route is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE anchor = Any() } move.routeTo(route) val currentRoute = core.current<Any>() assertEquals(route, currentRoute) } @Test fun `given a history with one route on default path, the current route payload is correct`() { val route = route { target = TargetRoute::class path = Core.ROOT_NODE params = mapOf("param1" to 1, "param2" to "hi!") anchor = Any() } move.routeTo(route) val currentParam1 = core.payload<Int>("param1") val currentParam2 = core.payload<String>("param2") assertEquals(currentParam1, 1) assertEquals(currentParam2, "hi!") } } ...
39a2a54708c58bf4edc083a7764bc777da594853
src/com/temporaryteam/treenote/Main.java
src/com/temporaryteam/treenote/Main.java
package com.temporaryteam.treenote; import javafx.application.Application; import javafx.stage.Stage; import java.util.Locale; import java.util.ResourceBundle; public class Main extends Application { @Override public void start(Stage primaryStage) { primaryStage.setTitle("TreeNote"); ResourceBundle res = ResourceBundle.getBundle("resources.translate.Language", Locale.getDefault()); Context.init(res, primaryStage); Context.loadToStage("Main").show(); } public static void main(String[] args) { launch(args); } }
package com.temporaryteam.treenote; import javafx.application.Application; import javafx.stage.Stage; import java.util.Locale; import java.util.ResourceBundle; public class Main extends Application { @Override public void start(Stage primaryStage) { System.setProperty("prism.lcdtext", "false"); primaryStage.setTitle("TreeNote"); ResourceBundle res = ResourceBundle.getBundle("resources.translate.Language", Locale.getDefault()); Context.init(res, primaryStage); Context.loadToStage("Main").show(); } public static void main(String[] args) { launch(args); } }
Fix font smoothing in WebView (on linux)
Fix font smoothing in WebView (on linux)
Java
apache-2.0
NaikSoftware/TreeNote,NaikSoftware/TreeNote
java
## Code Before: package com.temporaryteam.treenote; import javafx.application.Application; import javafx.stage.Stage; import java.util.Locale; import java.util.ResourceBundle; public class Main extends Application { @Override public void start(Stage primaryStage) { primaryStage.setTitle("TreeNote"); ResourceBundle res = ResourceBundle.getBundle("resources.translate.Language", Locale.getDefault()); Context.init(res, primaryStage); Context.loadToStage("Main").show(); } public static void main(String[] args) { launch(args); } } ## Instruction: Fix font smoothing in WebView (on linux) ## Code After: package com.temporaryteam.treenote; import javafx.application.Application; import javafx.stage.Stage; import java.util.Locale; import java.util.ResourceBundle; public class Main extends Application { @Override public void start(Stage primaryStage) { System.setProperty("prism.lcdtext", "false"); primaryStage.setTitle("TreeNote"); ResourceBundle res = ResourceBundle.getBundle("resources.translate.Language", Locale.getDefault()); Context.init(res, primaryStage); Context.loadToStage("Main").show(); } public static void main(String[] args) { launch(args); } }
... @Override public void start(Stage primaryStage) { System.setProperty("prism.lcdtext", "false"); primaryStage.setTitle("TreeNote"); ResourceBundle res = ResourceBundle.getBundle("resources.translate.Language", Locale.getDefault()); Context.init(res, primaryStage); ...
5be4dec175c9e672ec5e7e011be604ad39459565
apps/polls/admin.py
apps/polls/admin.py
from django.contrib import admin from apps.polls.models import Poll, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question'] admin.site.register(Poll, PollAdmin) admin.site.register(Choice)
from django.contrib import admin from apps.polls.models import Poll, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question'] date_hierarchy = 'pub_date' admin.site.register(Poll, PollAdmin) admin.site.register(Choice)
Add date_hierarchy = 'pub_date' to PollAdmin
Add date_hierarchy = 'pub_date' to PollAdmin
Python
bsd-3-clause
teracyhq/django-tutorial,datphan/teracy-tutorial
python
## Code Before: from django.contrib import admin from apps.polls.models import Poll, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question'] admin.site.register(Poll, PollAdmin) admin.site.register(Choice) ## Instruction: Add date_hierarchy = 'pub_date' to PollAdmin ## Code After: from django.contrib import admin from apps.polls.models import Poll, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question'] date_hierarchy = 'pub_date' admin.site.register(Poll, PollAdmin) admin.site.register(Choice)
... list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question'] date_hierarchy = 'pub_date' admin.site.register(Poll, PollAdmin) ...
6182fd214580e517ffe8a59ed89037adf7fd2094
traits/tests/test_dynamic_trait_definition.py
traits/tests/test_dynamic_trait_definition.py
from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float x_changes = List y_changes = List def _x_changed(self, new): self.x_changes.append(new) def _y_changed(self, new): self.y_changes.append(new) class TestDynamicTraitDefinition(unittest.TestCase): """ Test demonstrating special change events using the 'event' metadata. """ def test_add_trait(self): foo = Foo(x=3) foo.add_trait('y', Int) self.assertTrue(hasattr(foo, 'y')) self.assertEqual(type(foo.y), int) foo.y = 4 self.assertEqual(foo.y_changes, [4]) def test_remove_trait(self): foo = Foo(x=3) # We can't remove a "statically" added trait (i.e., a trait defined # in the Foo class). result = foo.remove_trait('x') self.assertFalse(result) # We can remove dynamically added traits. foo.add_trait('y', Int) foo.y = 70 result = foo.remove_trait('y') self.assertTrue(result) self.assertFalse(hasattr(foo, 'y')) foo.y = 10 self.assertEqual(foo.y_changes, [70])
from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float y_changes = List def _y_changed(self, new): self.y_changes.append(new) class TestDynamicTraitDefinition(unittest.TestCase): """ Test demonstrating special change events using the 'event' metadata. """ def test_add_trait(self): foo = Foo(x=3) foo.add_trait('y', Int) self.assertTrue(hasattr(foo, 'y')) self.assertEqual(type(foo.y), int) foo.y = 4 self.assertEqual(foo.y_changes, [4]) def test_remove_trait(self): foo = Foo(x=3) # We can't remove a "statically" added trait (i.e., a trait defined # in the Foo class). result = foo.remove_trait('x') self.assertFalse(result) # We can remove dynamically added traits. foo.add_trait('y', Int) foo.y = 70 result = foo.remove_trait('y') self.assertTrue(result) self.assertFalse(hasattr(foo, 'y')) foo.y = 10 self.assertEqual(foo.y_changes, [70])
Remove unused trait definitions in test.
Remove unused trait definitions in test.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
python
## Code Before: from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float x_changes = List y_changes = List def _x_changed(self, new): self.x_changes.append(new) def _y_changed(self, new): self.y_changes.append(new) class TestDynamicTraitDefinition(unittest.TestCase): """ Test demonstrating special change events using the 'event' metadata. """ def test_add_trait(self): foo = Foo(x=3) foo.add_trait('y', Int) self.assertTrue(hasattr(foo, 'y')) self.assertEqual(type(foo.y), int) foo.y = 4 self.assertEqual(foo.y_changes, [4]) def test_remove_trait(self): foo = Foo(x=3) # We can't remove a "statically" added trait (i.e., a trait defined # in the Foo class). result = foo.remove_trait('x') self.assertFalse(result) # We can remove dynamically added traits. foo.add_trait('y', Int) foo.y = 70 result = foo.remove_trait('y') self.assertTrue(result) self.assertFalse(hasattr(foo, 'y')) foo.y = 10 self.assertEqual(foo.y_changes, [70]) ## Instruction: Remove unused trait definitions in test. ## Code After: from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float y_changes = List def _y_changed(self, new): self.y_changes.append(new) class TestDynamicTraitDefinition(unittest.TestCase): """ Test demonstrating special change events using the 'event' metadata. """ def test_add_trait(self): foo = Foo(x=3) foo.add_trait('y', Int) self.assertTrue(hasattr(foo, 'y')) self.assertEqual(type(foo.y), int) foo.y = 4 self.assertEqual(foo.y_changes, [4]) def test_remove_trait(self): foo = Foo(x=3) # We can't remove a "statically" added trait (i.e., a trait defined # in the Foo class). result = foo.remove_trait('x') self.assertFalse(result) # We can remove dynamically added traits. foo.add_trait('y', Int) foo.y = 70 result = foo.remove_trait('y') self.assertTrue(result) self.assertFalse(hasattr(foo, 'y')) foo.y = 10 self.assertEqual(foo.y_changes, [70])
// ... existing code ... class Foo(HasTraits): x = Float y_changes = List def _y_changed(self, new): self.y_changes.append(new) // ... rest of the code ...
e4d5fa8c70dd283d4511f155da5be5835b1836f7
tests/unit/test_validate.py
tests/unit/test_validate.py
import pytest import mock import synapseclient from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat # def test_wrongfilename_get_filetype(): # assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None
import pytest import mock import synapseclient import pytest from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat def test_wrongfilename_get_filetype(): with pytest.raises( ValueError, match="Your filename is incorrect! " "Please change your filename before you run " "the validator or specify --filetype if you are " "running the validator locally"): validate.determine_filetype(syn, ['wrong.txt'], center)
Add in unit tests for validate.py
Add in unit tests for validate.py
Python
mit
thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie,thomasyu888/Genie
python
## Code Before: import pytest import mock import synapseclient from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat # def test_wrongfilename_get_filetype(): # assert input_to_database.get_filetype(syn, ['wrong.txt'], center) is None ## Instruction: Add in unit tests for validate.py ## Code After: import pytest import mock import synapseclient import pytest from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) @pytest.fixture(params=[ # tuple with (input, expectedOutput) (["data_CNA_SAGE.txt"], "cna"), (["data_clinical_supp_SAGE.txt"], "clinical"), (["data_clinical_supp_sample_SAGE.txt", "data_clinical_supp_patient_SAGE.txt"], "clinical")]) def filename_fileformat_map(request): return request.param def test_perfect_get_filetype(filename_fileformat_map): (filepath_list, fileformat) = filename_fileformat_map assert validate.determine_filetype( syn, filepath_list, center) == fileformat def test_wrongfilename_get_filetype(): with pytest.raises( ValueError, match="Your filename is incorrect! " "Please change your filename before you run " "the validator or specify --filetype if you are " "running the validator locally"): validate.determine_filetype(syn, ['wrong.txt'], center)
// ... existing code ... import pytest import mock import synapseclient import pytest from genie import validate center = "SAGE" syn = mock.create_autospec(synapseclient.Synapse) // ... modified code ... syn, filepath_list, center) == fileformat def test_wrongfilename_get_filetype(): with pytest.raises( ValueError, match="Your filename is incorrect! " "Please change your filename before you run " "the validator or specify --filetype if you are " "running the validator locally"): validate.determine_filetype(syn, ['wrong.txt'], center) // ... rest of the code ...
c9e11c04bd5981f810b47a659f0777d1976cb01f
vaux/storage/metadata.py
vaux/storage/metadata.py
import rethinkdb as r class MetaEngine(object): def __init__(self, hostname, port, db, table): self.rdb = r.connect(host=hostname, port=port, db=db, timeout=20) self.table = table def get_all(self): for item in r.table(self.table).run(self.rdb): yield item def put(self, data): r.table(self.table).insert(data).run(self.rdb) def delete(self, filter_data): r.table(self.table).filter(filter_data).delete().run(self.rdb) def get(self, filter_data): result = list(r.table(self.table).filter(filter_data).run(self.rdb)) if len(result) > 0: return result[0] return None def exists(self, filter_data): return len(list(r.table(self.table).filter(filter_data).run(self.rdb))) > 0 def search(self, ffunc): for item in r.table(self.table).filter(ffunc).run(self.rdb): yield item
import rethinkdb as r class MetaEngine(object): def __init__(self, hostname, port, db, table): self.rdb = r.connect(host=hostname, port=port, timeout=20) try: self.rdb.db_create(db).run() except Exception, e: pass self.rdb.close() self.rdb = r.connect(host=hostname, port=port, db=db, timeout=20) try: self.rdb.table_create(table).run() except Exception, e: pass self.table = table def get_all(self): for item in r.table(self.table).run(self.rdb): yield item def put(self, data): r.table(self.table).insert(data).run(self.rdb) def delete(self, filter_data): r.table(self.table).filter(filter_data).delete().run(self.rdb) def get(self, filter_data): result = list(r.table(self.table).filter(filter_data).run(self.rdb)) if len(result) > 0: return result[0] return None def exists(self, filter_data): return len(list(r.table(self.table).filter(filter_data).run(self.rdb))) > 0 def search(self, ffunc): for item in r.table(self.table).filter(ffunc).run(self.rdb): yield item
Create the database and table if they don't exist
Create the database and table if they don't exist I think... :/
Python
mit
VauxIo/core
python
## Code Before: import rethinkdb as r class MetaEngine(object): def __init__(self, hostname, port, db, table): self.rdb = r.connect(host=hostname, port=port, db=db, timeout=20) self.table = table def get_all(self): for item in r.table(self.table).run(self.rdb): yield item def put(self, data): r.table(self.table).insert(data).run(self.rdb) def delete(self, filter_data): r.table(self.table).filter(filter_data).delete().run(self.rdb) def get(self, filter_data): result = list(r.table(self.table).filter(filter_data).run(self.rdb)) if len(result) > 0: return result[0] return None def exists(self, filter_data): return len(list(r.table(self.table).filter(filter_data).run(self.rdb))) > 0 def search(self, ffunc): for item in r.table(self.table).filter(ffunc).run(self.rdb): yield item ## Instruction: Create the database and table if they don't exist I think... :/ ## Code After: import rethinkdb as r class MetaEngine(object): def __init__(self, hostname, port, db, table): self.rdb = r.connect(host=hostname, port=port, timeout=20) try: self.rdb.db_create(db).run() except Exception, e: pass self.rdb.close() self.rdb = r.connect(host=hostname, port=port, db=db, timeout=20) try: self.rdb.table_create(table).run() except Exception, e: pass self.table = table def get_all(self): for item in r.table(self.table).run(self.rdb): yield item def put(self, data): r.table(self.table).insert(data).run(self.rdb) def delete(self, filter_data): r.table(self.table).filter(filter_data).delete().run(self.rdb) def get(self, filter_data): result = list(r.table(self.table).filter(filter_data).run(self.rdb)) if len(result) > 0: return result[0] return None def exists(self, filter_data): return len(list(r.table(self.table).filter(filter_data).run(self.rdb))) > 0 def search(self, ffunc): for item in r.table(self.table).filter(ffunc).run(self.rdb): yield item
... class MetaEngine(object): def __init__(self, hostname, port, db, table): self.rdb = r.connect(host=hostname, port=port, timeout=20) try: self.rdb.db_create(db).run() except Exception, e: pass self.rdb.close() self.rdb = r.connect(host=hostname, port=port, db=db, timeout=20) try: self.rdb.table_create(table).run() except Exception, e: pass self.table = table def get_all(self): ...
c62e1b325a536294b3285f8cbcad7d66a415ee23
heat/objects/base.py
heat/objects/base.py
"""Heat common internal object model""" from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0'
"""Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None
Use a weakref for the data object context
Use a weakref for the data object context There are no known circular reference issues caused by storing the context in data objects, but the following changes will refer to data objects in the context, so this change prevents any later issues. Change-Id: I3680e5678003cf339a98fbb7a2b1b387fb2243c0 Related-Bug: #1578854
Python
apache-2.0
noironetworks/heat,openstack/heat,openstack/heat,cwolferh/heat-scratch,noironetworks/heat,cwolferh/heat-scratch
python
## Code Before: """Heat common internal object model""" from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' ## Instruction: Use a weakref for the data object context There are no known circular reference issues caused by storing the context in data objects, but the following changes will refer to data objects in the context, so this change prevents any later issues. Change-Id: I3680e5678003cf339a98fbb7a2b1b387fb2243c0 Related-Bug: #1578854 ## Code After: """Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None
... """Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base ... class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None ...
eb9d9196155e90c4949380c66ff8876f41bccc01
tomviz/python/tomviz/io/formats/numpy.py
tomviz/python/tomviz/io/formats/numpy.py
import numpy as np from tomviz.io import FileType, IOBase, Reader, Writer import tomviz.utils from vtk import vtkImageData class NumpyBase(IOBase): @staticmethod def file_type(): return FileType('NumPy binary format', ['npy']) class NumpyWriter(Writer, NumpyBase): def write(self, path, data_object): data = tomviz.utils.get_array(data_object) with open(path, "wb") as f: np.save(f, data) class NumpyReader(Reader, NumpyBase): def read(self, path): with open(path, "rb") as f: data = np.load(f) if len(data.shape) != 3: return vtkImageData() image_data = vtkImageData() (x, y, z) = data.shape image_data.SetOrigin(0, 0, 0) image_data.SetSpacing(1, 1, 1) image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1) tomviz.utils.set_array(image_data, data) return image_data
import numpy as np from tomviz.io import FileType, IOBase, Reader, Writer import tomviz.utils from vtk import vtkImageData class NumpyBase(IOBase): @staticmethod def file_type(): return FileType('NumPy binary format', ['npy']) class NumpyWriter(Writer, NumpyBase): def write(self, path, data_object): data = tomviz.utils.get_array(data_object) # Switch to row major order for NPY stores data = data.reshape(data.shape[::-1]) with open(path, "wb") as f: np.save(f, data) class NumpyReader(Reader, NumpyBase): def read(self, path): with open(path, "rb") as f: data = np.load(f) if len(data.shape) != 3: return vtkImageData() # NPY stores data as row major order. VTK expects column major order. data = data.reshape(data.shape[::-1]) image_data = vtkImageData() (x, y, z) = data.shape image_data.SetOrigin(0, 0, 0) image_data.SetSpacing(1, 1, 1) image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1) tomviz.utils.set_array(image_data, data) return image_data
Use C ordering for npy format
Use C ordering for npy format This appears to save and and load files correctly, but when loading, it prints this message: Warning, array does not have Fortran order, making deep copy and fixing... ...done. I'm looking into this... Signed-off-by: Patrick Avery <[email protected]>
Python
bsd-3-clause
OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
python
## Code Before: import numpy as np from tomviz.io import FileType, IOBase, Reader, Writer import tomviz.utils from vtk import vtkImageData class NumpyBase(IOBase): @staticmethod def file_type(): return FileType('NumPy binary format', ['npy']) class NumpyWriter(Writer, NumpyBase): def write(self, path, data_object): data = tomviz.utils.get_array(data_object) with open(path, "wb") as f: np.save(f, data) class NumpyReader(Reader, NumpyBase): def read(self, path): with open(path, "rb") as f: data = np.load(f) if len(data.shape) != 3: return vtkImageData() image_data = vtkImageData() (x, y, z) = data.shape image_data.SetOrigin(0, 0, 0) image_data.SetSpacing(1, 1, 1) image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1) tomviz.utils.set_array(image_data, data) return image_data ## Instruction: Use C ordering for npy format This appears to save and and load files correctly, but when loading, it prints this message: Warning, array does not have Fortran order, making deep copy and fixing... ...done. I'm looking into this... Signed-off-by: Patrick Avery <[email protected]> ## Code After: import numpy as np from tomviz.io import FileType, IOBase, Reader, Writer import tomviz.utils from vtk import vtkImageData class NumpyBase(IOBase): @staticmethod def file_type(): return FileType('NumPy binary format', ['npy']) class NumpyWriter(Writer, NumpyBase): def write(self, path, data_object): data = tomviz.utils.get_array(data_object) # Switch to row major order for NPY stores data = data.reshape(data.shape[::-1]) with open(path, "wb") as f: np.save(f, data) class NumpyReader(Reader, NumpyBase): def read(self, path): with open(path, "rb") as f: data = np.load(f) if len(data.shape) != 3: return vtkImageData() # NPY stores data as row major order. VTK expects column major order. data = data.reshape(data.shape[::-1]) image_data = vtkImageData() (x, y, z) = data.shape image_data.SetOrigin(0, 0, 0) image_data.SetSpacing(1, 1, 1) image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1) tomviz.utils.set_array(image_data, data) return image_data
// ... existing code ... def write(self, path, data_object): data = tomviz.utils.get_array(data_object) # Switch to row major order for NPY stores data = data.reshape(data.shape[::-1]) with open(path, "wb") as f: np.save(f, data) // ... modified code ... if len(data.shape) != 3: return vtkImageData() # NPY stores data as row major order. VTK expects column major order. data = data.reshape(data.shape[::-1]) image_data = vtkImageData() (x, y, z) = data.shape // ... rest of the code ...
ab5d343a91374119b1983e93a57fd47ab09ebc63
plinyproj/__version__.py
plinyproj/__version__.py
<<<<<<< HEAD __version_info__ = (0, 6, 0) ======= __version_info__ = (0, 5, 7) >>>>>>> hotfix/0.5.7 __version__ = '.'.join([str(i) for i in __version_info__])
__version_info__ = (0, 6, 0) __version__ = '.'.join([str(i) for i in __version_info__])
Fix version conflict and bump to 0.6
Fix version conflict and bump to 0.6
Python
mit
bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject
python
## Code Before: <<<<<<< HEAD __version_info__ = (0, 6, 0) ======= __version_info__ = (0, 5, 7) >>>>>>> hotfix/0.5.7 __version__ = '.'.join([str(i) for i in __version_info__]) ## Instruction: Fix version conflict and bump to 0.6 ## Code After: __version_info__ = (0, 6, 0) __version__ = '.'.join([str(i) for i in __version_info__])
# ... existing code ... __version_info__ = (0, 6, 0) __version__ = '.'.join([str(i) for i in __version_info__]) # ... rest of the code ...
fc8ac6ba5081e7847847d31588a65db8ea13416c
openprescribing/matrixstore/build/dates.py
openprescribing/matrixstore/build/dates.py
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months((year, month), months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
Fix another py27-ism which Black can't handle
Fix another py27-ism which Black can't handle Not sure how I missed this one last time.
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
python
## Code Before: DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months((year, month), months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1 ## Instruction: Fix another py27-ism which Black can't handle Not sure how I missed this one last time. ## Code After: DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
# ... existing code ... return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1 # ... rest of the code ...
910474568881ed229c3fdfddbafb8bf2a2740546
src/main/java/de/craften/plugins/educraft/luaapi/functions/MoveForwardFunction.java
src/main/java/de/craften/plugins/educraft/luaapi/functions/MoveForwardFunction.java
package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import java.util.Collection; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block blockAhead = getApi().getBlockAhead(); Location locationAhead = blockAhead.getLocation(); Collection<Entity> entities = getApi().getEntitiesAhead(); if (!blockAhead.getType().isSolid() && !blockAhead.getRelative(BlockFace.UP).getType().isSolid() && getApi().getEnvironment().getSheepAt(locationAhead) == null && getApi().getEnvironment().contains(locationAhead)) { getApi().moveTo(locationAhead, false); } return LuaValue.NIL; } }
package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block blockAhead = getApi().getBlockAhead(); Location locationAhead = blockAhead.getLocation(); if (!blockAhead.getType().isSolid() && !blockAhead.getRelative(BlockFace.UP).getType().isSolid() && getApi().getEnvironment().getSheepAt(locationAhead) == null && getApi().getEnvironment().contains(locationAhead)) { getApi().moveTo(locationAhead, false); } while (!blockAhead.getRelative(BlockFace.DOWN).getType().isSolid() && blockAhead.getY() > 0) { blockAhead = blockAhead.getRelative(BlockFace.DOWN); } getApi().moveTo(blockAhead.getLocation(), false); return LuaValue.NIL; } }
Make entity fall if there is no solid block below it.
Make entity fall if there is no solid block below it.
Java
mit
leMaik/EduCraft
java
## Code Before: package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import java.util.Collection; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block blockAhead = getApi().getBlockAhead(); Location locationAhead = blockAhead.getLocation(); Collection<Entity> entities = getApi().getEntitiesAhead(); if (!blockAhead.getType().isSolid() && !blockAhead.getRelative(BlockFace.UP).getType().isSolid() && getApi().getEnvironment().getSheepAt(locationAhead) == null && getApi().getEnvironment().contains(locationAhead)) { getApi().moveTo(locationAhead, false); } return LuaValue.NIL; } } ## Instruction: Make entity fall if there is no solid block below it. ## Code After: package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block blockAhead = getApi().getBlockAhead(); Location locationAhead = blockAhead.getLocation(); if (!blockAhead.getType().isSolid() && !blockAhead.getRelative(BlockFace.UP).getType().isSolid() && getApi().getEnvironment().getSheepAt(locationAhead) == null && getApi().getEnvironment().contains(locationAhead)) { getApi().moveTo(locationAhead, false); } while (!blockAhead.getRelative(BlockFace.DOWN).getType().isSolid() && blockAhead.getY() > 0) { blockAhead = blockAhead.getRelative(BlockFace.DOWN); } getApi().moveTo(blockAhead.getLocation(), false); return LuaValue.NIL; } }
... import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Lua API function to move one block forward. ... public Varargs execute(Varargs varargs) { Block blockAhead = getApi().getBlockAhead(); Location locationAhead = blockAhead.getLocation(); if (!blockAhead.getType().isSolid() && !blockAhead.getRelative(BlockFace.UP).getType().isSolid() ... getApi().moveTo(locationAhead, false); } while (!blockAhead.getRelative(BlockFace.DOWN).getType().isSolid() && blockAhead.getY() > 0) { blockAhead = blockAhead.getRelative(BlockFace.DOWN); } getApi().moveTo(blockAhead.getLocation(), false); return LuaValue.NIL; } } ...
3ced8676d474df3149bf78519e918cfa3b6b0ec3
src/dal_gm2m/fields.py
src/dal_gm2m/fields.py
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ x for x in getattr(instance, name).all()] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value)
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ getattr(x, 'gm2m_tgt', x) for x in getattr(instance, name).all() ] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value)
Support new versions with django-gm2m
Support new versions with django-gm2m
Python
mit
yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light
python
## Code Before: """GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ x for x in getattr(instance, name).all()] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value) ## Instruction: Support new versions with django-gm2m ## Code After: """GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ getattr(x, 'gm2m_tgt', x) for x in getattr(instance, name).all() ] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value)
// ... existing code ... def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ getattr(x, 'gm2m_tgt', x) for x in getattr(instance, name).all() ] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" // ... rest of the code ...
731e48b1b81e9249fc8bdd0f826c6e009559fcc3
mempoke.py
mempoke.py
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): value_bytes = struct.pack('I', value) self.inferior.write_memory(address, value_bytes)
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): value_bytes = struct.pack('I', value) self.inferior.write_memory(address, value_bytes) def create_memory_reg(offset, name): def reg_getter(self): return self.device_memory.read(self.address + offset) def reg_setter(self, value): self.device_memory.write(self.address + offset, value) return property(reg_getter, reg_setter, None, name) def create_mem_struct(name, registers): structure_fields = {} for register, offset in registers: structure_fields[register] = create_memory_reg(offset, register) def memory_structure_init(self, address, device_memory): self.address = address self.device_memory = device_memory structure_fields['__init__'] = memory_structure_init return type(name, (object,), structure_fields)
Add mechanism for defining MCU control structures
Add mechanism for defining MCU control structures
Python
mit
fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing
python
## Code Before: import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): value_bytes = struct.pack('I', value) self.inferior.write_memory(address, value_bytes) ## Instruction: Add mechanism for defining MCU control structures ## Code After: import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): value_bytes = struct.pack('I', value) self.inferior.write_memory(address, value_bytes) def create_memory_reg(offset, name): def reg_getter(self): return self.device_memory.read(self.address + offset) def reg_setter(self, value): self.device_memory.write(self.address + offset, value) return property(reg_getter, reg_setter, None, name) def create_mem_struct(name, registers): structure_fields = {} for register, offset in registers: structure_fields[register] = create_memory_reg(offset, register) def memory_structure_init(self, address, device_memory): self.address = address self.device_memory = device_memory structure_fields['__init__'] = memory_structure_init return type(name, (object,), structure_fields)
... def write(self, address, value): value_bytes = struct.pack('I', value) self.inferior.write_memory(address, value_bytes) def create_memory_reg(offset, name): def reg_getter(self): return self.device_memory.read(self.address + offset) def reg_setter(self, value): self.device_memory.write(self.address + offset, value) return property(reg_getter, reg_setter, None, name) def create_mem_struct(name, registers): structure_fields = {} for register, offset in registers: structure_fields[register] = create_memory_reg(offset, register) def memory_structure_init(self, address, device_memory): self.address = address self.device_memory = device_memory structure_fields['__init__'] = memory_structure_init return type(name, (object,), structure_fields) ...
2f4645ad10da0d9d0b9d726dc9beea453434af6e
app/src/test/java/pl/droidsonroids/droidsmap/OfficePresenterTest.kt
app/src/test/java/pl/droidsonroids/droidsmap/OfficePresenterTest.kt
package pl.droidsonroids.droidsmap import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.junit.Before import org.junit.Test import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeEntity import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeMvpView import pl.droidsonroids.droidsmap.feature.office.mvp.OfficePresenter import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeUiModel class OfficePresenterTest { lateinit var officeView : OfficeMvpView lateinit var officeBoundary : OfficeFeatureBoundary lateinit var presenter: OfficePresenter @Before fun setUp() { officeView = mock<OfficeMvpView>() officeBoundary = mock<OfficeFeatureBoundary>() presenter = OfficePresenter.create(officeView, officeBoundary) } @Test fun `should show map once data is provided`() { val officeEntity = OfficeEntity() whenever(officeBoundary.requestOffice(any())).thenAnswer { (it.arguments[0] as OfficeFeatureBoundary.Gateway).onOfficeEntityAvailable(officeEntity) } presenter.onRequestOffice() verify(officeView).displayOfficeRooms(OfficeUiModel.from(officeEntity)) } }
package pl.droidsonroids.droidsmap import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeEntity import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeMvpView import pl.droidsonroids.droidsmap.feature.office.mvp.OfficePresenter import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeUiModel class OfficePresenterTest { lateinit var officeView : OfficeMvpView lateinit var officeBoundary : OfficeFeatureBoundary lateinit var presenter: OfficePresenter @Before fun setUp() { officeView = mock<OfficeMvpView>() officeBoundary = mock<OfficeFeatureBoundary>() presenter = OfficePresenter.create(officeView, officeBoundary) } @Test fun `should show map once data is provided`() { val officeEntity = OfficeEntity() whenever(officeBoundary.requestOffice(any())).thenAnswer { (it.arguments[0] as OfficeFeatureBoundary.Gateway).onOfficeEntityAvailable(officeEntity) } presenter.onRequestOffice() with(OfficeUiModel.from(officeEntity)) { inOrder(officeView) { verify(officeView).setMapPanningConstraints(this@with) verify(officeView).focusMapOnOfficeLocation(this@with) verify(officeView).displayOfficeRooms(this@with) } } } }
Test office view methods invocation order
Test office view methods invocation order
Kotlin
mit
DroidsOnRoids/DroidsMap,DroidsOnRoids/DroidsMap
kotlin
## Code Before: package pl.droidsonroids.droidsmap import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.junit.Before import org.junit.Test import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeEntity import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeMvpView import pl.droidsonroids.droidsmap.feature.office.mvp.OfficePresenter import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeUiModel class OfficePresenterTest { lateinit var officeView : OfficeMvpView lateinit var officeBoundary : OfficeFeatureBoundary lateinit var presenter: OfficePresenter @Before fun setUp() { officeView = mock<OfficeMvpView>() officeBoundary = mock<OfficeFeatureBoundary>() presenter = OfficePresenter.create(officeView, officeBoundary) } @Test fun `should show map once data is provided`() { val officeEntity = OfficeEntity() whenever(officeBoundary.requestOffice(any())).thenAnswer { (it.arguments[0] as OfficeFeatureBoundary.Gateway).onOfficeEntityAvailable(officeEntity) } presenter.onRequestOffice() verify(officeView).displayOfficeRooms(OfficeUiModel.from(officeEntity)) } } ## Instruction: Test office view methods invocation order ## Code After: package pl.droidsonroids.droidsmap import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeEntity import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeMvpView import pl.droidsonroids.droidsmap.feature.office.mvp.OfficePresenter import pl.droidsonroids.droidsmap.feature.office.mvp.OfficeUiModel class OfficePresenterTest { lateinit var officeView : OfficeMvpView lateinit var officeBoundary : OfficeFeatureBoundary lateinit var presenter: OfficePresenter @Before fun setUp() { officeView = mock<OfficeMvpView>() officeBoundary = mock<OfficeFeatureBoundary>() presenter = OfficePresenter.create(officeView, officeBoundary) } @Test fun `should show map once data is provided`() { val officeEntity = OfficeEntity() whenever(officeBoundary.requestOffice(any())).thenAnswer { (it.arguments[0] as OfficeFeatureBoundary.Gateway).onOfficeEntityAvailable(officeEntity) } presenter.onRequestOffice() with(OfficeUiModel.from(officeEntity)) { inOrder(officeView) { verify(officeView).setMapPanningConstraints(this@with) verify(officeView).focusMapOnOfficeLocation(this@with) verify(officeView).displayOfficeRooms(this@with) } } } }
# ... existing code ... package pl.droidsonroids.droidsmap import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeEntity # ... modified code ... } presenter.onRequestOffice() with(OfficeUiModel.from(officeEntity)) { inOrder(officeView) { verify(officeView).setMapPanningConstraints(this@with) verify(officeView).focusMapOnOfficeLocation(this@with) verify(officeView).displayOfficeRooms(this@with) } } } } # ... rest of the code ...
c4dd6502bc7b9d5970a659c57e6aa2d25cc00fe5
catwatch/lib/util_datetime.py
catwatch/lib/util_datetime.py
import datetime def timedelta_months(months, compare_date=None): """ Return a JSON response. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: Flask response """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
import datetime def timedelta_months(months, compare_date=None): """ Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
Update timedelta_months docstring to be accurate
Update timedelta_months docstring to be accurate
Python
mit
z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
python
## Code Before: import datetime def timedelta_months(months, compare_date=None): """ Return a JSON response. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: Flask response """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta ## Instruction: Update timedelta_months docstring to be accurate ## Code After: import datetime def timedelta_months(months, compare_date=None): """ Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
// ... existing code ... def timedelta_months(months, compare_date=None): """ Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: datetime """ if compare_date is None: compare_date = datetime.date.today() // ... rest of the code ...
6136fc2bd2d9d191df7a9e6afd3aa9e4f110d61e
numpy/core/tests/test_print.py
numpy/core/tests/test_print.py
import numpy as np from numpy.testing import * class TestPrint(TestCase): def test_float_types(self) : """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(float(x))) def test_complex_types(self) : """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(complex(x))) assert_equal(str(t(x*1j)), str(complex(x*1j))) assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) if __name__ == "__main__": run_module_suite()
import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
Use parametric tests for format tests so that it is clearer which type is failing.
Use parametric tests for format tests so that it is clearer which type is failing.
Python
bsd-3-clause
solarjoe/numpy,NextThought/pypy-numpy,musically-ut/numpy,trankmichael/numpy,ViralLeadership/numpy,b-carter/numpy,argriffing/numpy,ogrisel/numpy,mhvk/numpy,mingwpy/numpy,b-carter/numpy,ewmoore/numpy,jakirkham/numpy,ahaldane/numpy,KaelChen/numpy,mhvk/numpy,utke1/numpy,ogrisel/numpy,skymanaditya1/numpy,rmcgibbo/numpy,embray/numpy,immerrr/numpy,ekalosak/numpy,skymanaditya1/numpy,ssanderson/numpy,pelson/numpy,abalkin/numpy,GaZ3ll3/numpy,rhythmsosad/numpy,kiwifb/numpy,numpy/numpy-refactor,nguyentu1602/numpy,maniteja123/numpy,BMJHayward/numpy,empeeu/numpy,has2k1/numpy,dwillmer/numpy,githubmlai/numpy,pyparallel/numpy,BMJHayward/numpy,seberg/numpy,Srisai85/numpy,AustereCuriosity/numpy,dwf/numpy,GrimDerp/numpy,numpy/numpy,charris/numpy,abalkin/numpy,Anwesh43/numpy,ViralLeadership/numpy,dato-code/numpy,rgommers/numpy,pizzathief/numpy,ChanderG/numpy,madphysicist/numpy,dwf/numpy,brandon-rhodes/numpy,gfyoung/numpy,groutr/numpy,numpy/numpy-refactor,CMartelLML/numpy,jonathanunderwood/numpy,rajathkumarmp/numpy,cowlicks/numpy,rhythmsosad/numpy,joferkington/numpy,joferkington/numpy,BabeNovelty/numpy,utke1/numpy,Yusa95/numpy,GrimDerp/numpy,astrofrog/numpy,charris/numpy,CMartelLML/numpy,GaZ3ll3/numpy,cjermain/numpy,ajdawson/numpy,MSeifert04/numpy,MaPePeR/numpy,has2k1/numpy,andsor/numpy,githubmlai/numpy,larsmans/numpy,matthew-brett/numpy,mindw/numpy,Dapid/numpy,nguyentu1602/numpy,gmcastil/numpy,abalkin/numpy,cjermain/numpy,rajathkumarmp/numpy,Anwesh43/numpy,mortada/numpy,sigma-random/numpy,numpy/numpy,chiffa/numpy,Dapid/numpy,mathdd/numpy,hainm/numpy,jschueller/numpy,ogrisel/numpy,brandon-rhodes/numpy,ewmoore/numpy,dwillmer/numpy,ekalosak/numpy,tacaswell/numpy,numpy/numpy-refactor,mwiebe/numpy,bertrand-l/numpy,jakirkham/numpy,endolith/numpy,embray/numpy,solarjoe/numpy,mattip/numpy,MaPePeR/numpy,mwiebe/numpy,AustereCuriosity/numpy,ESSS/numpy,matthew-brett/numpy,argriffing/numpy,nbeaver/numpy,dimasad/numpy,drasmuss/numpy,rudimeier/numpy,Eric89GXL/numpy,naritta/numpy,chatcannon/numpy,Dapid/numpy,jakirkham/numpy,AustereCuriosity/numpy,ESSS/numpy,tdsmith/numpy,rmcgibbo/numpy,pizzathief/numpy,rherault-insa/numpy,embray/numpy,seberg/numpy,rudimeier/numpy,mathdd/numpy,SunghanKim/numpy,MaPePeR/numpy,ddasilva/numpy,naritta/numpy,GrimDerp/numpy,nbeaver/numpy,numpy/numpy,drasmuss/numpy,kiwifb/numpy,mwiebe/numpy,bertrand-l/numpy,ogrisel/numpy,ahaldane/numpy,mortada/numpy,numpy/numpy-refactor,andsor/numpy,astrofrog/numpy,skwbc/numpy,MaPePeR/numpy,githubmlai/numpy,andsor/numpy,empeeu/numpy,dwillmer/numpy,CMartelLML/numpy,Srisai85/numpy,dimasad/numpy,madphysicist/numpy,cjermain/numpy,shoyer/numpy,ewmoore/numpy,drasmuss/numpy,bringingheavendown/numpy,dato-code/numpy,NextThought/pypy-numpy,Anwesh43/numpy,bmorris3/numpy,andsor/numpy,felipebetancur/numpy,mindw/numpy,mhvk/numpy,GaZ3ll3/numpy,skwbc/numpy,BMJHayward/numpy,jschueller/numpy,musically-ut/numpy,charris/numpy,matthew-brett/numpy,pelson/numpy,joferkington/numpy,seberg/numpy,jankoslavic/numpy,WillieMaddox/numpy,grlee77/numpy,Linkid/numpy,KaelChen/numpy,yiakwy/numpy,ChristopherHogan/numpy,MichaelAquilina/numpy,sigma-random/numpy,chatcannon/numpy,sinhrks/numpy,grlee77/numpy,dwillmer/numpy,SiccarPoint/numpy,gfyoung/numpy,pbrod/numpy,simongibbons/numpy,jorisvandenbossche/numpy,MSeifert04/numpy,ViralLeadership/numpy,yiakwy/numpy,njase/numpy,yiakwy/numpy,jorisvandenbossche/numpy,leifdenby/numpy,rhythmsosad/numpy,simongibbons/numpy,trankmichael/numpy,charris/numpy,brandon-rhodes/numpy,tdsmith/numpy,seberg/numpy,pdebuyl/numpy,numpy/numpy-refactor,rudimeier/numpy,anntzer/numpy,jorisvandenbossche/numpy,rajathkumarmp/numpy,musically-ut/numpy,grlee77/numpy,MSeifert04/numpy,bertrand-l/numpy,pyparallel/numpy,ajdawson/numpy,SunghanKim/numpy,KaelChen/numpy,jakirkham/numpy,chatcannon/numpy,kiwifb/numpy,pelson/numpy,Linkid/numpy,simongibbons/numpy,NextThought/pypy-numpy,madphysicist/numpy,MSeifert04/numpy,behzadnouri/numpy,shoyer/numpy,rherault-insa/numpy,WarrenWeckesser/numpy,ContinuumIO/numpy,embray/numpy,pdebuyl/numpy,kirillzhuravlev/numpy,utke1/numpy,larsmans/numpy,GrimDerp/numpy,immerrr/numpy,stefanv/numpy,dwf/numpy,sonnyhu/numpy,ewmoore/numpy,mhvk/numpy,ChanderG/numpy,hainm/numpy,SiccarPoint/numpy,jankoslavic/numpy,behzadnouri/numpy,musically-ut/numpy,mortada/numpy,pbrod/numpy,hainm/numpy,Yusa95/numpy,pizzathief/numpy,embray/numpy,leifdenby/numpy,stuarteberg/numpy,groutr/numpy,sigma-random/numpy,jankoslavic/numpy,solarjoe/numpy,moreati/numpy,pelson/numpy,immerrr/numpy,dimasad/numpy,endolith/numpy,hainm/numpy,larsmans/numpy,tynn/numpy,SunghanKim/numpy,trankmichael/numpy,nbeaver/numpy,pbrod/numpy,ChristopherHogan/numpy,ajdawson/numpy,sigma-random/numpy,dch312/numpy,tdsmith/numpy,stuarteberg/numpy,brandon-rhodes/numpy,has2k1/numpy,MichaelAquilina/numpy,mhvk/numpy,mingwpy/numpy,pelson/numpy,tynn/numpy,rgommers/numpy,felipebetancur/numpy,dato-code/numpy,rmcgibbo/numpy,WarrenWeckesser/numpy,WarrenWeckesser/numpy,rherault-insa/numpy,bringingheavendown/numpy,simongibbons/numpy,jakirkham/numpy,jorisvandenbossche/numpy,dwf/numpy,anntzer/numpy,jankoslavic/numpy,Yusa95/numpy,ajdawson/numpy,sinhrks/numpy,ogrisel/numpy,ssanderson/numpy,naritta/numpy,madphysicist/numpy,moreati/numpy,WarrenWeckesser/numpy,SunghanKim/numpy,numpy/numpy,jschueller/numpy,kirillzhuravlev/numpy,WillieMaddox/numpy,ssanderson/numpy,Eric89GXL/numpy,sinhrks/numpy,stuarteberg/numpy,SiccarPoint/numpy,endolith/numpy,tynn/numpy,maniteja123/numpy,BabeNovelty/numpy,skwbc/numpy,BabeNovelty/numpy,SiccarPoint/numpy,rudimeier/numpy,WarrenWeckesser/numpy,NextThought/pypy-numpy,trankmichael/numpy,dwf/numpy,sonnyhu/numpy,dch312/numpy,tacaswell/numpy,pbrod/numpy,ESSS/numpy,empeeu/numpy,larsmans/numpy,MSeifert04/numpy,maniteja123/numpy,bmorris3/numpy,gfyoung/numpy,mattip/numpy,jorisvandenbossche/numpy,ekalosak/numpy,moreati/numpy,pdebuyl/numpy,MichaelAquilina/numpy,kirillzhuravlev/numpy,ddasilva/numpy,Eric89GXL/numpy,matthew-brett/numpy,mortada/numpy,mathdd/numpy,empeeu/numpy,felipebetancur/numpy,Anwesh43/numpy,pdebuyl/numpy,ewmoore/numpy,bringingheavendown/numpy,behzadnouri/numpy,dato-code/numpy,astrofrog/numpy,Linkid/numpy,gmcastil/numpy,rhythmsosad/numpy,chiffa/numpy,endolith/numpy,stuarteberg/numpy,groutr/numpy,Linkid/numpy,GaZ3ll3/numpy,tacaswell/numpy,rajathkumarmp/numpy,jonathanunderwood/numpy,mindw/numpy,simongibbons/numpy,kirillzhuravlev/numpy,cowlicks/numpy,nguyentu1602/numpy,anntzer/numpy,njase/numpy,chiffa/numpy,pizzathief/numpy,shoyer/numpy,Srisai85/numpy,CMartelLML/numpy,githubmlai/numpy,WillieMaddox/numpy,ContinuumIO/numpy,ahaldane/numpy,mingwpy/numpy,madphysicist/numpy,naritta/numpy,sinhrks/numpy,KaelChen/numpy,stefanv/numpy,felipebetancur/numpy,yiakwy/numpy,cowlicks/numpy,MichaelAquilina/numpy,mindw/numpy,gmcastil/numpy,bmorris3/numpy,dch312/numpy,ahaldane/numpy,Yusa95/numpy,jonathanunderwood/numpy,grlee77/numpy,mathdd/numpy,sonnyhu/numpy,rgommers/numpy,rmcgibbo/numpy,tdsmith/numpy,astrofrog/numpy,sonnyhu/numpy,Srisai85/numpy,ahaldane/numpy,mattip/numpy,stefanv/numpy,shoyer/numpy,ChristopherHogan/numpy,ChanderG/numpy,rgommers/numpy,bmorris3/numpy,argriffing/numpy,mingwpy/numpy,pbrod/numpy,cjermain/numpy,pyparallel/numpy,anntzer/numpy,has2k1/numpy,b-carter/numpy,BMJHayward/numpy,stefanv/numpy,cowlicks/numpy,ChanderG/numpy,joferkington/numpy,skymanaditya1/numpy,dch312/numpy,BabeNovelty/numpy,matthew-brett/numpy,ddasilva/numpy,astrofrog/numpy,immerrr/numpy,jschueller/numpy,shoyer/numpy,grlee77/numpy,leifdenby/numpy,Eric89GXL/numpy,ChristopherHogan/numpy,ekalosak/numpy,stefanv/numpy,skymanaditya1/numpy,mattip/numpy,dimasad/numpy,ContinuumIO/numpy,njase/numpy,pizzathief/numpy,nguyentu1602/numpy
python
## Code Before: import numpy as np from numpy.testing import * class TestPrint(TestCase): def test_float_types(self) : """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(float(x))) def test_complex_types(self) : """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(t(x)), str(complex(x))) assert_equal(str(t(x*1j)), str(complex(x*1j))) assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) if __name__ == "__main__": run_module_suite() ## Instruction: Use parametric tests for format tests so that it is clearer which type is failing. ## Code After: import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
... import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite() ...
3e37e1e5919eb93ed25131fe088a12d9d8eb1f07
modules/jeditint/src/main/java/org/terasology/logic/jedit/JeditSystem.java
modules/jeditint/src/main/java/org/terasology/logic/jedit/JeditSystem.java
package org.terasology.logic.jedit; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.input.ButtonState; import org.terasology.input.binds.general.JeditButton; import org.terasology.network.ClientComponent; import org.terasology.utilities.jedit.JeditManager; /** * Open Jedit * @author Patricio Huepe */ @RegisterSystem public class JeditSystem extends BaseComponentSystem { @ReceiveEvent(components = ClientComponent.class) public void onToggleChat(JeditButton event, EntityRef entity) { if (event.getState() == ButtonState.DOWN) { JeditManager.openJedit("test.java"); event.consume(); } } }
package org.terasology.logic.jedit; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.input.ButtonState; import org.terasology.input.binds.general.JeditButton; import org.terasology.network.ClientComponent; import org.terasology.utilities.jedit.JeditManager; /** * Open Jedit * @author Patricio Huepe */ @RegisterSystem public class JeditSystem extends BaseComponentSystem { @ReceiveEvent(components = ClientComponent.class) public void openJedit(JeditButton event, EntityRef entity) { if (event.getState() == ButtonState.DOWN) { JeditManager.openJedit("test.java"); event.consume(); } } }
Change of a method name
Change of a method name
Java
apache-2.0
CC4401-TeraCity/TeraCity,Ciclop/Terasology,Ciclop/Terasology,CC4401-TeraCity/TeraCity
java
## Code Before: package org.terasology.logic.jedit; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.input.ButtonState; import org.terasology.input.binds.general.JeditButton; import org.terasology.network.ClientComponent; import org.terasology.utilities.jedit.JeditManager; /** * Open Jedit * @author Patricio Huepe */ @RegisterSystem public class JeditSystem extends BaseComponentSystem { @ReceiveEvent(components = ClientComponent.class) public void onToggleChat(JeditButton event, EntityRef entity) { if (event.getState() == ButtonState.DOWN) { JeditManager.openJedit("test.java"); event.consume(); } } } ## Instruction: Change of a method name ## Code After: package org.terasology.logic.jedit; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.input.ButtonState; import org.terasology.input.binds.general.JeditButton; import org.terasology.network.ClientComponent; import org.terasology.utilities.jedit.JeditManager; /** * Open Jedit * @author Patricio Huepe */ @RegisterSystem public class JeditSystem extends BaseComponentSystem { @ReceiveEvent(components = ClientComponent.class) public void openJedit(JeditButton event, EntityRef entity) { if (event.getState() == ButtonState.DOWN) { JeditManager.openJedit("test.java"); event.consume(); } } }
... @RegisterSystem public class JeditSystem extends BaseComponentSystem { @ReceiveEvent(components = ClientComponent.class) public void openJedit(JeditButton event, EntityRef entity) { if (event.getState() == ButtonState.DOWN) { JeditManager.openJedit("test.java"); event.consume(); ... } } } ...
96c14567ee54033a11bf1f8bc3b3eb0058c092f7
manoseimas/compatibility_test/admin.py
manoseimas/compatibility_test/admin.py
from django.contrib import admin from manoseimas.compatibility_test.models import CompatTest from manoseimas.compatibility_test.models import Topic from manoseimas.compatibility_test.models import TopicVoting from manoseimas.compatibility_test.models import Argument from manoseimas.compatibility_test.models import TestGroup class VotingInline(admin.TabularInline): model = TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(CompatTest, CompatTestAdmin) admin.site.register(Topic, TopicAdmin) admin.site.register(TestGroup, TestGroupAdmin)
from django.contrib import admin from manoseimas.compatibility_test import models class VotingInline(admin.TabularInline): model = models.TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = models.Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = models.TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(models.CompatTest, CompatTestAdmin) admin.site.register(models.Topic, TopicAdmin) admin.site.register(models.TestGroup, TestGroupAdmin)
Fix really strange bug about conflicting models
Fix really strange bug about conflicting models The bug: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ... ERROR ====================================================================== ERROR: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ---------------------------------------------------------------------- Traceback (most recent call last): eggs/nose-1.3.7-py2.7.egg/nose/loader.py|523| in makeTest return self._makeTest(obj, parent) eggs/nose-1.3.7-py2.7.egg/nose/loader.py|568| in _makeTest obj = transplant_class(obj, parent.__name__) eggs/nose-1.3.7-py2.7.egg/nose/util.py|642| in transplant_class class C(cls): eggs/Django-1.8.5-py2.7.egg/django/db/models/base.py|309| in __new__ new_class._meta.apps.register_model(new_class._meta.app_label, new_class) eggs/Django-1.8.5-py2.7.egg/django/apps/registry.py|221| in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>. Have no idea what is going on here, but it seems related to this bug report: https://code.djangoproject.com/ticket/22280 To reproduce this bug it is enough to add this line: from manoseimas.compatibility_test.models import TestGroup to `manoseimas/compatibility_test/admin.py`, some how it conflicts with `nose`, but I'm not sure what `nose` has to do with Django apps and models? Anyway changing the way how `TestGroup` is imported fixes the bug.
Python
agpl-3.0
ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt
python
## Code Before: from django.contrib import admin from manoseimas.compatibility_test.models import CompatTest from manoseimas.compatibility_test.models import Topic from manoseimas.compatibility_test.models import TopicVoting from manoseimas.compatibility_test.models import Argument from manoseimas.compatibility_test.models import TestGroup class VotingInline(admin.TabularInline): model = TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(CompatTest, CompatTestAdmin) admin.site.register(Topic, TopicAdmin) admin.site.register(TestGroup, TestGroupAdmin) ## Instruction: Fix really strange bug about conflicting models The bug: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ... ERROR ====================================================================== ERROR: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ---------------------------------------------------------------------- Traceback (most recent call last): eggs/nose-1.3.7-py2.7.egg/nose/loader.py|523| in makeTest return self._makeTest(obj, parent) eggs/nose-1.3.7-py2.7.egg/nose/loader.py|568| in _makeTest obj = transplant_class(obj, parent.__name__) eggs/nose-1.3.7-py2.7.egg/nose/util.py|642| in transplant_class class C(cls): eggs/Django-1.8.5-py2.7.egg/django/db/models/base.py|309| in __new__ new_class._meta.apps.register_model(new_class._meta.app_label, new_class) eggs/Django-1.8.5-py2.7.egg/django/apps/registry.py|221| in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>. Have no idea what is going on here, but it seems related to this bug report: https://code.djangoproject.com/ticket/22280 To reproduce this bug it is enough to add this line: from manoseimas.compatibility_test.models import TestGroup to `manoseimas/compatibility_test/admin.py`, some how it conflicts with `nose`, but I'm not sure what `nose` has to do with Django apps and models? Anyway changing the way how `TestGroup` is imported fixes the bug. ## Code After: from django.contrib import admin from manoseimas.compatibility_test import models class VotingInline(admin.TabularInline): model = models.TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = models.Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = models.TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(models.CompatTest, CompatTestAdmin) admin.site.register(models.Topic, TopicAdmin) admin.site.register(models.TestGroup, TestGroupAdmin)
... from django.contrib import admin from manoseimas.compatibility_test import models class VotingInline(admin.TabularInline): model = models.TopicVoting raw_id_fields = [ 'voting', ] ... class ArgumentInline(admin.TabularInline): model = models.Argument class TopicAdmin(admin.ModelAdmin): ... class TestGroupInline(admin.TabularInline): model = models.TestGroup class CompatTestAdmin(admin.ModelAdmin): ... class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(models.CompatTest, CompatTestAdmin) admin.site.register(models.Topic, TopicAdmin) admin.site.register(models.TestGroup, TestGroupAdmin) ...
27e5d7c74125784cb278b44e12881ca3596ee868
STM32F103GNU/src/startup.c
STM32F103GNU/src/startup.c
/* * startup.h * * Created on: Nov 15, 2016 * Author: RoyerAriel */ #ifndef STARTUP_C_ #define STARTUP_C_ #include "Timer.h" void startup() { //Start Systick Timer at 1ms Systick_Startup(); AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; //0x‭2000000‬ } #endif /* STARTUP_C_ */
/* * startup.h * * Created on: Nov 15, 2016 * Author: RoyerAriel */ #ifndef STARTUP_C_ #define STARTUP_C_ #include "Timer.h" void startup() { //Start Systick Timer at 1ms Systick_Startup(); AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; //0x‭2000000‬disable jtag } #endif /* STARTUP_C_ */
Disable Jtag came enable by default
Disable Jtag came enable by default Disable Jtag came enable by default and use GPIOB P04,P03 and P05
C
epl-1.0
royel21/STM32F103GNU,royel21/STM32F103GNU
c
## Code Before: /* * startup.h * * Created on: Nov 15, 2016 * Author: RoyerAriel */ #ifndef STARTUP_C_ #define STARTUP_C_ #include "Timer.h" void startup() { //Start Systick Timer at 1ms Systick_Startup(); AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; //0x‭2000000‬ } #endif /* STARTUP_C_ */ ## Instruction: Disable Jtag came enable by default Disable Jtag came enable by default and use GPIOB P04,P03 and P05 ## Code After: /* * startup.h * * Created on: Nov 15, 2016 * Author: RoyerAriel */ #ifndef STARTUP_C_ #define STARTUP_C_ #include "Timer.h" void startup() { //Start Systick Timer at 1ms Systick_Startup(); AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; //0x‭2000000‬disable jtag } #endif /* STARTUP_C_ */
... { //Start Systick Timer at 1ms Systick_Startup(); AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; //0x‭2000000‬disable jtag } ...
4c147d483d009a9ee6c34336c88f261b909e8b42
app/src/main/java/com/alorma/github/utils/NaturalTimeFormatter.java
app/src/main/java/com/alorma/github/utils/NaturalTimeFormatter.java
package com.alorma.github.utils; import android.content.Context; import tk.zielony.naturaldateformat.AbsoluteDateFormat; import tk.zielony.naturaldateformat.NaturalDateFormat; import tk.zielony.naturaldateformat.RelativeDateFormat; public class NaturalTimeFormatter implements TimeFormatter { private Context context; public NaturalTimeFormatter(Context context) { this.context = context; } @Override public String relative(long milis) { RelativeDateFormat relFormat = new RelativeDateFormat(context, NaturalDateFormat.TIME); return relFormat.format(milis); } @Override public String absolute(long milis) { AbsoluteDateFormat absFormat = new AbsoluteDateFormat(context, NaturalDateFormat.DATE | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES); return absFormat.format(milis); } }
package com.alorma.github.utils; import android.content.Context; import tk.zielony.naturaldateformat.AbsoluteDateFormat; import tk.zielony.naturaldateformat.NaturalDateFormat; import tk.zielony.naturaldateformat.RelativeDateFormat; public class NaturalTimeFormatter implements TimeFormatter { private Context context; public NaturalTimeFormatter(Context context) { this.context = context; } @Override public String relative(long milis) { RelativeDateFormat relFormat = new RelativeDateFormat(context, NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS); return relFormat.format(milis); } @Override public String absolute(long milis) { AbsoluteDateFormat absFormat = new AbsoluteDateFormat(context, NaturalDateFormat.DATE | NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES); return absFormat.format(milis); } }
Improve time visibility on Milestone
Improve time visibility on Milestone
Java
mit
epiphany27/Gitskarios,gitskarios/Gitskarios,gitskarios/Gitskarios,epiphany27/Gitskarios,gitskarios/Gitskarios,epiphany27/Gitskarios
java
## Code Before: package com.alorma.github.utils; import android.content.Context; import tk.zielony.naturaldateformat.AbsoluteDateFormat; import tk.zielony.naturaldateformat.NaturalDateFormat; import tk.zielony.naturaldateformat.RelativeDateFormat; public class NaturalTimeFormatter implements TimeFormatter { private Context context; public NaturalTimeFormatter(Context context) { this.context = context; } @Override public String relative(long milis) { RelativeDateFormat relFormat = new RelativeDateFormat(context, NaturalDateFormat.TIME); return relFormat.format(milis); } @Override public String absolute(long milis) { AbsoluteDateFormat absFormat = new AbsoluteDateFormat(context, NaturalDateFormat.DATE | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES); return absFormat.format(milis); } } ## Instruction: Improve time visibility on Milestone ## Code After: package com.alorma.github.utils; import android.content.Context; import tk.zielony.naturaldateformat.AbsoluteDateFormat; import tk.zielony.naturaldateformat.NaturalDateFormat; import tk.zielony.naturaldateformat.RelativeDateFormat; public class NaturalTimeFormatter implements TimeFormatter { private Context context; public NaturalTimeFormatter(Context context) { this.context = context; } @Override public String relative(long milis) { RelativeDateFormat relFormat = new RelativeDateFormat(context, NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS); return relFormat.format(milis); } @Override public String absolute(long milis) { AbsoluteDateFormat absFormat = new AbsoluteDateFormat(context, NaturalDateFormat.DATE | NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES); return absFormat.format(milis); } }
# ... existing code ... @Override public String relative(long milis) { RelativeDateFormat relFormat = new RelativeDateFormat(context, NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS); return relFormat.format(milis); } # ... modified code ... @Override public String absolute(long milis) { AbsoluteDateFormat absFormat = new AbsoluteDateFormat(context, NaturalDateFormat.DATE | NaturalDateFormat.MONTHS | NaturalDateFormat.DAYS | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES); return absFormat.format(milis); } } # ... rest of the code ...
a4c7d804b817cc6a7321278286ab85624a007e04
test/com/karateca/jstoolbox/dashcamel/CaseHelperTest.java
test/com/karateca/jstoolbox/dashcamel/CaseHelperTest.java
package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } }
package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); assertEquals("o", CaseHelper.toCamelCase("o")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("x", CaseHelper.toCamelCase(" x -- - - - ")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } @Test public void shouldTransformCamelToDash() { assertEquals("one-two", CaseHelper.toDashCase("oneTwo")); } }
Add test for dash case
Add test for dash case
Java
mit
andresdominguez/jsToolbox,andresdominguez/jsToolbox
java
## Code Before: package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } } ## Instruction: Add test for dash case ## Code After: package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); assertEquals("o", CaseHelper.toCamelCase("o")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("x", CaseHelper.toCamelCase(" x -- - - - ")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } @Test public void shouldTransformCamelToDash() { assertEquals("one-two", CaseHelper.toDashCase("oneTwo")); } }
... public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); assertEquals("o", CaseHelper.toCamelCase("o")); } @Test ... public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("x", CaseHelper.toCamelCase(" x -- - - - ")); } @Test ... public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } @Test public void shouldTransformCamelToDash() { assertEquals("one-two", CaseHelper.toDashCase("oneTwo")); } } ...
716f6d2f8ed4e2845746bcb803092806dd8f50b7
tx_salaries/utils/transformers/mixins.py
tx_salaries/utils/transformers/mixins.py
class OrganizationMixin(object): """ Adds a generic ``organization`` property to the class This requires that the class mixing it in adds an ``ORGANIZATION_NAME`` property of the main level agency or department. """ @property def organization(self): return { 'name': self.ORGANIZATION_NAME, 'children': [{ 'name': unicode(self.department), }], }
class OrganizationMixin(object): """ Adds a generic ``organization`` property to the class This requires that the class mixing it in adds an ``ORGANIZATION_NAME`` property of the main level agency or department and needs a ``department`` property. """ @property def organization(self): return { 'name': self.ORGANIZATION_NAME, 'children': [{ 'name': unicode(self.department), }], }
Tweak the wording just a bit
Tweak the wording just a bit
Python
apache-2.0
texastribune/tx_salaries,texastribune/tx_salaries
python
## Code Before: class OrganizationMixin(object): """ Adds a generic ``organization`` property to the class This requires that the class mixing it in adds an ``ORGANIZATION_NAME`` property of the main level agency or department. """ @property def organization(self): return { 'name': self.ORGANIZATION_NAME, 'children': [{ 'name': unicode(self.department), }], } ## Instruction: Tweak the wording just a bit ## Code After: class OrganizationMixin(object): """ Adds a generic ``organization`` property to the class This requires that the class mixing it in adds an ``ORGANIZATION_NAME`` property of the main level agency or department and needs a ``department`` property. """ @property def organization(self): return { 'name': self.ORGANIZATION_NAME, 'children': [{ 'name': unicode(self.department), }], }
# ... existing code ... This requires that the class mixing it in adds an ``ORGANIZATION_NAME`` property of the main level agency or department and needs a ``department`` property. """ @property def organization(self): # ... rest of the code ...
f9698eb96ca0c69a9d41a2d19a56af83e74da949
examples/advanced/extend_python.py
examples/advanced/extend_python.py
from lark.lark import Lark from python_parser import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty())
from lark.lark import Lark from lark.indenter import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty())
Fix confusing import (no change in functionality)
Fix confusing import (no change in functionality)
Python
mit
lark-parser/lark
python
## Code Before: from lark.lark import Lark from python_parser import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty()) ## Instruction: Fix confusing import (no change in functionality) ## Code After: from lark.lark import Lark from lark.indenter import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty())
// ... existing code ... from lark.lark import Lark from lark.indenter import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) // ... rest of the code ...
bcc2988c70e9b87de9ae6b1cd7c83500beff2b29
vangogh/src/main/java/com/pspdfkit/vangogh/api/AnimationSchedulers.java
vangogh/src/main/java/com/pspdfkit/vangogh/api/AnimationSchedulers.java
package com.pspdfkit.vangogh.api; import com.pspdfkit.vangogh.rx.AnimationCompletable; import io.reactivex.Completable; /** * Class containing convenient animation scheduling methods. */ public final class AnimationSchedulers { /** * Animates given animations at the same time. * @param animations Animation to execute together. * @return Completable finishing once the last animation is completed. */ public static Completable together(AnimationCompletable... animations) { return Completable.mergeArray(animations); } /** * Animates given animations one after another * @param animations Animation to execute sequentially. * @return Completable finishing once the last animation is completed. */ public static Completable sequentially(AnimationCompletable... animations) { return Completable.concatArray(animations); } }
package com.pspdfkit.vangogh.api; import com.pspdfkit.vangogh.rx.AnimationCompletable; import io.reactivex.Completable; /** * Class containing convenient animation scheduling methods. */ public final class AnimationSchedulers { /** * Animates given animations at the same time. * @param animations Animations to execute together. * @return Completable finishing once the last animation is completed. */ public static Completable together(Completable... animations) { return Completable.mergeArray(animations); } /** * Animates given animations one after another * @param animations Animations to execute sequentially. * @return Completable finishing once the last animation is completed. */ public static Completable sequentially(Completable... animations) { return Completable.concatArray(animations); } }
Enable scheduling Completables, not just AnimationCompletables
Enable scheduling Completables, not just AnimationCompletables
Java
mit
PSPDFKit-labs/VanGogh
java
## Code Before: package com.pspdfkit.vangogh.api; import com.pspdfkit.vangogh.rx.AnimationCompletable; import io.reactivex.Completable; /** * Class containing convenient animation scheduling methods. */ public final class AnimationSchedulers { /** * Animates given animations at the same time. * @param animations Animation to execute together. * @return Completable finishing once the last animation is completed. */ public static Completable together(AnimationCompletable... animations) { return Completable.mergeArray(animations); } /** * Animates given animations one after another * @param animations Animation to execute sequentially. * @return Completable finishing once the last animation is completed. */ public static Completable sequentially(AnimationCompletable... animations) { return Completable.concatArray(animations); } } ## Instruction: Enable scheduling Completables, not just AnimationCompletables ## Code After: package com.pspdfkit.vangogh.api; import com.pspdfkit.vangogh.rx.AnimationCompletable; import io.reactivex.Completable; /** * Class containing convenient animation scheduling methods. */ public final class AnimationSchedulers { /** * Animates given animations at the same time. * @param animations Animations to execute together. * @return Completable finishing once the last animation is completed. */ public static Completable together(Completable... animations) { return Completable.mergeArray(animations); } /** * Animates given animations one after another * @param animations Animations to execute sequentially. * @return Completable finishing once the last animation is completed. */ public static Completable sequentially(Completable... animations) { return Completable.concatArray(animations); } }
# ... existing code ... /** * Animates given animations at the same time. * @param animations Animations to execute together. * @return Completable finishing once the last animation is completed. */ public static Completable together(Completable... animations) { return Completable.mergeArray(animations); } /** * Animates given animations one after another * @param animations Animations to execute sequentially. * @return Completable finishing once the last animation is completed. */ public static Completable sequentially(Completable... animations) { return Completable.concatArray(animations); } # ... rest of the code ...
9a320dc49927cbcc910232dbeabb8999d3fb2896
core/editline/src/rlcurses.h
core/editline/src/rlcurses.h
// @(#)root/editline:$Id$ // Author: Axel Naumann, 2009 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifdef __sun # include R__CURSESHDR extern "C" { // cannot #include term.fH because it #defines move() etc char *tparm(char*, long, long, long, long, long, long, long, long, long); char *tigetstr(char*); char *tgoto(char*, int, int); int tputs(char*, int, int (*)(int)); int tgetflag(char*); int tgetnum(char*); char* tgetstr(char*, char**); int tgetent(char*, const char*); } // un-be-lievable. # undef erase # undef move # undef clear # undef del # undef key_end # undef key_clear # undef key_print #else # include R__CURSESHDR # include <termcap.h> # include <termcap.h> extern "C" int setupterm(const char* term, int fd, int* perrcode); #endif
// @(#)root/editline:$Id$ // Author: Axel Naumann, 2009 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifdef __sun # include R__CURSESHDR extern "C" { // cannot #include term.h because it #defines move() etc char *tparm(char*, long, long, long, long, long, long, long, long, long); char *tigetstr(char*); int tigetnum(char*); char *tgoto(char*, int, int); int tputs(char*, int, int (*)(int)); int tgetflag(char*); int tgetnum(char*); char* tgetstr(char*, char**); int tgetent(char*, const char*); } // un-be-lievable. # undef erase # undef move # undef clear # undef del # undef key_end # undef key_clear # undef key_print #else # include R__CURSESHDR # include <termcap.h> # include <termcap.h> extern "C" int setupterm(const char* term, int fd, int* perrcode); #endif
Fix for solaris: declare tigetnum
Fix for solaris: declare tigetnum git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@30238 27541ba8-7e3a-0410-8455-c3a389f83636
C
lgpl-2.1
tc3t/qoot,zzxuanyuan/root-compressor-dummy,simonpf/root,ffurano/root5,veprbl/root,zzxuanyuan/root-compressor-dummy,Duraznos/root,CristinaCristescu/root,thomaskeck/root,olifre/root,perovic/root,evgeny-boger/root,perovic/root,CristinaCristescu/root,bbockelm/root,thomaskeck/root,beniz/root,abhinavmoudgil95/root,mattkretz/root,arch1tect0r/root,kirbyherm/root-r-tools,esakellari/root,lgiommi/root,buuck/root,gbitzes/root,sirinath/root,satyarth934/root,omazapa/root-old,krafczyk/root,sawenzel/root,CristinaCristescu/root,mkret2/root,bbockelm/root,agarciamontoro/root,gbitzes/root,perovic/root,vukasinmilosevic/root,ffurano/root5,krafczyk/root,bbockelm/root,buuck/root,smarinac/root,jrtomps/root,abhinavmoudgil95/root,veprbl/root,Y--/root,karies/root,krafczyk/root,perovic/root,krafczyk/root,evgeny-boger/root,arch1tect0r/root,Duraznos/root,Duraznos/root,simonpf/root,CristinaCristescu/root,thomaskeck/root,mkret2/root,strykejern/TTreeReader,gganis/root,strykejern/TTreeReader,mattkretz/root,zzxuanyuan/root-compressor-dummy,davidlt/root,buuck/root,zzxuanyuan/root-compressor-dummy,smarinac/root,kirbyherm/root-r-tools,omazapa/root,gganis/root,esakellari/root,sbinet/cxx-root,nilqed/root,lgiommi/root,abhinavmoudgil95/root,olifre/root,evgeny-boger/root,omazapa/root,Dr15Jones/root,gganis/root,sirinath/root,cxx-hep/root-cern,mkret2/root,root-mirror/root,BerserkerTroll/root,zzxuanyuan/root,perovic/root,davidlt/root,cxx-hep/root-cern,esakellari/root,sawenzel/root,pspe/root,dfunke/root,root-mirror/root,gbitzes/root,arch1tect0r/root,esakellari/root,pspe/root,pspe/root,zzxuanyuan/root-compressor-dummy,Duraznos/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,jrtomps/root,simonpf/root,davidlt/root,evgeny-boger/root,georgtroska/root,gganis/root,0x0all/ROOT,gganis/root,dfunke/root,root-mirror/root,mkret2/root,cxx-hep/root-cern,georgtroska/root,nilqed/root,arch1tect0r/root,evgeny-boger/root,sbinet/cxx-root,omazapa/root,sirinath/root,gbitzes/root,gbitzes/root,georgtroska/root,Y--/root,olifre/root,zzxuanyuan/root-compressor-dummy,veprbl/root,root-mirror/root,tc3t/qoot,davidlt/root,karies/root,sbinet/cxx-root,satyarth934/root,beniz/root,esakellari/root,Duraznos/root,BerserkerTroll/root,perovic/root,arch1tect0r/root,arch1tect0r/root,evgeny-boger/root,dfunke/root,0x0all/ROOT,smarinac/root,pspe/root,sbinet/cxx-root,CristinaCristescu/root,krafczyk/root,jrtomps/root,bbockelm/root,agarciamontoro/root,gbitzes/root,Y--/root,davidlt/root,Duraznos/root,sirinath/root,sawenzel/root,mhuwiler/rootauto,simonpf/root,lgiommi/root,buuck/root,mattkretz/root,tc3t/qoot,vukasinmilosevic/root,Dr15Jones/root,BerserkerTroll/root,lgiommi/root,alexschlueter/cern-root,Y--/root,dfunke/root,BerserkerTroll/root,dfunke/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,omazapa/root-old,Y--/root,smarinac/root,nilqed/root,mattkretz/root,abhinavmoudgil95/root,CristinaCristescu/root,abhinavmoudgil95/root,pspe/root,buuck/root,georgtroska/root,jrtomps/root,lgiommi/root,mkret2/root,thomaskeck/root,ffurano/root5,olifre/root,tc3t/qoot,mattkretz/root,davidlt/root,0x0all/ROOT,esakellari/my_root_for_test,veprbl/root,davidlt/root,vukasinmilosevic/root,0x0all/ROOT,thomaskeck/root,smarinac/root,dfunke/root,krafczyk/root,mhuwiler/rootauto,zzxuanyuan/root,simonpf/root,BerserkerTroll/root,mkret2/root,nilqed/root,olifre/root,Dr15Jones/root,thomaskeck/root,veprbl/root,evgeny-boger/root,thomaskeck/root,abhinavmoudgil95/root,pspe/root,arch1tect0r/root,esakellari/my_root_for_test,CristinaCristescu/root,root-mirror/root,karies/root,Y--/root,esakellari/root,agarciamontoro/root,sbinet/cxx-root,Duraznos/root,sirinath/root,alexschlueter/cern-root,bbockelm/root,nilqed/root,smarinac/root,karies/root,omazapa/root,vukasinmilosevic/root,omazapa/root-old,esakellari/my_root_for_test,root-mirror/root,pspe/root,gganis/root,krafczyk/root,omazapa/root-old,thomaskeck/root,karies/root,gbitzes/root,mattkretz/root,sirinath/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,olifre/root,bbockelm/root,dfunke/root,simonpf/root,CristinaCristescu/root,omazapa/root-old,CristinaCristescu/root,omazapa/root-old,pspe/root,CristinaCristescu/root,arch1tect0r/root,abhinavmoudgil95/root,esakellari/root,buuck/root,sirinath/root,satyarth934/root,0x0all/ROOT,zzxuanyuan/root,veprbl/root,lgiommi/root,krafczyk/root,tc3t/qoot,jrtomps/root,0x0all/ROOT,mhuwiler/rootauto,satyarth934/root,evgeny-boger/root,BerserkerTroll/root,cxx-hep/root-cern,zzxuanyuan/root,jrtomps/root,tc3t/qoot,BerserkerTroll/root,omazapa/root,satyarth934/root,agarciamontoro/root,jrtomps/root,gbitzes/root,zzxuanyuan/root,mhuwiler/rootauto,esakellari/root,agarciamontoro/root,veprbl/root,zzxuanyuan/root,olifre/root,vukasinmilosevic/root,bbockelm/root,sbinet/cxx-root,karies/root,sawenzel/root,esakellari/my_root_for_test,Y--/root,jrtomps/root,mkret2/root,Y--/root,smarinac/root,abhinavmoudgil95/root,mattkretz/root,sirinath/root,davidlt/root,sirinath/root,simonpf/root,davidlt/root,sawenzel/root,strykejern/TTreeReader,0x0all/ROOT,perovic/root,jrtomps/root,sawenzel/root,mattkretz/root,gbitzes/root,buuck/root,beniz/root,veprbl/root,agarciamontoro/root,alexschlueter/cern-root,cxx-hep/root-cern,Duraznos/root,mkret2/root,zzxuanyuan/root,tc3t/qoot,nilqed/root,gganis/root,mhuwiler/rootauto,Dr15Jones/root,esakellari/root,veprbl/root,root-mirror/root,sawenzel/root,satyarth934/root,strykejern/TTreeReader,gbitzes/root,alexschlueter/cern-root,vukasinmilosevic/root,cxx-hep/root-cern,pspe/root,satyarth934/root,bbockelm/root,sbinet/cxx-root,ffurano/root5,BerserkerTroll/root,esakellari/my_root_for_test,pspe/root,nilqed/root,beniz/root,omazapa/root,gganis/root,satyarth934/root,strykejern/TTreeReader,Dr15Jones/root,gganis/root,strykejern/TTreeReader,georgtroska/root,gganis/root,perovic/root,mhuwiler/rootauto,buuck/root,cxx-hep/root-cern,karies/root,karies/root,sawenzel/root,kirbyherm/root-r-tools,davidlt/root,georgtroska/root,agarciamontoro/root,beniz/root,dfunke/root,simonpf/root,buuck/root,sbinet/cxx-root,bbockelm/root,evgeny-boger/root,alexschlueter/cern-root,satyarth934/root,vukasinmilosevic/root,arch1tect0r/root,sawenzel/root,jrtomps/root,CristinaCristescu/root,ffurano/root5,omazapa/root,0x0all/ROOT,georgtroska/root,dfunke/root,satyarth934/root,ffurano/root5,mhuwiler/rootauto,kirbyherm/root-r-tools,krafczyk/root,esakellari/root,bbockelm/root,cxx-hep/root-cern,evgeny-boger/root,mkret2/root,karies/root,georgtroska/root,beniz/root,smarinac/root,evgeny-boger/root,sirinath/root,mkret2/root,esakellari/my_root_for_test,arch1tect0r/root,mattkretz/root,perovic/root,lgiommi/root,simonpf/root,kirbyherm/root-r-tools,lgiommi/root,georgtroska/root,esakellari/my_root_for_test,alexschlueter/cern-root,beniz/root,abhinavmoudgil95/root,zzxuanyuan/root,omazapa/root-old,veprbl/root,zzxuanyuan/root,omazapa/root-old,sawenzel/root,olifre/root,omazapa/root-old,georgtroska/root,perovic/root,simonpf/root,root-mirror/root,agarciamontoro/root,vukasinmilosevic/root,nilqed/root,esakellari/my_root_for_test,Dr15Jones/root,perovic/root,mhuwiler/rootauto,mkret2/root,buuck/root,smarinac/root,nilqed/root,olifre/root,karies/root,veprbl/root,arch1tect0r/root,mattkretz/root,satyarth934/root,lgiommi/root,simonpf/root,olifre/root,davidlt/root,esakellari/my_root_for_test,tc3t/qoot,gbitzes/root,root-mirror/root,gganis/root,omazapa/root,beniz/root,vukasinmilosevic/root,omazapa/root,esakellari/root,georgtroska/root,vukasinmilosevic/root,abhinavmoudgil95/root,nilqed/root,Duraznos/root,sbinet/cxx-root,Y--/root,zzxuanyuan/root,karies/root,beniz/root,BerserkerTroll/root,Duraznos/root,thomaskeck/root,zzxuanyuan/root,krafczyk/root,buuck/root,esakellari/my_root_for_test,beniz/root,thomaskeck/root,abhinavmoudgil95/root,tc3t/qoot,sirinath/root,sbinet/cxx-root,beniz/root,omazapa/root-old,mhuwiler/rootauto,jrtomps/root,omazapa/root,nilqed/root,kirbyherm/root-r-tools,root-mirror/root,omazapa/root,zzxuanyuan/root,Y--/root,bbockelm/root,agarciamontoro/root,0x0all/ROOT,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,lgiommi/root,lgiommi/root,sbinet/cxx-root,dfunke/root,agarciamontoro/root,root-mirror/root,tc3t/qoot,krafczyk/root,BerserkerTroll/root,vukasinmilosevic/root,smarinac/root,Y--/root,kirbyherm/root-r-tools,pspe/root,olifre/root,alexschlueter/cern-root,Dr15Jones/root,ffurano/root5,dfunke/root,Duraznos/root,strykejern/TTreeReader,sawenzel/root,mattkretz/root,omazapa/root-old
c
## Code Before: // @(#)root/editline:$Id$ // Author: Axel Naumann, 2009 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifdef __sun # include R__CURSESHDR extern "C" { // cannot #include term.fH because it #defines move() etc char *tparm(char*, long, long, long, long, long, long, long, long, long); char *tigetstr(char*); char *tgoto(char*, int, int); int tputs(char*, int, int (*)(int)); int tgetflag(char*); int tgetnum(char*); char* tgetstr(char*, char**); int tgetent(char*, const char*); } // un-be-lievable. # undef erase # undef move # undef clear # undef del # undef key_end # undef key_clear # undef key_print #else # include R__CURSESHDR # include <termcap.h> # include <termcap.h> extern "C" int setupterm(const char* term, int fd, int* perrcode); #endif ## Instruction: Fix for solaris: declare tigetnum git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@30238 27541ba8-7e3a-0410-8455-c3a389f83636 ## Code After: // @(#)root/editline:$Id$ // Author: Axel Naumann, 2009 /************************************************************************* * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifdef __sun # include R__CURSESHDR extern "C" { // cannot #include term.h because it #defines move() etc char *tparm(char*, long, long, long, long, long, long, long, long, long); char *tigetstr(char*); int tigetnum(char*); char *tgoto(char*, int, int); int tputs(char*, int, int (*)(int)); int tgetflag(char*); int tgetnum(char*); char* tgetstr(char*, char**); int tgetent(char*, const char*); } // un-be-lievable. # undef erase # undef move # undef clear # undef del # undef key_end # undef key_clear # undef key_print #else # include R__CURSESHDR # include <termcap.h> # include <termcap.h> extern "C" int setupterm(const char* term, int fd, int* perrcode); #endif
... #ifdef __sun # include R__CURSESHDR extern "C" { // cannot #include term.h because it #defines move() etc char *tparm(char*, long, long, long, long, long, long, long, long, long); char *tigetstr(char*); int tigetnum(char*); char *tgoto(char*, int, int); int tputs(char*, int, int (*)(int)); int tgetflag(char*); ...
e21fd90de3b97f3ea2564a8d2c35351f2136b4e5
feder/letters/tests/base.py
feder/letters/tests/base.py
import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='[email protected]') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open('git-lfs.github.com', 'r'): if 'git-lfs' in line: raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert()
import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='[email protected]') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open(path, 'r'): if 'git-lfs' in line: raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert()
Fix detect Git-LFS in tests
Fix detect Git-LFS in tests
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
python
## Code Before: import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='[email protected]') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open('git-lfs.github.com', 'r'): if 'git-lfs' in line: raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert() ## Instruction: Fix detect Git-LFS in tests ## Code After: import email from os.path import dirname, join from django.utils import six from django_mailbox.models import Mailbox from feder.letters.signals import MessageParser class MessageMixin(object): def setUp(self): self.mailbox = Mailbox.objects.create(from_email='[email protected]') super(MessageMixin, self).setUp() @staticmethod def _get_email_path(filename): return join(dirname(__file__), 'messages', filename) @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open(path, 'r'): if 'git-lfs' in line: raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename)) if six.PY3: return email.message_from_file(open(path, 'r')) else: # Deprecated. Back-ward compatible for PY2.7< return email.message_from_file(open(path, 'rb')) def get_message(self, filename): message = self._get_email_object(filename) msg = self.mailbox._process_message(message) msg.save() return msg def load_letter(self, name): message = self.get_message(name) return MessageParser(message).insert()
# ... existing code ... @staticmethod def _get_email_object(filename): # See coddingtonbear/django-mailbox#89 path = MessageMixin._get_email_path(filename) for line in open(path, 'r'): if 'git-lfs' in line: raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename)) if six.PY3: # ... rest of the code ...
7cd69c1a4b8cc221bbbb40d5b2a1a53a835b11e9
nhs/raw/urls.py
nhs/raw/urls.py
from django.conf.urls.defaults import patterns, url from nhs.raw.views import Ratio, Drug urlpatterns = patterns( '', url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$', Ratio.as_view(), name='rawcompare'), url(r'/drug/percapitamap/ccg/(?P<bnf_code>[0-9A-Z]+)/percap.zip$', Drug.as_view(), name='rawdrug'), )
from django.conf.urls.defaults import patterns, url from nhs.raw.views import Ratio, Drug urlpatterns = patterns( '', url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$', Ratio.as_view(), name='rawcompare'), url(r'/drug/(?P<bnf_code>[0-9A-Z]+)/percap.zip$', Drug.as_view(), name='rawdrug'), )
Update URls for raw download.
Update URls for raw download.
Python
agpl-3.0
openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing
python
## Code Before: from django.conf.urls.defaults import patterns, url from nhs.raw.views import Ratio, Drug urlpatterns = patterns( '', url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$', Ratio.as_view(), name='rawcompare'), url(r'/drug/percapitamap/ccg/(?P<bnf_code>[0-9A-Z]+)/percap.zip$', Drug.as_view(), name='rawdrug'), ) ## Instruction: Update URls for raw download. ## Code After: from django.conf.urls.defaults import patterns, url from nhs.raw.views import Ratio, Drug urlpatterns = patterns( '', url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$', Ratio.as_view(), name='rawcompare'), url(r'/drug/(?P<bnf_code>[0-9A-Z]+)/percap.zip$', Drug.as_view(), name='rawdrug'), )
// ... existing code ... url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$', Ratio.as_view(), name='rawcompare'), url(r'/drug/(?P<bnf_code>[0-9A-Z]+)/percap.zip$', Drug.as_view(), name='rawdrug'), ) // ... rest of the code ...
21d9b2f89a7eb9a6801a48c2586cc360e6be47c3
LTA_to_UVFITS.py
LTA_to_UVFITS.py
def lta_to_uvfits(): lta_files = glob.glob('*.lta*') #flag_files = glob.glob('*.FLAGS*') for i in range(len(lta_files)): lta_file_name = lta_files[i] uvfits_file_name = lta_file_name +'.UVFITS' spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name )
def lta_to_uvfits(): lta_files = glob.glob('*.lta*') #flag_files = glob.glob('*.FLAGS*') for i in range(len(lta_files)): lta_file_name = lta_files[i] uvfits_file_name = lta_file_name +'.UVFITS' spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name ) return lta_files
Return LTA files to use as argument in main thread code
Return LTA files to use as argument in main thread code
Python
mit
NCRA-TIFR/gadpu,NCRA-TIFR/gadpu
python
## Code Before: def lta_to_uvfits(): lta_files = glob.glob('*.lta*') #flag_files = glob.glob('*.FLAGS*') for i in range(len(lta_files)): lta_file_name = lta_files[i] uvfits_file_name = lta_file_name +'.UVFITS' spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name ) ## Instruction: Return LTA files to use as argument in main thread code ## Code After: def lta_to_uvfits(): lta_files = glob.glob('*.lta*') #flag_files = glob.glob('*.FLAGS*') for i in range(len(lta_files)): lta_file_name = lta_files[i] uvfits_file_name = lta_file_name +'.UVFITS' spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name ) return lta_files
... lta_file_name = lta_files[i] uvfits_file_name = lta_file_name +'.UVFITS' spam.convert_lta_to_uvfits( lta_file_name, uvfits_file_name ) return lta_files ...
a81fbdd334dc475554e77bbb71ae00985f2d23c4
eventlog/stats.py
eventlog/stats.py
from datetime import datetime, timedelta from django.contrib.auth.models import User def stats(): return { "used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(), "used_site_last_seven_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=7)).distinct().count() }
from datetime import datetime, timedelta from django.contrib.auth.models import User def used_active(days): used = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).distinct().count() active = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).exclude( date_joined__gt=datetime.now() - timedelta(days=days) ).distinct().count() return used, active def stats(): used_seven, active_seven = used_active(7) used_thirty, active_thirty = used_active(30) return { "used_seven": used_seven, "used_thirty": used_thirty, "active_seven": active_seven, "active_thirty": active_thirty }
Add active_seven and active_thirty users
Add active_seven and active_thirty users
Python
bsd-3-clause
ConsumerAffairs/django-eventlog-ca,rosscdh/pinax-eventlog,KleeTaurus/pinax-eventlog,jawed123/pinax-eventlog,pinax/pinax-eventlog
python
## Code Before: from datetime import datetime, timedelta from django.contrib.auth.models import User def stats(): return { "used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(), "used_site_last_seven_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=7)).distinct().count() } ## Instruction: Add active_seven and active_thirty users ## Code After: from datetime import datetime, timedelta from django.contrib.auth.models import User def used_active(days): used = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).distinct().count() active = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).exclude( date_joined__gt=datetime.now() - timedelta(days=days) ).distinct().count() return used, active def stats(): used_seven, active_seven = used_active(7) used_thirty, active_thirty = used_active(30) return { "used_seven": used_seven, "used_thirty": used_thirty, "active_seven": active_seven, "active_thirty": active_thirty }
... from django.contrib.auth.models import User def used_active(days): used = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).distinct().count() active = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).exclude( date_joined__gt=datetime.now() - timedelta(days=days) ).distinct().count() return used, active def stats(): used_seven, active_seven = used_active(7) used_thirty, active_thirty = used_active(30) return { "used_seven": used_seven, "used_thirty": used_thirty, "active_seven": active_seven, "active_thirty": active_thirty } ...
fd599497011fcb94d8b5c29dc696128eafb9d603
tests/app/test_create_app.py
tests/app/test_create_app.py
from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'}) def test_default_instance_links(): """Validate default instance_links are being populated properly.""" pipeline_config = { "instance_links": { "example2": "https://example2.com", } } combined = {'example1': 'https://example1.com'} combined.update(pipeline_config['instance_links']) spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == combined, "Instance Links are not being retrieved properly"
from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'}) def test_default_instance_links(): """Validate default instance_links are being populated properly.""" pipeline_config = { "instance_links": { "example2": "https://example2.com", } } combined = {'example1': 'https://example1.com'} combined.update(pipeline_config['instance_links']) spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == combined, "Instance Links are not being retrieved properly" @mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'}) def test_duplicate_instance_links(): """Validate behavior when two keys are identical.""" pipeline_config = { "instance_links": {} } duplicate = {'example': 'example2'} spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == duplicate, "Instance links handing duplicates are wrong."
Check handling duplicate key for instance links
test: Check handling duplicate key for instance links
Python
apache-2.0
gogoair/foremast,gogoair/foremast
python
## Code Before: from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'}) def test_default_instance_links(): """Validate default instance_links are being populated properly.""" pipeline_config = { "instance_links": { "example2": "https://example2.com", } } combined = {'example1': 'https://example1.com'} combined.update(pipeline_config['instance_links']) spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == combined, "Instance Links are not being retrieved properly" ## Instruction: test: Check handling duplicate key for instance links ## Code After: from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'}) def test_default_instance_links(): """Validate default instance_links are being populated properly.""" pipeline_config = { "instance_links": { "example2": "https://example2.com", } } combined = {'example1': 'https://example1.com'} combined.update(pipeline_config['instance_links']) spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == combined, "Instance Links are not being retrieved properly" @mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'}) def test_duplicate_instance_links(): """Validate behavior when two keys are identical.""" pipeline_config = { "instance_links": {} } duplicate = {'example': 'example2'} spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == duplicate, "Instance links handing duplicates are wrong."
# ... existing code ... instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == combined, "Instance Links are not being retrieved properly" @mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'}) def test_duplicate_instance_links(): """Validate behavior when two keys are identical.""" pipeline_config = { "instance_links": {} } duplicate = {'example': 'example2'} spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config) instance_links = spinnaker_app.retrieve_instance_links() assert instance_links == duplicate, "Instance links handing duplicates are wrong." # ... rest of the code ...
edd722e38b883236c9f214d5df309110500b3529
test/Sema/attr-noreturn.c
test/Sema/attr-noreturn.c
// RUN: clang-cc -verify -fsyntax-only %s static void (*fp0)(void) __attribute__((noreturn)); static void __attribute__((noreturn)) f0(void) { fatal(); } // expected-warning {{function declared 'noreturn' should not return}} // On K&R int f1() __attribute__((noreturn)); int g0 __attribute__((noreturn)); // expected-warning {{'noreturn' attribute only applies to function types}} int f2() __attribute__((noreturn(1, 2))); // expected-error {{attribute requires 0 argument(s)}} void f3() __attribute__((noreturn)); void f3() { return; // expected-warning {{function 'f3' declared 'noreturn' should not return}} } #pragma clang diagnostic error "-Winvalid-noreturn" void f4() __attribute__((noreturn)); void f4() { return; // expected-error {{function 'f4' declared 'noreturn' should not return}} } // PR4685 extern void f5 (unsigned long) __attribute__ ((__noreturn__)); void f5 (unsigned long size) { }
// RUN: clang -cc1 -verify -fsyntax-only %s static void (*fp0)(void) __attribute__((noreturn)); static void __attribute__((noreturn)) f0(void) { fatal(); } // expected-warning {{function declared 'noreturn' should not return}} // On K&R int f1() __attribute__((noreturn)); int g0 __attribute__((noreturn)); // expected-warning {{'noreturn' attribute only applies to function types}} int f2() __attribute__((noreturn(1, 2))); // expected-error {{attribute requires 0 argument(s)}} void f3() __attribute__((noreturn)); void f3() { return; // expected-warning {{function 'f3' declared 'noreturn' should not return}} } #pragma clang diagnostic error "-Winvalid-noreturn" void f4() __attribute__((noreturn)); void f4() { return; // expected-error {{function 'f4' declared 'noreturn' should not return}} } // PR4685 extern void f5 (unsigned long) __attribute__ ((__noreturn__)); void f5 (unsigned long size) { } // PR2461 __attribute__((noreturn)) void f(__attribute__((noreturn)) void (*x)(void)) { x(); }
Add testcase for recent checkin.
Add testcase for recent checkin. Patch by Chip Davis. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@91436 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
c
## Code Before: // RUN: clang-cc -verify -fsyntax-only %s static void (*fp0)(void) __attribute__((noreturn)); static void __attribute__((noreturn)) f0(void) { fatal(); } // expected-warning {{function declared 'noreturn' should not return}} // On K&R int f1() __attribute__((noreturn)); int g0 __attribute__((noreturn)); // expected-warning {{'noreturn' attribute only applies to function types}} int f2() __attribute__((noreturn(1, 2))); // expected-error {{attribute requires 0 argument(s)}} void f3() __attribute__((noreturn)); void f3() { return; // expected-warning {{function 'f3' declared 'noreturn' should not return}} } #pragma clang diagnostic error "-Winvalid-noreturn" void f4() __attribute__((noreturn)); void f4() { return; // expected-error {{function 'f4' declared 'noreturn' should not return}} } // PR4685 extern void f5 (unsigned long) __attribute__ ((__noreturn__)); void f5 (unsigned long size) { } ## Instruction: Add testcase for recent checkin. Patch by Chip Davis. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@91436 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: clang -cc1 -verify -fsyntax-only %s static void (*fp0)(void) __attribute__((noreturn)); static void __attribute__((noreturn)) f0(void) { fatal(); } // expected-warning {{function declared 'noreturn' should not return}} // On K&R int f1() __attribute__((noreturn)); int g0 __attribute__((noreturn)); // expected-warning {{'noreturn' attribute only applies to function types}} int f2() __attribute__((noreturn(1, 2))); // expected-error {{attribute requires 0 argument(s)}} void f3() __attribute__((noreturn)); void f3() { return; // expected-warning {{function 'f3' declared 'noreturn' should not return}} } #pragma clang diagnostic error "-Winvalid-noreturn" void f4() __attribute__((noreturn)); void f4() { return; // expected-error {{function 'f4' declared 'noreturn' should not return}} } // PR4685 extern void f5 (unsigned long) __attribute__ ((__noreturn__)); void f5 (unsigned long size) { } // PR2461 __attribute__((noreturn)) void f(__attribute__((noreturn)) void (*x)(void)) { x(); }
// ... existing code ... // RUN: clang -cc1 -verify -fsyntax-only %s static void (*fp0)(void) __attribute__((noreturn)); // ... modified code ... { } // PR2461 __attribute__((noreturn)) void f(__attribute__((noreturn)) void (*x)(void)) { x(); } // ... rest of the code ...
1abfdea38e868d68c532961459d2b4cbef5a9b71
src/zeit/website/section.py
src/zeit/website/section.py
import zeit.website.interfaces from zeit.cms.section.interfaces import ISectionMarker import grokcore.component as grok import zeit.cms.checkout.interfaces import zeit.cms.content.interfaces import zope.interface @grok.subscribe( zeit.cms.content.interfaces.ICommonMetadata, zeit.cms.checkout.interfaces.IBeforeCheckinEvent) def provide_website_content(content, event): content = zope.security.proxy.getObject(content) if not content.rebrush_website_content: return for iface in zope.interface.providedBy(content): if issubclass(iface, ISectionMarker): zope.interface.noLongerProvides(content, iface) zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection)
import zeit.website.interfaces from zeit.cms.section.interfaces import ISectionMarker import grokcore.component as grok import zeit.cms.checkout.interfaces import zeit.cms.content.interfaces import zope.interface @grok.subscribe( zeit.cms.content.interfaces.ICommonMetadata, zeit.cms.checkout.interfaces.IBeforeCheckinEvent) def provide_website_content(content, event): content = zope.security.proxy.getObject(content) if not content.rebrush_website_content: zope.interface.noLongerProvides(content, zeit.website.interfaces.IWebsiteSection) return for iface in zope.interface.providedBy(content): if issubclass(iface, ISectionMarker): zope.interface.noLongerProvides(content, iface) zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection)
Remove iface, if rebrush_contetn ist not set
Remove iface, if rebrush_contetn ist not set
Python
bsd-3-clause
ZeitOnline/zeit.website
python
## Code Before: import zeit.website.interfaces from zeit.cms.section.interfaces import ISectionMarker import grokcore.component as grok import zeit.cms.checkout.interfaces import zeit.cms.content.interfaces import zope.interface @grok.subscribe( zeit.cms.content.interfaces.ICommonMetadata, zeit.cms.checkout.interfaces.IBeforeCheckinEvent) def provide_website_content(content, event): content = zope.security.proxy.getObject(content) if not content.rebrush_website_content: return for iface in zope.interface.providedBy(content): if issubclass(iface, ISectionMarker): zope.interface.noLongerProvides(content, iface) zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection) ## Instruction: Remove iface, if rebrush_contetn ist not set ## Code After: import zeit.website.interfaces from zeit.cms.section.interfaces import ISectionMarker import grokcore.component as grok import zeit.cms.checkout.interfaces import zeit.cms.content.interfaces import zope.interface @grok.subscribe( zeit.cms.content.interfaces.ICommonMetadata, zeit.cms.checkout.interfaces.IBeforeCheckinEvent) def provide_website_content(content, event): content = zope.security.proxy.getObject(content) if not content.rebrush_website_content: zope.interface.noLongerProvides(content, zeit.website.interfaces.IWebsiteSection) return for iface in zope.interface.providedBy(content): if issubclass(iface, ISectionMarker): zope.interface.noLongerProvides(content, iface) zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection)
// ... existing code ... def provide_website_content(content, event): content = zope.security.proxy.getObject(content) if not content.rebrush_website_content: zope.interface.noLongerProvides(content, zeit.website.interfaces.IWebsiteSection) return for iface in zope.interface.providedBy(content): if issubclass(iface, ISectionMarker): // ... rest of the code ...
13f6248da3578c67dc472fb38e1abc621fc6f2ae
src/untrusted/nacl/pthread_initialize_minimal.c
src/untrusted/nacl/pthread_initialize_minimal.c
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <unistd.h> #include "native_client/src/untrusted/nacl/nacl_irt.h" #include "native_client/src/untrusted/nacl/nacl_thread.h" #include "native_client/src/untrusted/nacl/tls.h" /* * This initialization happens early in startup with or without libpthread. * It must make it safe for vanilla newlib code to run. */ void __pthread_initialize_minimal(size_t tdb_size) { /* Adapt size for sbrk. */ /* TODO(robertm): this is somewhat arbitrary - re-examine). */ size_t combined_size = (__nacl_tls_combined_size(tdb_size) + 15) & ~15; /* * Use sbrk not malloc here since the library is not initialized yet. */ void *combined_area = sbrk(combined_size); /* * Fill in that memory with its initializer data. */ void *tp = __nacl_tls_initialize_memory(combined_area, tdb_size); /* * Set %gs, r9, or equivalent platform-specific mechanism. Requires * a syscall since certain bitfields of these registers are trusted. */ nacl_tls_init(tp); /* * Initialize newlib's thread-specific pointer. */ __newlib_thread_init(); }
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <unistd.h> #include "native_client/src/untrusted/nacl/nacl_irt.h" #include "native_client/src/untrusted/nacl/nacl_thread.h" #include "native_client/src/untrusted/nacl/tls.h" /* * This initialization happens early in startup with or without libpthread. * It must make it safe for vanilla newlib code to run. */ void __pthread_initialize_minimal(size_t tdb_size) { size_t combined_size = __nacl_tls_combined_size(tdb_size); /* * Use sbrk not malloc here since the library is not initialized yet. */ void *combined_area = sbrk(combined_size); /* * Fill in that memory with its initializer data. */ void *tp = __nacl_tls_initialize_memory(combined_area, tdb_size); /* * Set %gs, r9, or equivalent platform-specific mechanism. Requires * a syscall since certain bitfields of these registers are trusted. */ nacl_tls_init(tp); /* * Initialize newlib's thread-specific pointer. */ __newlib_thread_init(); }
Remove unnecessary rounding when allocating initial thread block
Cleanup: Remove unnecessary rounding when allocating initial thread block The other calls to __nacl_tls_combined_size() don't do this. __nacl_tls_combined_size() should be doing any necessary rounding itself. BUG=none TEST=trybots Review URL: https://codereview.chromium.org/18555008 git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@11698 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
C
bsd-3-clause
Lind-Project/native_client,Lind-Project/native_client,Lind-Project/native_client,Lind-Project/native_client,Lind-Project/native_client,Lind-Project/native_client
c
## Code Before: /* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <unistd.h> #include "native_client/src/untrusted/nacl/nacl_irt.h" #include "native_client/src/untrusted/nacl/nacl_thread.h" #include "native_client/src/untrusted/nacl/tls.h" /* * This initialization happens early in startup with or without libpthread. * It must make it safe for vanilla newlib code to run. */ void __pthread_initialize_minimal(size_t tdb_size) { /* Adapt size for sbrk. */ /* TODO(robertm): this is somewhat arbitrary - re-examine). */ size_t combined_size = (__nacl_tls_combined_size(tdb_size) + 15) & ~15; /* * Use sbrk not malloc here since the library is not initialized yet. */ void *combined_area = sbrk(combined_size); /* * Fill in that memory with its initializer data. */ void *tp = __nacl_tls_initialize_memory(combined_area, tdb_size); /* * Set %gs, r9, or equivalent platform-specific mechanism. Requires * a syscall since certain bitfields of these registers are trusted. */ nacl_tls_init(tp); /* * Initialize newlib's thread-specific pointer. */ __newlib_thread_init(); } ## Instruction: Cleanup: Remove unnecessary rounding when allocating initial thread block The other calls to __nacl_tls_combined_size() don't do this. __nacl_tls_combined_size() should be doing any necessary rounding itself. BUG=none TEST=trybots Review URL: https://codereview.chromium.org/18555008 git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@11698 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2 ## Code After: /* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <unistd.h> #include "native_client/src/untrusted/nacl/nacl_irt.h" #include "native_client/src/untrusted/nacl/nacl_thread.h" #include "native_client/src/untrusted/nacl/tls.h" /* * This initialization happens early in startup with or without libpthread. * It must make it safe for vanilla newlib code to run. */ void __pthread_initialize_minimal(size_t tdb_size) { size_t combined_size = __nacl_tls_combined_size(tdb_size); /* * Use sbrk not malloc here since the library is not initialized yet. */ void *combined_area = sbrk(combined_size); /* * Fill in that memory with its initializer data. */ void *tp = __nacl_tls_initialize_memory(combined_area, tdb_size); /* * Set %gs, r9, or equivalent platform-specific mechanism. Requires * a syscall since certain bitfields of these registers are trusted. */ nacl_tls_init(tp); /* * Initialize newlib's thread-specific pointer. */ __newlib_thread_init(); }
... * It must make it safe for vanilla newlib code to run. */ void __pthread_initialize_minimal(size_t tdb_size) { size_t combined_size = __nacl_tls_combined_size(tdb_size); /* * Use sbrk not malloc here since the library is not initialized yet. ...
edd5adc9be2a700421bd8e98af825322796b8714
dns/models.py
dns/models.py
from google.appengine.ext import db TOP_LEVEL_DOMAINS = 'com net org biz info'.split() class Lookup(db.Model): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Updates since 2010-01-01 use negative numbers for 60 bit hashes of the SOA server name, see tools/update_dns.py. """ backwards = db.StringProperty(required=True) # For suffix matching. timestamp = db.DateTimeProperty(required=True) # Created or updated. com = db.IntegerProperty(indexed=False) net = db.IntegerProperty(indexed=False) org = db.IntegerProperty(indexed=False) biz = db.IntegerProperty(indexed=False) info = db.IntegerProperty(indexed=False)
from google.appengine.ext import db TOP_LEVEL_DOMAINS = """ com net org biz info ag am at be by ch ck de es eu fm in io is it la li ly me mobi ms name ru se sh sy tel th to travel tv us """.split() # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN. class UpgradeStringProperty(db.IntegerProperty): def validate(self, value): return unicode(value) if value else u'' class Lookup(db.Expando): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Some updates on 2010-01-01 use negative numbers for 60 bit hashes of the SOA server name. Since 2010-01-02, this model inherits from Expando to flexibly add more top level domains. Each property stores the authority name server as string backwards, e.g. com.1and1.ns1 for better sorting. """ backwards = db.StringProperty(required=True) # For suffix matching. timestamp = db.DateTimeProperty(required=True) # Created or updated. com = UpgradeStringProperty() net = UpgradeStringProperty() org = UpgradeStringProperty() biz = UpgradeStringProperty() info = UpgradeStringProperty()
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Python
mit
jcrocholl/nxdom,jcrocholl/nxdom
python
## Code Before: from google.appengine.ext import db TOP_LEVEL_DOMAINS = 'com net org biz info'.split() class Lookup(db.Model): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Updates since 2010-01-01 use negative numbers for 60 bit hashes of the SOA server name, see tools/update_dns.py. """ backwards = db.StringProperty(required=True) # For suffix matching. timestamp = db.DateTimeProperty(required=True) # Created or updated. com = db.IntegerProperty(indexed=False) net = db.IntegerProperty(indexed=False) org = db.IntegerProperty(indexed=False) biz = db.IntegerProperty(indexed=False) info = db.IntegerProperty(indexed=False) ## Instruction: Upgrade Lookup model to Expando and DNS result properties from integer to string. ## Code After: from google.appengine.ext import db TOP_LEVEL_DOMAINS = """ com net org biz info ag am at be by ch ck de es eu fm in io is it la li ly me mobi ms name ru se sh sy tel th to travel tv us """.split() # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN. class UpgradeStringProperty(db.IntegerProperty): def validate(self, value): return unicode(value) if value else u'' class Lookup(db.Expando): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Some updates on 2010-01-01 use negative numbers for 60 bit hashes of the SOA server name. Since 2010-01-02, this model inherits from Expando to flexibly add more top level domains. Each property stores the authority name server as string backwards, e.g. com.1and1.ns1 for better sorting. """ backwards = db.StringProperty(required=True) # For suffix matching. timestamp = db.DateTimeProperty(required=True) # Created or updated. com = UpgradeStringProperty() net = UpgradeStringProperty() org = UpgradeStringProperty() biz = UpgradeStringProperty() info = UpgradeStringProperty()
... from google.appengine.ext import db TOP_LEVEL_DOMAINS = """ com net org biz info ag am at be by ch ck de es eu fm in io is it la li ly me mobi ms name ru se sh sy tel th to travel tv us """.split() # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN. class UpgradeStringProperty(db.IntegerProperty): def validate(self, value): return unicode(value) if value else u'' class Lookup(db.Expando): """ The datastore key name is the domain name, without top level. ... IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Some updates on 2010-01-01 use negative numbers for 60 bit hashes of the SOA server name. Since 2010-01-02, this model inherits from Expando to flexibly add more top level domains. Each property stores the authority name server as string backwards, e.g. com.1and1.ns1 for better sorting. """ backwards = db.StringProperty(required=True) # For suffix matching. timestamp = db.DateTimeProperty(required=True) # Created or updated. com = UpgradeStringProperty() net = UpgradeStringProperty() org = UpgradeStringProperty() biz = UpgradeStringProperty() info = UpgradeStringProperty() ...
595555433d7495ab54cdeb26d37cb2bc6c58f830
plyades/core.py
plyades/core.py
import datetime import numpy as np class Epoch(datetime.datetime): def get_jd(self, epoch=2000): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0) if epoch == 2000: return jd - 2451544.5 elif epoch == 1950: return jd - 2433282.5 elif epoch == "mjd": return jd - 2400000.5 elif epoch == 0: return jd class State: def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)): self.r = np.array([x, y, z]) self.v = np.array([vx, vy, vz]) self.t = epoch
import datetime import numpy as np class Epoch(datetime.datetime): @property def jd(self): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0) return jd @property def jd2000(self): return self.jd - 2451544.5 @property def jd1950(self): return self.jd - 2433282.5 @property def mjd(self): return self.jd - 2400000.5 class State: def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)): self.r = np.array([x, y, z]) self.v = np.array([vx, vy, vz]) self.t = epoch
Change julian date to be a property.
Change julian date to be a property.
Python
mit
helgee/plyades
python
## Code Before: import datetime import numpy as np class Epoch(datetime.datetime): def get_jd(self, epoch=2000): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0) if epoch == 2000: return jd - 2451544.5 elif epoch == 1950: return jd - 2433282.5 elif epoch == "mjd": return jd - 2400000.5 elif epoch == 0: return jd class State: def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)): self.r = np.array([x, y, z]) self.v = np.array([vx, vy, vz]) self.t = epoch ## Instruction: Change julian date to be a property. ## Code After: import datetime import numpy as np class Epoch(datetime.datetime): @property def jd(self): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0) return jd @property def jd2000(self): return self.jd - 2451544.5 @property def jd1950(self): return self.jd - 2433282.5 @property def mjd(self): return self.jd - 2400000.5 class State: def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)): self.r = np.array([x, y, z]) self.v = np.array([vx, vy, vz]) self.t = epoch
... import numpy as np class Epoch(datetime.datetime): @property def jd(self): jd = (367.0 * self.year - np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 ) + np.floor( 275 * self.month / 9.0 ) + self.day + 1721013.5 + ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0) return jd @property def jd2000(self): return self.jd - 2451544.5 @property def jd1950(self): return self.jd - 2433282.5 @property def mjd(self): return self.jd - 2400000.5 class State: def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)): ...
25bf543b633f7007ddffb53b0a4493a4afc8d9c3
basearch-webapp/src/main/java/basearch/integration/ThymeleafConfiguration.java
basearch-webapp/src/main/java/basearch/integration/ThymeleafConfiguration.java
package basearch.integration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ThymeleafConfiguration { @Bean public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/thymeleaf"); resolver.setTemplateMode("HTML5"); return resolver; } @Bean public SpringSecurityDialect springSecurityDialect() { return new SpringSecurityDialect(); } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(springSecurityDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); viewResolver.setViewNames(new String[] {"*.html"}); return viewResolver; } }
package basearch.integration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ThymeleafConfiguration { @Bean public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/thymeleaf"); resolver.setTemplateMode("HTML5"); resolver.setCacheable(false); return resolver; } @Bean public SpringSecurityDialect springSecurityDialect() { return new SpringSecurityDialect(); } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(springSecurityDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); viewResolver.setViewNames(new String[] {"*.html"}); return viewResolver; } }
Make thymeleaf templates not cacheable, to ease jetty redeploys
Make thymeleaf templates not cacheable, to ease jetty redeploys
Java
mit
hectorlf/basearch,hectorlf/basearch-current,hectorlf/basearch,hectorlf/basearch-current
java
## Code Before: package basearch.integration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ThymeleafConfiguration { @Bean public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/thymeleaf"); resolver.setTemplateMode("HTML5"); return resolver; } @Bean public SpringSecurityDialect springSecurityDialect() { return new SpringSecurityDialect(); } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(springSecurityDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); viewResolver.setViewNames(new String[] {"*.html"}); return viewResolver; } } ## Instruction: Make thymeleaf templates not cacheable, to ease jetty redeploys ## Code After: package basearch.integration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ThymeleafConfiguration { @Bean public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/thymeleaf"); resolver.setTemplateMode("HTML5"); resolver.setCacheable(false); return resolver; } @Bean public SpringSecurityDialect springSecurityDialect() { return new SpringSecurityDialect(); } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(springSecurityDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); viewResolver.setViewNames(new String[] {"*.html"}); return viewResolver; } }
// ... existing code ... ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); resolver.setPrefix("/WEB-INF/thymeleaf"); resolver.setTemplateMode("HTML5"); resolver.setCacheable(false); return resolver; } // ... rest of the code ...
dff7a6e4cfa46c26483c4dd1f19faf1943b8b6f9
src/main/java/org/cyclops/integrateddynamics/capability/cable/CableFakeableDefault.java
src/main/java/org/cyclops/integrateddynamics/capability/cable/CableFakeableDefault.java
package org.cyclops.integrateddynamics.capability.cable; import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable; /** * Default implementation of {@link ICableFakeable}. * @author rubensworks */ public abstract class CableFakeableDefault implements ICableFakeable { private boolean real = true; @Override public boolean isRealCable() { return real; } @Override public void setRealCable(boolean real) { this.real = real; sendUpdate(); } protected abstract void sendUpdate(); }
package org.cyclops.integrateddynamics.capability.cable; import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable; /** * Default implementation of {@link ICableFakeable}. * @author rubensworks */ public abstract class CableFakeableDefault implements ICableFakeable { private boolean real = true; @Override public boolean isRealCable() { return real; } @Override public void setRealCable(boolean real) { boolean oldReal = this.real; this.real = real; if (oldReal != this.real) { sendUpdate(); } } protected abstract void sendUpdate(); }
Fix display panels causing unnecessary chunk rerenders
Fix display panels causing unnecessary chunk rerenders
Java
mit
CyclopsMC/IntegratedDynamics
java
## Code Before: package org.cyclops.integrateddynamics.capability.cable; import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable; /** * Default implementation of {@link ICableFakeable}. * @author rubensworks */ public abstract class CableFakeableDefault implements ICableFakeable { private boolean real = true; @Override public boolean isRealCable() { return real; } @Override public void setRealCable(boolean real) { this.real = real; sendUpdate(); } protected abstract void sendUpdate(); } ## Instruction: Fix display panels causing unnecessary chunk rerenders ## Code After: package org.cyclops.integrateddynamics.capability.cable; import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable; /** * Default implementation of {@link ICableFakeable}. * @author rubensworks */ public abstract class CableFakeableDefault implements ICableFakeable { private boolean real = true; @Override public boolean isRealCable() { return real; } @Override public void setRealCable(boolean real) { boolean oldReal = this.real; this.real = real; if (oldReal != this.real) { sendUpdate(); } } protected abstract void sendUpdate(); }
# ... existing code ... @Override public void setRealCable(boolean real) { boolean oldReal = this.real; this.real = real; if (oldReal != this.real) { sendUpdate(); } } protected abstract void sendUpdate(); # ... rest of the code ...
8cd68fb795295b3a26d30f48f5529389b5ebd4b0
readcsv.py
readcsv.py
""" Read the CSV NOTE: Manually edited csv file twice to match FIELD NAME format """ import csv datareader = csv.DictReader(open("C:/Users/pgao/Documents/DATA_FIELD_DESCRIPTORS.csv")) data = [] entry = {} current_table = "" for line in datareader: new_table_number = line['TABLE NUMBER'] if new_table_number != current_table: entry = {} current_table = new_table_number entry['Matrix Number'] = line['TABLE NUMBER'] entry['File Name'] = line['SEGMENT'] next_line = datareader.next() entry['Universe'] = (next_line['FIELD NAME'][9:].lstrip()) try: entry['Name'] = line['FIELD NAME'][:line['FIELD NAME'].index('[')-1] entry['Cell Count'] = line['FIELD NAME'][line['FIELD NAME'].index('[')+1] except ValueError: print line data.append(entry) #Write the tsv file datawriter = csv.DictWriter(open("C:/Users/pgao/Documents/SF1.tsv", "w"), ['File Name', 'Matrix Number', 'Cell Count', 'Name', 'Universe'], delimiter = '\t', lineterminator='\n') datawriter.writeheader() datawriter.writerows(data)
""" Read the CSV NOTE: Manually edited csv file twice to match FIELD NAME format """ import csv datareader = csv.DictReader(open("sf1_data_field_descriptors_2010.csv")) data = [] entry = None current_table = "" for line in datareader: new_table_number = line['TABLE NUMBER'] if new_table_number != current_table: # save the old one if entry != None: data.append(entry) entry = {} current_table = new_table_number entry['Matrix Number'] = line['TABLE NUMBER'] entry['File Name'] = line['SEGMENT'] next_line = datareader.next() entry['Universe'] = (next_line['FIELD NAME'][9:].lstrip()) entry['Name'] = line['FIELD NAME'][:line['FIELD NAME'].index('[')-1] entry['Cell Count'] = 0 # Increment the cell count iff there's actually data, rather than this being a descriptive row if len(line['FIELD CODE']) > 0: entry['Cell Count'] += 1 # Write the tsv file datawriter = csv.DictWriter(open("sf1_2010.tsv", "w"), ['File Name', 'Matrix Number', 'Cell Count', 'Name', 'Universe'], dialect = 'excel-tab' ) datawriter.writeheader() datawriter.writerows(data)
Fix bug with matrices with >= 10 columns
Fix bug with matrices with >= 10 columns
Python
isc
ikding/census-tools,ikding/census-tools
python
## Code Before: """ Read the CSV NOTE: Manually edited csv file twice to match FIELD NAME format """ import csv datareader = csv.DictReader(open("C:/Users/pgao/Documents/DATA_FIELD_DESCRIPTORS.csv")) data = [] entry = {} current_table = "" for line in datareader: new_table_number = line['TABLE NUMBER'] if new_table_number != current_table: entry = {} current_table = new_table_number entry['Matrix Number'] = line['TABLE NUMBER'] entry['File Name'] = line['SEGMENT'] next_line = datareader.next() entry['Universe'] = (next_line['FIELD NAME'][9:].lstrip()) try: entry['Name'] = line['FIELD NAME'][:line['FIELD NAME'].index('[')-1] entry['Cell Count'] = line['FIELD NAME'][line['FIELD NAME'].index('[')+1] except ValueError: print line data.append(entry) #Write the tsv file datawriter = csv.DictWriter(open("C:/Users/pgao/Documents/SF1.tsv", "w"), ['File Name', 'Matrix Number', 'Cell Count', 'Name', 'Universe'], delimiter = '\t', lineterminator='\n') datawriter.writeheader() datawriter.writerows(data) ## Instruction: Fix bug with matrices with >= 10 columns ## Code After: """ Read the CSV NOTE: Manually edited csv file twice to match FIELD NAME format """ import csv datareader = csv.DictReader(open("sf1_data_field_descriptors_2010.csv")) data = [] entry = None current_table = "" for line in datareader: new_table_number = line['TABLE NUMBER'] if new_table_number != current_table: # save the old one if entry != None: data.append(entry) entry = {} current_table = new_table_number entry['Matrix Number'] = line['TABLE NUMBER'] entry['File Name'] = line['SEGMENT'] next_line = datareader.next() entry['Universe'] = (next_line['FIELD NAME'][9:].lstrip()) entry['Name'] = line['FIELD NAME'][:line['FIELD NAME'].index('[')-1] entry['Cell Count'] = 0 # Increment the cell count iff there's actually data, rather than this being a descriptive row if len(line['FIELD CODE']) > 0: entry['Cell Count'] += 1 # Write the tsv file datawriter = csv.DictWriter(open("sf1_2010.tsv", "w"), ['File Name', 'Matrix Number', 'Cell Count', 'Name', 'Universe'], dialect = 'excel-tab' ) datawriter.writeheader() datawriter.writerows(data)
// ... existing code ... """ import csv datareader = csv.DictReader(open("sf1_data_field_descriptors_2010.csv")) data = [] entry = None current_table = "" for line in datareader: new_table_number = line['TABLE NUMBER'] if new_table_number != current_table: # save the old one if entry != None: data.append(entry) entry = {} current_table = new_table_number entry['Matrix Number'] = line['TABLE NUMBER'] // ... modified code ... entry['File Name'] = line['SEGMENT'] next_line = datareader.next() entry['Universe'] = (next_line['FIELD NAME'][9:].lstrip()) entry['Name'] = line['FIELD NAME'][:line['FIELD NAME'].index('[')-1] entry['Cell Count'] = 0 # Increment the cell count iff there's actually data, rather than this being a descriptive row if len(line['FIELD CODE']) > 0: entry['Cell Count'] += 1 # Write the tsv file datawriter = csv.DictWriter(open("sf1_2010.tsv", "w"), ['File Name', 'Matrix Number', 'Cell Count', 'Name', 'Universe'], dialect = 'excel-tab' ) datawriter.writeheader() datawriter.writerows(data) // ... rest of the code ...
e67c5af0ff71301c861aa9268be7d5345219624f
src/main/java/module-info.java
src/main/java/module-info.java
/** * JFreeChart module. */ module org.jfree.chart { requires java.desktop; exports org.jfree.chart; exports org.jfree.chart.annotations; exports org.jfree.chart.axis; exports org.jfree.chart.date; exports org.jfree.chart.editor; exports org.jfree.chart.entity; exports org.jfree.chart.event; exports org.jfree.chart.imagemap; exports org.jfree.chart.labels; exports org.jfree.chart.needle; exports org.jfree.chart.panel; exports org.jfree.chart.plot; exports org.jfree.chart.plot.dial; exports org.jfree.chart.renderer; exports org.jfree.chart.renderer.category; exports org.jfree.chart.renderer.xy; exports org.jfree.chart.text; exports org.jfree.chart.title; exports org.jfree.chart.ui; exports org.jfree.chart.urls; exports org.jfree.chart.util; exports org.jfree.data; exports org.jfree.data.category; exports org.jfree.data.function; exports org.jfree.data.gantt; exports org.jfree.data.general; exports org.jfree.data.io; exports org.jfree.data.json; exports org.jfree.data.statistics; exports org.jfree.data.time; exports org.jfree.data.time.ohlc; exports org.jfree.data.xml; exports org.jfree.data.xy; }
/** * JFreeChart module. */ module org.jfree.chart { requires java.desktop; exports org.jfree.chart; exports org.jfree.chart.annotations; exports org.jfree.chart.axis; exports org.jfree.chart.date; exports org.jfree.chart.editor; exports org.jfree.chart.entity; exports org.jfree.chart.event; exports org.jfree.chart.imagemap; exports org.jfree.chart.labels; exports org.jfree.chart.needle; exports org.jfree.chart.panel; exports org.jfree.chart.plot; exports org.jfree.chart.plot.dial; exports org.jfree.chart.renderer; exports org.jfree.chart.renderer.category; exports org.jfree.chart.renderer.xy; exports org.jfree.chart.swing; exports org.jfree.chart.text; exports org.jfree.chart.title; exports org.jfree.chart.ui; exports org.jfree.chart.urls; exports org.jfree.chart.util; exports org.jfree.data; exports org.jfree.data.category; exports org.jfree.data.function; exports org.jfree.data.gantt; exports org.jfree.data.general; exports org.jfree.data.io; exports org.jfree.data.json; exports org.jfree.data.statistics; exports org.jfree.data.time; exports org.jfree.data.time.ohlc; exports org.jfree.data.xml; exports org.jfree.data.xy; }
Add new swing package to exports.
Add new swing package to exports.
Java
lgpl-2.1
jfree/jfreechart,jfree/jfreechart,jfree/jfreechart,jfree/jfreechart
java
## Code Before: /** * JFreeChart module. */ module org.jfree.chart { requires java.desktop; exports org.jfree.chart; exports org.jfree.chart.annotations; exports org.jfree.chart.axis; exports org.jfree.chart.date; exports org.jfree.chart.editor; exports org.jfree.chart.entity; exports org.jfree.chart.event; exports org.jfree.chart.imagemap; exports org.jfree.chart.labels; exports org.jfree.chart.needle; exports org.jfree.chart.panel; exports org.jfree.chart.plot; exports org.jfree.chart.plot.dial; exports org.jfree.chart.renderer; exports org.jfree.chart.renderer.category; exports org.jfree.chart.renderer.xy; exports org.jfree.chart.text; exports org.jfree.chart.title; exports org.jfree.chart.ui; exports org.jfree.chart.urls; exports org.jfree.chart.util; exports org.jfree.data; exports org.jfree.data.category; exports org.jfree.data.function; exports org.jfree.data.gantt; exports org.jfree.data.general; exports org.jfree.data.io; exports org.jfree.data.json; exports org.jfree.data.statistics; exports org.jfree.data.time; exports org.jfree.data.time.ohlc; exports org.jfree.data.xml; exports org.jfree.data.xy; } ## Instruction: Add new swing package to exports. ## Code After: /** * JFreeChart module. */ module org.jfree.chart { requires java.desktop; exports org.jfree.chart; exports org.jfree.chart.annotations; exports org.jfree.chart.axis; exports org.jfree.chart.date; exports org.jfree.chart.editor; exports org.jfree.chart.entity; exports org.jfree.chart.event; exports org.jfree.chart.imagemap; exports org.jfree.chart.labels; exports org.jfree.chart.needle; exports org.jfree.chart.panel; exports org.jfree.chart.plot; exports org.jfree.chart.plot.dial; exports org.jfree.chart.renderer; exports org.jfree.chart.renderer.category; exports org.jfree.chart.renderer.xy; exports org.jfree.chart.swing; exports org.jfree.chart.text; exports org.jfree.chart.title; exports org.jfree.chart.ui; exports org.jfree.chart.urls; exports org.jfree.chart.util; exports org.jfree.data; exports org.jfree.data.category; exports org.jfree.data.function; exports org.jfree.data.gantt; exports org.jfree.data.general; exports org.jfree.data.io; exports org.jfree.data.json; exports org.jfree.data.statistics; exports org.jfree.data.time; exports org.jfree.data.time.ohlc; exports org.jfree.data.xml; exports org.jfree.data.xy; }
// ... existing code ... exports org.jfree.chart.renderer; exports org.jfree.chart.renderer.category; exports org.jfree.chart.renderer.xy; exports org.jfree.chart.swing; exports org.jfree.chart.text; exports org.jfree.chart.title; exports org.jfree.chart.ui; // ... rest of the code ...
739ae88d817cb86723b126360aaf3dd6df3045c0
tests/test_log.py
tests/test_log.py
import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "..." in message["list"] def test_trim_values_nested(): message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}}) assert "..." in message["obj"]["obj2"]["string2"] def test_trim_values_batch(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"] def test_trim_message(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"]
import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values, _trim_message def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "..." in message["list"] def test_trim_values_nested(): message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}}) assert "..." in message["obj"]["obj2"]["string2"] def test_trim_values_batch(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"] def test_trim_message(): message = _trim_message("foo" * 100) assert "..." in message
Add coverage to some of log.py
Add coverage to some of log.py
Python
mit
bcb/jsonrpcclient
python
## Code Before: import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "..." in message["list"] def test_trim_values_nested(): message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}}) assert "..." in message["obj"]["obj2"]["string2"] def test_trim_values_batch(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"] def test_trim_message(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"] ## Instruction: Add coverage to some of log.py ## Code After: import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values, _trim_message def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "..." in message["list"] def test_trim_values_nested(): message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}}) assert "..." in message["obj"]["obj2"]["string2"] def test_trim_values_batch(): message = _trim_values([{"list": [0] * 100}]) assert "..." in message[0]["list"] def test_trim_message(): message = _trim_message("foo" * 100) assert "..." in message
... import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values, _trim_message def test_trim_string(): ... def test_trim_message(): message = _trim_message("foo" * 100) assert "..." in message ...
51ac844e88a6cd30af2a9f2c0367eaada1e9c8dc
nassau/src/main/java/org/jvirtanen/nassau/MessageListener.java
nassau/src/main/java/org/jvirtanen/nassau/MessageListener.java
package org.jvirtanen.nassau; import java.io.IOException; import java.nio.ByteBuffer; /** * <code>MessageListener</code> is the interface for inbound messages. */ public interface MessageListener { /** * Receive a message. The message is contained in the buffer between the * current position and the limit. * * @param buffer a buffer * @throws IOException if an I/O error occurs */ void message(ByteBuffer buffer) throws IOException; }
package org.jvirtanen.nassau; import java.io.IOException; import java.nio.ByteBuffer; /** * The interface for inbound messages. */ public interface MessageListener { /** * Receive a message. The message is contained in the buffer between the * current position and the limit. * * @param buffer a buffer * @throws IOException if an I/O error occurs */ void message(ByteBuffer buffer) throws IOException; }
Tweak documentation for message listener
Tweak documentation for message listener
Java
apache-2.0
pmcs/nassau,pmcs/nassau,paritytrading/nassau,paritytrading/nassau
java
## Code Before: package org.jvirtanen.nassau; import java.io.IOException; import java.nio.ByteBuffer; /** * <code>MessageListener</code> is the interface for inbound messages. */ public interface MessageListener { /** * Receive a message. The message is contained in the buffer between the * current position and the limit. * * @param buffer a buffer * @throws IOException if an I/O error occurs */ void message(ByteBuffer buffer) throws IOException; } ## Instruction: Tweak documentation for message listener ## Code After: package org.jvirtanen.nassau; import java.io.IOException; import java.nio.ByteBuffer; /** * The interface for inbound messages. */ public interface MessageListener { /** * Receive a message. The message is contained in the buffer between the * current position and the limit. * * @param buffer a buffer * @throws IOException if an I/O error occurs */ void message(ByteBuffer buffer) throws IOException; }
# ... existing code ... import java.nio.ByteBuffer; /** * The interface for inbound messages. */ public interface MessageListener { # ... rest of the code ...
bbb12dd60222ae617e5ed70d37c0ea3d350b9f3a
satsound/views.py
satsound/views.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
Python
mit
saanobhaai/apman,saanobhaai/apman
python
## Code Before: from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form}) ## Instruction: Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite ## Code After: from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
# ... existing code ... @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] # ... rest of the code ...
76c9b7e8e8e6836ad73c81610a82ee2098cea026
tests/main/views/test_status.py
tests/main/views/test_status.py
from tests.bases import BaseApplicationTest class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200
from tests.bases import BaseApplicationTest from sqlalchemy.exc import SQLAlchemyError import mock class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200 @mock.patch('app.status.utils.get_db_version') def test_catches_db_error_and_return_500(self, get_db_version): get_db_version.side_effect = SQLAlchemyError() status_response = self.client.get('/_status') assert status_response.status_code == 500
Test coverage for SQLAlchemyError handling in status view
Test coverage for SQLAlchemyError handling in status view
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
python
## Code Before: from tests.bases import BaseApplicationTest class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200 ## Instruction: Test coverage for SQLAlchemyError handling in status view ## Code After: from tests.bases import BaseApplicationTest from sqlalchemy.exc import SQLAlchemyError import mock class TestStatus(BaseApplicationTest): def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200 @mock.patch('app.status.utils.get_db_version') def test_catches_db_error_and_return_500(self, get_db_version): get_db_version.side_effect = SQLAlchemyError() status_response = self.client.get('/_status') assert status_response.status_code == 500
# ... existing code ... from tests.bases import BaseApplicationTest from sqlalchemy.exc import SQLAlchemyError import mock class TestStatus(BaseApplicationTest): # ... modified code ... def test_should_return_200_from_elb_status_check(self): status_response = self.client.get('/_status?ignore-dependencies') assert status_response.status_code == 200 @mock.patch('app.status.utils.get_db_version') def test_catches_db_error_and_return_500(self, get_db_version): get_db_version.side_effect = SQLAlchemyError() status_response = self.client.get('/_status') assert status_response.status_code == 500 # ... rest of the code ...
d108f090f198cba47083225c0de46e77b22ab5cc
serfclient/__init__.py
serfclient/__init__.py
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
Move module level import to top of file (PEP8)
Move module level import to top of file (PEP8) Error: E402 module level import not at top of file
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
python
## Code Before: from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient ## Instruction: Move module level import to top of file (PEP8) Error: E402 module level import not at top of file ## Code After: from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
// ... existing code ... from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version // ... rest of the code ...
a968cbcd4b5a2aec5e1253221598eb53f9f0c2e9
osgtest/tests/test_10_condor.py
osgtest/tests/test_10_condor.py
import os import osgtest.library.core as core import unittest class TestStartCondor(unittest.TestCase): def test_01_start_condor(self): core.config['condor.lockfile'] = '/var/lock/subsys/condor_master' core.state['condor.started-service'] = False core.state['condor.running-service'] = False if core.missing_rpm('condor'): return if os.path.exists(core.config['condor.lockfile']): core.state['condor.running-service'] = True core.skip('apparently running') return command = ('service', 'condor', 'start') stdout, _, fail = core.check_system(command, 'Start Condor') self.assert_(stdout.find('error') == -1, fail) self.assert_(os.path.exists(core.config['condor.lockfile']), 'Condor run lock file missing') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
import os from osgtest.library import core, osgunittest import unittest class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.config['condor.lockfile'] = '/var/lock/subsys/condor_master' core.state['condor.started-service'] = False core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') if os.path.exists(core.config['condor.lockfile']): core.state['condor.running-service'] = True self.skip_ok('already running') command = ('service', 'condor', 'start') stdout, _, fail = core.check_system(command, 'Start Condor') self.assert_(stdout.find('error') == -1, fail) self.assert_(os.path.exists(core.config['condor.lockfile']), 'Condor run lock file missing') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
Update 10_condor to use OkSkip functionality
Update 10_condor to use OkSkip functionality git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16522 4e558342-562e-0410-864c-e07659590f8c
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
python
## Code Before: import os import osgtest.library.core as core import unittest class TestStartCondor(unittest.TestCase): def test_01_start_condor(self): core.config['condor.lockfile'] = '/var/lock/subsys/condor_master' core.state['condor.started-service'] = False core.state['condor.running-service'] = False if core.missing_rpm('condor'): return if os.path.exists(core.config['condor.lockfile']): core.state['condor.running-service'] = True core.skip('apparently running') return command = ('service', 'condor', 'start') stdout, _, fail = core.check_system(command, 'Start Condor') self.assert_(stdout.find('error') == -1, fail) self.assert_(os.path.exists(core.config['condor.lockfile']), 'Condor run lock file missing') core.state['condor.started-service'] = True core.state['condor.running-service'] = True ## Instruction: Update 10_condor to use OkSkip functionality git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16522 4e558342-562e-0410-864c-e07659590f8c ## Code After: import os from osgtest.library import core, osgunittest import unittest class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.config['condor.lockfile'] = '/var/lock/subsys/condor_master' core.state['condor.started-service'] = False core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') if os.path.exists(core.config['condor.lockfile']): core.state['condor.running-service'] = True self.skip_ok('already running') command = ('service', 'condor', 'start') stdout, _, fail = core.check_system(command, 'Start Condor') self.assert_(stdout.find('error') == -1, fail) self.assert_(os.path.exists(core.config['condor.lockfile']), 'Condor run lock file missing') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
# ... existing code ... import os from osgtest.library import core, osgunittest import unittest class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.config['condor.lockfile'] = '/var/lock/subsys/condor_master' # ... modified code ... core.state['condor.started-service'] = False core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') if os.path.exists(core.config['condor.lockfile']): core.state['condor.running-service'] = True self.skip_ok('already running') command = ('service', 'condor', 'start') stdout, _, fail = core.check_system(command, 'Start Condor') self.assert_(stdout.find('error') == -1, fail) # ... rest of the code ...
46892da903a24432a41587b2cd6c4c274f970687
src/main/java/JSONServiceController.java
src/main/java/JSONServiceController.java
/** * Created by Siclait on 18/7/16. */ import JSONTools.ResponseError; import static JSONTools.JSONUtil.json; import static spark.Spark.after; import static spark.Spark.get; public class JSONServiceController { public JSONServiceController() { // Fetch All Urls get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json()); // Fetch Specific Short Url get("/json/original/:short", (req, res) -> { String shortURL = req.params(":short"); String url = DatabaseManager.FetchOriginalURL(shortURL); if(url != null) return url; res.status(400); return new ResponseError("No url with id %s found", shortURL); }, json()); after("/json/*",(req, res) -> {res.type("application/json");}); } }
/** * Created by Siclait on 18/7/16. */ import Entity.User; import JSONTools.ResponseError; import org.h2.engine.Database; import static JSONTools.JSONUtil.json; import static spark.Spark.after; import static spark.Spark.get; public class JSONServiceController { public JSONServiceController() { // Fetch All Urls get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json()); // Fetch Specific Short Url get("/json/original/:short", (req, res) -> { String shortURL = req.params(":short"); String url = DatabaseManager.FetchOriginalURL(shortURL); if(url != null) return url; res.status(400); return new ResponseError("No url with id %s found", shortURL); }, json()); // Fetch All Users get("/json/allusers", (req, res) -> DatabaseManager.FetchAllUsers(), json()); // Fetch Specific User get("/json/user/:username", (req, res) -> { String username = req.params(":username"); User user = DatabaseManager.FetchUser(username); if(user != null) return user; res.status(400); return new ResponseError("No user with id %s found", username); }, json()); after("/json/*",(req, res) -> {res.type("application/json");}); } }
Add find User json function
Add find User json function
Java
mit
Eduardoveras94/url-Shortener-spark,Eduardoveras94/url-Shortener-spark
java
## Code Before: /** * Created by Siclait on 18/7/16. */ import JSONTools.ResponseError; import static JSONTools.JSONUtil.json; import static spark.Spark.after; import static spark.Spark.get; public class JSONServiceController { public JSONServiceController() { // Fetch All Urls get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json()); // Fetch Specific Short Url get("/json/original/:short", (req, res) -> { String shortURL = req.params(":short"); String url = DatabaseManager.FetchOriginalURL(shortURL); if(url != null) return url; res.status(400); return new ResponseError("No url with id %s found", shortURL); }, json()); after("/json/*",(req, res) -> {res.type("application/json");}); } } ## Instruction: Add find User json function ## Code After: /** * Created by Siclait on 18/7/16. */ import Entity.User; import JSONTools.ResponseError; import org.h2.engine.Database; import static JSONTools.JSONUtil.json; import static spark.Spark.after; import static spark.Spark.get; public class JSONServiceController { public JSONServiceController() { // Fetch All Urls get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json()); // Fetch Specific Short Url get("/json/original/:short", (req, res) -> { String shortURL = req.params(":short"); String url = DatabaseManager.FetchOriginalURL(shortURL); if(url != null) return url; res.status(400); return new ResponseError("No url with id %s found", shortURL); }, json()); // Fetch All Users get("/json/allusers", (req, res) -> DatabaseManager.FetchAllUsers(), json()); // Fetch Specific User get("/json/user/:username", (req, res) -> { String username = req.params(":username"); User user = DatabaseManager.FetchUser(username); if(user != null) return user; res.status(400); return new ResponseError("No user with id %s found", username); }, json()); after("/json/*",(req, res) -> {res.type("application/json");}); } }
... /** * Created by Siclait on 18/7/16. */ import Entity.User; import JSONTools.ResponseError; import org.h2.engine.Database; import static JSONTools.JSONUtil.json; import static spark.Spark.after; ... }, json()); // Fetch All Users get("/json/allusers", (req, res) -> DatabaseManager.FetchAllUsers(), json()); // Fetch Specific User get("/json/user/:username", (req, res) -> { String username = req.params(":username"); User user = DatabaseManager.FetchUser(username); if(user != null) return user; res.status(400); return new ResponseError("No user with id %s found", username); }, json()); after("/json/*",(req, res) -> {res.type("application/json");}); } } ...
27ab65fd8dd2b17ad6579acd5c44435c2971b31b
Java/src/net/megaroid/math/Factors.java
Java/src/net/megaroid/math/Factors.java
package net.megaroid.math; public class Factors { }
package net.megaroid.math; public class Factors { private int mNumber; public Factors(int number) { mNumber = number; } public int getNumber() { return mNumber; } }
Add a member, a Constructor and a method
Add a member, a Constructor and a method
Java
mit
xmenta/megaroid,xmenta/megaroid,xmenta/megaroid
java
## Code Before: package net.megaroid.math; public class Factors { } ## Instruction: Add a member, a Constructor and a method ## Code After: package net.megaroid.math; public class Factors { private int mNumber; public Factors(int number) { mNumber = number; } public int getNumber() { return mNumber; } }
// ... existing code ... package net.megaroid.math; public class Factors { private int mNumber; public Factors(int number) { mNumber = number; } public int getNumber() { return mNumber; } } // ... rest of the code ...
a014838c02b0abb209e0a182c46574455ea5cd0b
kernel/kernel.c
kernel/kernel.c
void kmain() { //Install descriptor tables install_gdt(); install_idt(); install_isrs(); install_irq(); install_keyboard(); asm volatile ("sti"); //Set up VGA text mode, and print a welcome message initialize_screen(); set_text_colors(VGA_COLOR_LIGHT_GRAY, VGA_COLOR_BLACK); clear_screen(); printf("NorbyOS v%s\n", NORBY_VERSION); char* buffer; while(1) { printf("==> "); gets_s(buffer, 100); if(strcmp(buffer, "colortest") == 0) { colortest(); } } //Enter an endless loop. If you disable this, another loop in boot.asm will //start, but interrupts will be disabled. while (1) {} }
void kmain() { //Install descriptor tables install_gdt(); install_idt(); install_isrs(); install_irq(); install_keyboard(); asm volatile ("sti"); //Set up VGA text mode, and print a welcome message initialize_screen(); set_text_colors(VGA_COLOR_LIGHT_GRAY, VGA_COLOR_BLACK); clear_screen(); printf("NorbyOS v%s\n", NORBY_VERSION); char* buffer; while(1) { printf("==> "); gets_s(buffer, 100); if(strcmp(buffer, "colortest") == 0) { colortest(); } else if(strcmp(buffer, "clear") == 0) { clear_screen(); } } //Enter an endless loop. If you disable this, another loop in boot.asm will //start, but interrupts will be disabled. while (1) {} }
Add "clear" command for clearing screen
Add "clear" command for clearing screen
C
mit
simon-andrews/norby,simon-andrews/norby,simon-andrews/norby
c
## Code Before: void kmain() { //Install descriptor tables install_gdt(); install_idt(); install_isrs(); install_irq(); install_keyboard(); asm volatile ("sti"); //Set up VGA text mode, and print a welcome message initialize_screen(); set_text_colors(VGA_COLOR_LIGHT_GRAY, VGA_COLOR_BLACK); clear_screen(); printf("NorbyOS v%s\n", NORBY_VERSION); char* buffer; while(1) { printf("==> "); gets_s(buffer, 100); if(strcmp(buffer, "colortest") == 0) { colortest(); } } //Enter an endless loop. If you disable this, another loop in boot.asm will //start, but interrupts will be disabled. while (1) {} } ## Instruction: Add "clear" command for clearing screen ## Code After: void kmain() { //Install descriptor tables install_gdt(); install_idt(); install_isrs(); install_irq(); install_keyboard(); asm volatile ("sti"); //Set up VGA text mode, and print a welcome message initialize_screen(); set_text_colors(VGA_COLOR_LIGHT_GRAY, VGA_COLOR_BLACK); clear_screen(); printf("NorbyOS v%s\n", NORBY_VERSION); char* buffer; while(1) { printf("==> "); gets_s(buffer, 100); if(strcmp(buffer, "colortest") == 0) { colortest(); } else if(strcmp(buffer, "clear") == 0) { clear_screen(); } } //Enter an endless loop. If you disable this, another loop in boot.asm will //start, but interrupts will be disabled. while (1) {} }
# ... existing code ... if(strcmp(buffer, "colortest") == 0) { colortest(); } else if(strcmp(buffer, "clear") == 0) { clear_screen(); } } //Enter an endless loop. If you disable this, another loop in boot.asm will # ... rest of the code ...
bd0e25f25eacf9bcb282867ba5beda5619d8a9ab
src/main/java/com/coreoz/plume/admin/webservices/security/WebSessionAdmin.java
src/main/java/com/coreoz/plume/admin/webservices/security/WebSessionAdmin.java
package com.coreoz.plume.admin.webservices.security; import java.util.Set; import com.coreoz.plume.admin.jersey.WebSessionPermission; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; /** * Contains secure data of a user */ @Getter @Setter @Accessors(chain = true) @ToString public class WebSessionAdmin implements WebSessionPermission { private long idUser; private String userName; private String fullName; private Set<String> permissions; private long expirationTime; }
package com.coreoz.plume.admin.webservices.security; import java.util.Set; import com.coreoz.plume.admin.jersey.WebSessionPermission; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; /** * Contains secure data of a user */ @Getter @Setter @Accessors(chain = true) @ToString public class WebSessionAdmin implements WebSessionPermission { @JsonSerialize(using = ToStringSerializer.class) private long idUser; private String userName; private String fullName; private Set<String> permissions; @JsonSerialize(using = ToStringSerializer.class) private long expirationTime; }
Fix session serialization for Js
Fix session serialization for Js
Java
apache-2.0
Coreoz/Plume-admin
java
## Code Before: package com.coreoz.plume.admin.webservices.security; import java.util.Set; import com.coreoz.plume.admin.jersey.WebSessionPermission; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; /** * Contains secure data of a user */ @Getter @Setter @Accessors(chain = true) @ToString public class WebSessionAdmin implements WebSessionPermission { private long idUser; private String userName; private String fullName; private Set<String> permissions; private long expirationTime; } ## Instruction: Fix session serialization for Js ## Code After: package com.coreoz.plume.admin.webservices.security; import java.util.Set; import com.coreoz.plume.admin.jersey.WebSessionPermission; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; /** * Contains secure data of a user */ @Getter @Setter @Accessors(chain = true) @ToString public class WebSessionAdmin implements WebSessionPermission { @JsonSerialize(using = ToStringSerializer.class) private long idUser; private String userName; private String fullName; private Set<String> permissions; @JsonSerialize(using = ToStringSerializer.class) private long expirationTime; }
// ... existing code ... import java.util.Set; import com.coreoz.plume.admin.jersey.WebSessionPermission; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Getter; import lombok.Setter; // ... modified code ... @ToString public class WebSessionAdmin implements WebSessionPermission { @JsonSerialize(using = ToStringSerializer.class) private long idUser; private String userName; private String fullName; private Set<String> permissions; @JsonSerialize(using = ToStringSerializer.class) private long expirationTime; } // ... rest of the code ...
1a0958063fff30c42505a09214504750a2235b13
src/main/java/com/datalogics/pdf/security/HsmManager.java
src/main/java/com/datalogics/pdf/security/HsmManager.java
/* * Copyright 2016 Datalogics Inc. */ package com.datalogics.pdf.security; import java.security.Key; import java.security.cert.Certificate; /** * The basic interface for logging into a HSM machine. */ public interface HsmManager { /** * Performs a login operation to the HSM device. * * @param parms the parameters needed to login to the device * @return a boolean indicating if the login was successful * @throws IllegalArgumentException if an argument was invalid */ boolean hsmLogin(final HsmLoginParameters parms); /** * Logs out of the default session with the HSM device. * * <p> * This method should be called only if you have called {@link hsmLogin} to establish a login session. */ void hsmLogout(); /** * Determines if logged in to the HSM Device. * * @return boolean */ boolean isLoggedIn(); /** * Get the Key object for the HSM device. * * @param password the password for recovering the key * @param keyLabel the given alias associated with the key * @return key */ Key getKey(final String password, final String keyLabel); /** * Get an array of Certificates for the HSM device. * * @param certLabel the given alias associated with the certificate * @return Certificate[] */ Certificate[] getCertificateChain(final String certLabel); /** * Get the provider name installed by this HSM. * * @return the provider name */ String getProviderName(); }
/* * Copyright 2016 Datalogics Inc. */ package com.datalogics.pdf.security; import java.security.Key; import java.security.cert.Certificate; /** * The basic interface for logging into a HSM machine. */ public interface HsmManager { /** * Performs a login operation to the HSM device. * * @param parms the parameters needed to login to the device * @return a boolean indicating if the login was successful * @throws IllegalArgumentException if an argument was invalid */ boolean hsmLogin(final HsmLoginParameters parms); /** * Logs out of the default session with the HSM device. * * <p> * This method should be called only if you have called {@link HsmManager#hsmLogin(HsmLoginParameters)} to establish * a login session. */ void hsmLogout(); /** * Determines if logged in to the HSM Device. * * @return boolean */ boolean isLoggedIn(); /** * Get the Key object for the HSM device. * * @param password the password for recovering the key * @param keyLabel the given alias associated with the key * @return key */ Key getKey(final String password, final String keyLabel); /** * Get an array of Certificates for the HSM device. * * @param certLabel the given alias associated with the certificate * @return Certificate[] */ Certificate[] getCertificateChain(final String certLabel); /** * Get the provider name installed by this HSM. * * @return the provider name */ String getProviderName(); }
Correct link to fix Javadoc warnings
Correct link to fix Javadoc warnings
Java
mit
datalogics/pdf-java-toolkit-hsm-samples,datalogics/pdf-java-toolkit-hsm-samples
java
## Code Before: /* * Copyright 2016 Datalogics Inc. */ package com.datalogics.pdf.security; import java.security.Key; import java.security.cert.Certificate; /** * The basic interface for logging into a HSM machine. */ public interface HsmManager { /** * Performs a login operation to the HSM device. * * @param parms the parameters needed to login to the device * @return a boolean indicating if the login was successful * @throws IllegalArgumentException if an argument was invalid */ boolean hsmLogin(final HsmLoginParameters parms); /** * Logs out of the default session with the HSM device. * * <p> * This method should be called only if you have called {@link hsmLogin} to establish a login session. */ void hsmLogout(); /** * Determines if logged in to the HSM Device. * * @return boolean */ boolean isLoggedIn(); /** * Get the Key object for the HSM device. * * @param password the password for recovering the key * @param keyLabel the given alias associated with the key * @return key */ Key getKey(final String password, final String keyLabel); /** * Get an array of Certificates for the HSM device. * * @param certLabel the given alias associated with the certificate * @return Certificate[] */ Certificate[] getCertificateChain(final String certLabel); /** * Get the provider name installed by this HSM. * * @return the provider name */ String getProviderName(); } ## Instruction: Correct link to fix Javadoc warnings ## Code After: /* * Copyright 2016 Datalogics Inc. */ package com.datalogics.pdf.security; import java.security.Key; import java.security.cert.Certificate; /** * The basic interface for logging into a HSM machine. */ public interface HsmManager { /** * Performs a login operation to the HSM device. * * @param parms the parameters needed to login to the device * @return a boolean indicating if the login was successful * @throws IllegalArgumentException if an argument was invalid */ boolean hsmLogin(final HsmLoginParameters parms); /** * Logs out of the default session with the HSM device. * * <p> * This method should be called only if you have called {@link HsmManager#hsmLogin(HsmLoginParameters)} to establish * a login session. */ void hsmLogout(); /** * Determines if logged in to the HSM Device. * * @return boolean */ boolean isLoggedIn(); /** * Get the Key object for the HSM device. * * @param password the password for recovering the key * @param keyLabel the given alias associated with the key * @return key */ Key getKey(final String password, final String keyLabel); /** * Get an array of Certificates for the HSM device. * * @param certLabel the given alias associated with the certificate * @return Certificate[] */ Certificate[] getCertificateChain(final String certLabel); /** * Get the provider name installed by this HSM. * * @return the provider name */ String getProviderName(); }
# ... existing code ... * Logs out of the default session with the HSM device. * * <p> * This method should be called only if you have called {@link HsmManager#hsmLogin(HsmLoginParameters)} to establish * a login session. */ void hsmLogout(); # ... rest of the code ...
1a089ec6f34ebf81b4437b6f541ee2b9f4b85966
osf/migrations/0145_pagecounter_data.py
osf/migrations/0145_pagecounter_data.py
from __future__ import unicode_literals from django.db import migrations, connection def reverse_func(state, schema): with connection.cursor() as cursor: cursor.execute( """ UPDATE osf_pagecounter SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL); """ ) def separate_pagecounter_id(state, schema): """ Splits the data in pagecounter _id field of form action:guid_id:file_id:version into four new columns: action(char), guid(fk), file(fk), version(int) """ with connection.cursor() as cursor: cursor.execute( """ UPDATE osf_pagecounter PC SET (action, guid_id, file_id, version) = (split_part(PC._id, ':', 1), G.id, F.id, NULLIF(split_part(PC._id, ':', 4), '')::int) FROM osf_guid G, osf_basefilenode F WHERE PC._id LIKE '%' || G._id || '%' AND PC._id LIKE '%' || F._id || '%'; """ ) class Migration(migrations.Migration): dependencies = [ ('osf', '0144_pagecounter_index'), ] operations = [ migrations.RunPython( separate_pagecounter_id, reverse_func ), ]
from __future__ import unicode_literals from django.db import migrations reverse_func = [ """ UPDATE osf_pagecounter SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL); """ ] # Splits the data in pagecounter _id field of form action:guid_id:file_id:version into # four new columns: action(char), guid(fk), file(fk), version(int) separate_pagecounter_id = [ """ UPDATE osf_pagecounter PC SET (action, guid_id, file_id, version) = (split_part(PC._id, ':', 1), G.id, F.id, NULLIF(split_part(PC._id, ':', 4), '')::int) FROM osf_guid G, osf_basefilenode F WHERE PC._id LIKE '%' || G._id || '%' AND PC._id LIKE '%' || F._id || '%'; """ ] class Migration(migrations.Migration): dependencies = [ ('osf', '0144_pagecounter_index'), ] operations = [ migrations.RunSQL( separate_pagecounter_id, reverse_func ), ]
Call RunSQL instead of RunPython in pagecounter data migration.
Call RunSQL instead of RunPython in pagecounter data migration.
Python
apache-2.0
cslzchen/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,felliott/osf.io,baylee-d/osf.io,mattclark/osf.io,mfraezz/osf.io,aaxelb/osf.io,felliott/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,mattclark/osf.io,adlius/osf.io,saradbowman/osf.io,adlius/osf.io,mfraezz/osf.io,aaxelb/osf.io,baylee-d/osf.io,adlius/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,felliott/osf.io,felliott/osf.io,mattclark/osf.io,baylee-d/osf.io,adlius/osf.io
python
## Code Before: from __future__ import unicode_literals from django.db import migrations, connection def reverse_func(state, schema): with connection.cursor() as cursor: cursor.execute( """ UPDATE osf_pagecounter SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL); """ ) def separate_pagecounter_id(state, schema): """ Splits the data in pagecounter _id field of form action:guid_id:file_id:version into four new columns: action(char), guid(fk), file(fk), version(int) """ with connection.cursor() as cursor: cursor.execute( """ UPDATE osf_pagecounter PC SET (action, guid_id, file_id, version) = (split_part(PC._id, ':', 1), G.id, F.id, NULLIF(split_part(PC._id, ':', 4), '')::int) FROM osf_guid G, osf_basefilenode F WHERE PC._id LIKE '%' || G._id || '%' AND PC._id LIKE '%' || F._id || '%'; """ ) class Migration(migrations.Migration): dependencies = [ ('osf', '0144_pagecounter_index'), ] operations = [ migrations.RunPython( separate_pagecounter_id, reverse_func ), ] ## Instruction: Call RunSQL instead of RunPython in pagecounter data migration. ## Code After: from __future__ import unicode_literals from django.db import migrations reverse_func = [ """ UPDATE osf_pagecounter SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL); """ ] # Splits the data in pagecounter _id field of form action:guid_id:file_id:version into # four new columns: action(char), guid(fk), file(fk), version(int) separate_pagecounter_id = [ """ UPDATE osf_pagecounter PC SET (action, guid_id, file_id, version) = (split_part(PC._id, ':', 1), G.id, F.id, NULLIF(split_part(PC._id, ':', 4), '')::int) FROM osf_guid G, osf_basefilenode F WHERE PC._id LIKE '%' || G._id || '%' AND PC._id LIKE '%' || F._id || '%'; """ ] class Migration(migrations.Migration): dependencies = [ ('osf', '0144_pagecounter_index'), ] operations = [ migrations.RunSQL( separate_pagecounter_id, reverse_func ), ]
# ... existing code ... from __future__ import unicode_literals from django.db import migrations reverse_func = [ """ UPDATE osf_pagecounter SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL); """ ] # Splits the data in pagecounter _id field of form action:guid_id:file_id:version into # four new columns: action(char), guid(fk), file(fk), version(int) separate_pagecounter_id = [ """ UPDATE osf_pagecounter PC SET (action, guid_id, file_id, version) = (split_part(PC._id, ':', 1), G.id, F.id, NULLIF(split_part(PC._id, ':', 4), '')::int) FROM osf_guid G, osf_basefilenode F WHERE PC._id LIKE '%' || G._id || '%' AND PC._id LIKE '%' || F._id || '%'; """ ] class Migration(migrations.Migration): # ... modified code ... ] operations = [ migrations.RunSQL( separate_pagecounter_id, reverse_func ), ] # ... rest of the code ...
53b920751de0e620792511df406805a5cea420cb
ideascaly/utils.py
ideascaly/utils.py
import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, bytes): arg = arg.decode('ascii') if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
Remove conditional that checked type of arg
Remove conditional that checked type of arg
Python
mit
joausaga/ideascaly
python
## Code Before: import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, bytes): arg = arg.decode('ascii') if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json ## Instruction: Remove conditional that checked type of arg ## Code After: import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
// ... existing code ... def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): // ... rest of the code ...
45c4f2455b453ee361cbb38ed1add996012b1c5e
datahelper.py
datahelper.py
from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty_ndb: g.dirty_ndb.append(obj) @app.after_request def store_ndb(response): """ Puts the contents of g.dirty_ndb """ try: if g.dirty_ndb: ndb.put_multi(g.dirty_ndb) g.dirty_ndb = [] finally: return response
from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty_ndb: g.dirty_ndb.append(obj) @app.after_request def store_ndb(response): """ Puts the contents of g.dirty_ndb """ if g.dirty_ndb: ndb.put_multi(g.dirty_ndb) g.dirty_ndb = [] return response
Fix bug where dirty_ndb was silently failing.
Fix bug where dirty_ndb was silently failing.
Python
apache-2.0
kkinder/GAEStarterKit,kkinder/GAEStarterKit,kkinder/GAEStarterKit
python
## Code Before: from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty_ndb: g.dirty_ndb.append(obj) @app.after_request def store_ndb(response): """ Puts the contents of g.dirty_ndb """ try: if g.dirty_ndb: ndb.put_multi(g.dirty_ndb) g.dirty_ndb = [] finally: return response ## Instruction: Fix bug where dirty_ndb was silently failing. ## Code After: from google.appengine.ext import ndb from flask import g from app import app def put_later(*objs): """ Any ndb model instances passed to this method will be put after the flask request has been processed. """ for obj in objs: if obj not in g.dirty_ndb: g.dirty_ndb.append(obj) @app.after_request def store_ndb(response): """ Puts the contents of g.dirty_ndb """ if g.dirty_ndb: ndb.put_multi(g.dirty_ndb) g.dirty_ndb = [] return response
# ... existing code ... """ Puts the contents of g.dirty_ndb """ if g.dirty_ndb: ndb.put_multi(g.dirty_ndb) g.dirty_ndb = [] return response # ... rest of the code ...
188b56251284352d2a2da90d5fab31276a834ff7
testsuite/tests/rts/T7037_main.c
testsuite/tests/rts/T7037_main.c
int main(int argc, char *argv[]) { const char *args[2] = {"T7037", NULL}; execv("./T7037", args); }
int main(int argc, char *argv[]) { #ifdef __MINGW32__ const #endif char * args[2] = {"T7037", NULL}; execv("./T7037", args); }
Make T7037 work on both Windows and other platforms
Make T7037 work on both Windows and other platforms
C
bsd-3-clause
mcschroeder/ghc,forked-upstream-packages-for-ghcjs/ghc,tibbe/ghc,ryantm/ghc,TomMD/ghc,oldmanmike/ghc,nkaretnikov/ghc,mettekou/ghc,GaloisInc/halvm-ghc,GaloisInc/halvm-ghc,nkaretnikov/ghc,mfine/ghc,mettekou/ghc,mcschroeder/ghc,AlexanderPankiv/ghc,christiaanb/ghc,snoyberg/ghc,ghc-android/ghc,snoyberg/ghc,christiaanb/ghc,hferreiro/replay,spacekitteh/smcghc,acowley/ghc,fmthoma/ghc,wxwxwwxxx/ghc,tjakway/ghcjvm,ghc-android/ghc,da-x/ghc,nushio3/ghc,nkaretnikov/ghc,bitemyapp/ghc,anton-dessiatov/ghc,holzensp/ghc,nkaretnikov/ghc,oldmanmike/ghc,vikraman/ghc,bitemyapp/ghc,tjakway/ghcjvm,anton-dessiatov/ghc,elieux/ghc,christiaanb/ghc,oldmanmike/ghc,TomMD/ghc,vikraman/ghc,spacekitteh/smcghc,mfine/ghc,frantisekfarka/ghc-dsi,ryantm/ghc,frantisekfarka/ghc-dsi,sdiehl/ghc,vikraman/ghc,jstolarek/ghc,GaloisInc/halvm-ghc,forked-upstream-packages-for-ghcjs/ghc,nathyong/microghc-ghc,holzensp/ghc,elieux/ghc,anton-dessiatov/ghc,fmthoma/ghc,lukexi/ghc-7.8-arm64,nushio3/ghc,christiaanb/ghc,mettekou/ghc,nushio3/ghc,hferreiro/replay,nkaretnikov/ghc,forked-upstream-packages-for-ghcjs/ghc,ezyang/ghc,sgillespie/ghc,ghc-android/ghc,mettekou/ghc,sgillespie/ghc,gridaphobe/ghc,sgillespie/ghc,AlexanderPankiv/ghc,da-x/ghc,vTurbine/ghc,urbanslug/ghc,ryantm/ghc,christiaanb/ghc,anton-dessiatov/ghc,elieux/ghc,oldmanmike/ghc,holzensp/ghc,TomMD/ghc,urbanslug/ghc,siddhanathan/ghc,snoyberg/ghc,elieux/ghc,gcampax/ghc,ml9951/ghc,ezyang/ghc,shlevy/ghc,oldmanmike/ghc,bitemyapp/ghc,urbanslug/ghc,GaloisInc/halvm-ghc,urbanslug/ghc,green-haskell/ghc,urbanslug/ghc,nushio3/ghc,jstolarek/ghc,frantisekfarka/ghc-dsi,hferreiro/replay,olsner/ghc,forked-upstream-packages-for-ghcjs/ghc,forked-upstream-packages-for-ghcjs/ghc,anton-dessiatov/ghc,sdiehl/ghc,nushio3/ghc,tibbe/ghc,vTurbine/ghc,wxwxwwxxx/ghc,mettekou/ghc,ml9951/ghc,nkaretnikov/ghc,acowley/ghc,da-x/ghc,GaloisInc/halvm-ghc,da-x/ghc,shlevy/ghc,olsner/ghc,gcampax/ghc,oldmanmike/ghc,snoyberg/ghc,olsner/ghc,vTurbine/ghc,lukexi/ghc-7.8-arm64,sdiehl/ghc,green-haskell/ghc,ezyang/ghc,hferreiro/replay,tibbe/ghc,nathyong/microghc-ghc,gridaphobe/ghc,sdiehl/ghc,ml9951/ghc,sdiehl/ghc,wxwxwwxxx/ghc,TomMD/ghc,anton-dessiatov/ghc,nathyong/microghc-ghc,ezyang/ghc,sgillespie/ghc,ml9951/ghc,urbanslug/ghc,AlexanderPankiv/ghc,GaloisInc/halvm-ghc,siddhanathan/ghc,lukexi/ghc,ezyang/ghc,wxwxwwxxx/ghc,vTurbine/ghc,sgillespie/ghc,gridaphobe/ghc,lukexi/ghc,tjakway/ghcjvm,bitemyapp/ghc,olsner/ghc,tjakway/ghcjvm,acowley/ghc,mcschroeder/ghc,christiaanb/ghc,gcampax/ghc,fmthoma/ghc,lukexi/ghc,christiaanb/ghc,AlexanderPankiv/ghc,hferreiro/replay,ml9951/ghc,gridaphobe/ghc,olsner/ghc,mfine/ghc,ml9951/ghc,olsner/ghc,lukexi/ghc,vikraman/ghc,shlevy/ghc,fmthoma/ghc,olsner/ghc,shlevy/ghc,mfine/ghc,tibbe/ghc,siddhanathan/ghc,AlexanderPankiv/ghc,ezyang/ghc,bitemyapp/ghc,tjakway/ghcjvm,mcschroeder/ghc,ezyang/ghc,wxwxwwxxx/ghc,gcampax/ghc,mcschroeder/ghc,holzensp/ghc,lukexi/ghc,GaloisInc/halvm-ghc,siddhanathan/ghc,nkaretnikov/ghc,hferreiro/replay,gcampax/ghc,sdiehl/ghc,nathyong/microghc-ghc,sgillespie/ghc,ghc-android/ghc,jstolarek/ghc,siddhanathan/ghc,ryantm/ghc,spacekitteh/smcghc,lukexi/ghc-7.8-arm64,ghc-android/ghc,ml9951/ghc,fmthoma/ghc,mfine/ghc,green-haskell/ghc,gcampax/ghc,TomMD/ghc,da-x/ghc,acowley/ghc,mettekou/ghc,forked-upstream-packages-for-ghcjs/ghc,ghc-android/ghc,vikraman/ghc,fmthoma/ghc,vTurbine/ghc,mettekou/ghc,nushio3/ghc,sdiehl/ghc,green-haskell/ghc,vTurbine/ghc,frantisekfarka/ghc-dsi,acowley/ghc,elieux/ghc,gridaphobe/ghc,snoyberg/ghc,gridaphobe/ghc,vTurbine/ghc,ghc-android/ghc,tjakway/ghcjvm,snoyberg/ghc,fmthoma/ghc,nushio3/ghc,ryantm/ghc,mcschroeder/ghc,nathyong/microghc-ghc,holzensp/ghc,vikraman/ghc,elieux/ghc,hferreiro/replay,wxwxwwxxx/ghc,mfine/ghc,elieux/ghc,acowley/ghc,lukexi/ghc-7.8-arm64,wxwxwwxxx/ghc,ml9951/ghc,shlevy/ghc,jstolarek/ghc,da-x/ghc,shlevy/ghc,nathyong/microghc-ghc,tjakway/ghcjvm,mfine/ghc,sgillespie/ghc,gcampax/ghc,acowley/ghc,oldmanmike/ghc,anton-dessiatov/ghc,nathyong/microghc-ghc,spacekitteh/smcghc,vikraman/ghc,urbanslug/ghc,lukexi/ghc-7.8-arm64,spacekitteh/smcghc,TomMD/ghc,AlexanderPankiv/ghc,jstolarek/ghc,siddhanathan/ghc,mcschroeder/ghc,TomMD/ghc,forked-upstream-packages-for-ghcjs/ghc,shlevy/ghc,da-x/ghc,AlexanderPankiv/ghc,gridaphobe/ghc,siddhanathan/ghc,frantisekfarka/ghc-dsi,tibbe/ghc,snoyberg/ghc,green-haskell/ghc
c
## Code Before: int main(int argc, char *argv[]) { const char *args[2] = {"T7037", NULL}; execv("./T7037", args); } ## Instruction: Make T7037 work on both Windows and other platforms ## Code After: int main(int argc, char *argv[]) { #ifdef __MINGW32__ const #endif char * args[2] = {"T7037", NULL}; execv("./T7037", args); }
# ... existing code ... int main(int argc, char *argv[]) { #ifdef __MINGW32__ const #endif char * args[2] = {"T7037", NULL}; execv("./T7037", args); } # ... rest of the code ...
baf4b0bbf43b40d90e697b0eabc28b323df000f8
dom/src/main/java/org/isisaddons/metamodel/paraname8/NamedFacetOnParameterParaname8Factory.java
dom/src/main/java/org/isisaddons/metamodel/paraname8/NamedFacetOnParameterParaname8Factory.java
package org.isisaddons.metamodel.paraname8; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.apache.isis.core.commons.lang.StringExtensions; import org.apache.isis.core.metamodel.facetapi.FacetHolder; import org.apache.isis.core.metamodel.facetapi.FacetUtil; import org.apache.isis.core.metamodel.facetapi.FeatureType; import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; public class NamedFacetOnParameterParaname8Factory extends FacetFactoryAbstract { public NamedFacetOnParameterParaname8Factory() { super(FeatureType.PARAMETERS_ONLY); } @Override public void processParams(final ProcessParameterContext processParameterContext) { final Method method = processParameterContext.getMethod(); final int paramNum = processParameterContext.getParamNum(); final Parameter[] parameters = method.getParameters(); final Parameter parameter = parameters[paramNum]; final String parameterName = parameter.getName(); String naturalName = StringExtensions.asNaturalName2(parameterName); FacetUtil.addFacet(create(naturalName, processParameterContext.getFacetHolder())); } private NamedFacet create(final String parameterName, final FacetHolder holder) { return new NamedFacetOnParameterParaname8(parameterName, holder); } }
package org.isisaddons.metamodel.paraname8; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.apache.isis.core.commons.lang.StringExtensions; import org.apache.isis.core.metamodel.facetapi.FacetHolder; import org.apache.isis.core.metamodel.facetapi.FacetUtil; import org.apache.isis.core.metamodel.facetapi.FeatureType; import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; public class NamedFacetOnParameterParaname8Factory extends FacetFactoryAbstract { public NamedFacetOnParameterParaname8Factory() { super(FeatureType.PARAMETERS_ONLY); } @Override public void processParams(final ProcessParameterContext processParameterContext) { final Method method = processParameterContext.getMethod(); final int paramNum = processParameterContext.getParamNum(); final Parameter[] parameters = method.getParameters(); final Parameter parameter = parameters[paramNum]; final String parameterName = parameter.getName(); if (parameterName.matches("arg\\d+")){ // Use default when the parameter name isn't available super.processParams(processParameterContext); } else { String naturalName = StringExtensions.asNaturalName2(parameterName); FacetUtil.addFacet(create(naturalName, processParameterContext.getFacetHolder())); } } private NamedFacet create(final String parameterName, final FacetHolder holder) { return new NamedFacetOnParameterParaname8(parameterName, holder); } }
Use default when parameter name is not available
Use default when parameter name is not available
Java
apache-2.0
isisaddons/isis-metamodel-paraname8,isisaddons/isis-metamodel-paraname8,isisaddons/isis-metamodel-paraname8,isisaddons/isis-metamodel-paraname8
java
## Code Before: package org.isisaddons.metamodel.paraname8; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.apache.isis.core.commons.lang.StringExtensions; import org.apache.isis.core.metamodel.facetapi.FacetHolder; import org.apache.isis.core.metamodel.facetapi.FacetUtil; import org.apache.isis.core.metamodel.facetapi.FeatureType; import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; public class NamedFacetOnParameterParaname8Factory extends FacetFactoryAbstract { public NamedFacetOnParameterParaname8Factory() { super(FeatureType.PARAMETERS_ONLY); } @Override public void processParams(final ProcessParameterContext processParameterContext) { final Method method = processParameterContext.getMethod(); final int paramNum = processParameterContext.getParamNum(); final Parameter[] parameters = method.getParameters(); final Parameter parameter = parameters[paramNum]; final String parameterName = parameter.getName(); String naturalName = StringExtensions.asNaturalName2(parameterName); FacetUtil.addFacet(create(naturalName, processParameterContext.getFacetHolder())); } private NamedFacet create(final String parameterName, final FacetHolder holder) { return new NamedFacetOnParameterParaname8(parameterName, holder); } } ## Instruction: Use default when parameter name is not available ## Code After: package org.isisaddons.metamodel.paraname8; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.apache.isis.core.commons.lang.StringExtensions; import org.apache.isis.core.metamodel.facetapi.FacetHolder; import org.apache.isis.core.metamodel.facetapi.FacetUtil; import org.apache.isis.core.metamodel.facetapi.FeatureType; import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; public class NamedFacetOnParameterParaname8Factory extends FacetFactoryAbstract { public NamedFacetOnParameterParaname8Factory() { super(FeatureType.PARAMETERS_ONLY); } @Override public void processParams(final ProcessParameterContext processParameterContext) { final Method method = processParameterContext.getMethod(); final int paramNum = processParameterContext.getParamNum(); final Parameter[] parameters = method.getParameters(); final Parameter parameter = parameters[paramNum]; final String parameterName = parameter.getName(); if (parameterName.matches("arg\\d+")){ // Use default when the parameter name isn't available super.processParams(processParameterContext); } else { String naturalName = StringExtensions.asNaturalName2(parameterName); FacetUtil.addFacet(create(naturalName, processParameterContext.getFacetHolder())); } } private NamedFacet create(final String parameterName, final FacetHolder holder) { return new NamedFacetOnParameterParaname8(parameterName, holder); } }
... final Parameter parameter = parameters[paramNum]; final String parameterName = parameter.getName(); if (parameterName.matches("arg\\d+")){ // Use default when the parameter name isn't available super.processParams(processParameterContext); } else { String naturalName = StringExtensions.asNaturalName2(parameterName); FacetUtil.addFacet(create(naturalName, processParameterContext.getFacetHolder())); } } private NamedFacet create(final String parameterName, final FacetHolder holder) { ...
7c65017fa16632f21eb94896a3d7c8d2cce989dd
user/admin.py
user/admin.py
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined')
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
Add Profile name to UserAdmin list.
Ch23: Add Profile name to UserAdmin list.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
python
## Code Before: from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') ## Instruction: Ch23: Add Profile name to UserAdmin list. ## Code After: from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',) def get_date_joined(self, user): return user.profile.joined get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name'
# ... existing code ... class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'get_name', 'email', 'get_date_joined', 'is_staff', # ... modified code ... get_date_joined.short_description = 'Joined' get_date_joined.admin_order_field = ( 'profile__joined') def get_name(self, user): return user.profile.name get_name.short_description = 'Name' get_name.admin_order_field = 'profile__name' # ... rest of the code ...
dc6f82bce52419c7c2153a33be15f3d811161d1d
flask_app.py
flask_app.py
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def nbis_list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def nbis_api_list_restaurants(): return jsonify({'restaurants': main.list_restaurants()}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def nbis_api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data})
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def list_restaurants(): return jsonify({'restaurants': [entry['identifier'] for entry in main.list_restaurants()]}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data})
Return a list of identifiers instead of almost all info
Return a list of identifiers instead of almost all info
Python
bsd-3-clause
talavis/kimenu
python
## Code Before: from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def nbis_list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def nbis_api_list_restaurants(): return jsonify({'restaurants': main.list_restaurants()}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def nbis_api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data}) ## Instruction: Return a list of identifiers instead of almost all info ## Code After: from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def list_restaurants(): return jsonify({'restaurants': [entry['identifier'] for entry in main.list_restaurants()]}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data})
# ... existing code ... @app.route('/api/') @cache.cached(timeout=3600) def list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def list_restaurants(): return jsonify({'restaurants': [entry['identifier'] for entry in main.list_restaurants()]}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) # ... rest of the code ...
4a32fe3b3735df9ec56a4ca1769268740ef5d8f4
tests/test_to_html.py
tests/test_to_html.py
from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки." def setUp(self): from paka.cmark import to_html self.func = to_html def check(self, source, expected, **kwargs): self.assertEqual(self.func(source, **kwargs), expected) def test_empty(self): self.check("", "") def test_ascii(self): self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n") def test_non_ascii(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>. И другие штуки.</p>\n")) def test_breaks(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"), breaks=True)
from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = ( "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n" "<p>Test of <em>HTML</em>.</p>") def setUp(self): from paka.cmark import to_html self.func = to_html def check(self, source, expected, **kwargs): self.assertEqual(self.func(source, **kwargs), expected) def test_empty(self): self.check("", "") def test_ascii(self): self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n") def test_non_ascii(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>. И другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n")) def test_breaks(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n"), breaks=True)
Add HTML fragment to test sample
Add HTML fragment to test sample
Python
bsd-3-clause
PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark
python
## Code Before: from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки." def setUp(self): from paka.cmark import to_html self.func = to_html def check(self, source, expected, **kwargs): self.assertEqual(self.func(source, **kwargs), expected) def test_empty(self): self.check("", "") def test_ascii(self): self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n") def test_non_ascii(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>. И другие штуки.</p>\n")) def test_breaks(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"), breaks=True) ## Instruction: Add HTML fragment to test sample ## Code After: from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = ( "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n" "<p>Test of <em>HTML</em>.</p>") def setUp(self): from paka.cmark import to_html self.func = to_html def check(self, source, expected, **kwargs): self.assertEqual(self.func(source, **kwargs), expected) def test_empty(self): self.check("", "") def test_ascii(self): self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n") def test_non_ascii(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>. И другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n")) def test_breaks(self): self.check( self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n"), breaks=True)
// ... existing code ... class ToHTMLTest(unittest.TestCase): SAMPLE = ( "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n" "<p>Test of <em>HTML</em>.</p>") def setUp(self): from paka.cmark import to_html // ... modified code ... self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>. И другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n")) def test_breaks(self): self.check( ... self.SAMPLE, ( "<p>Проверяем <em>CommonMark</em>.</p>\n" "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n" "<p>Test of <em>HTML</em>.</p>\n"), breaks=True) // ... rest of the code ...
caf0e17a2d295284ddb171139a94435643458d3f
core/src/test/java/org/realityforge/arez/api2/NodeTest.java
core/src/test/java/org/realityforge/arez/api2/NodeTest.java
package org.realityforge.arez.api2; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class NodeTest extends AbstractArezTest { static class TestNode extends Node { TestNode( @Nonnull final ArezContext context, @Nullable final String name ) { super( context, name ); } } @Test public void basicOperation() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final TestNode node = new TestNode( context, name ); assertEquals( node.getName(), name ); assertEquals( node.getContext(), context ); assertEquals( node.toString(), name ); } @Test public void basicOperation_namesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); final TestNode node = new TestNode( context, null ); assertThrows( node::getName ); assertEquals( node.getContext(), context ); assertTrue( node.toString().startsWith( node.getClass().getName() + "@" ), "node.toString() == " + node ); } }
package org.realityforge.arez.api2; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class NodeTest extends AbstractArezTest { static class TestNode extends Node { TestNode( @Nonnull final ArezContext context, @Nullable final String name ) { super( context, name ); } } @Test public void basicOperation() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final TestNode node = new TestNode( context, name ); assertEquals( node.getName(), name ); assertEquals( node.getContext(), context ); assertEquals( node.toString(), name ); } @Test public void noNameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); final TestNode node = new TestNode( context, null ); assertThrows( node::getName ); assertEquals( node.getContext(), context ); assertTrue( node.toString().startsWith( node.getClass().getName() + "@" ), "node.toString() == " + node ); } @Test public void nameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); assertThrows( () -> new TestNode( context, ValueUtil.randomString() ) ); } }
Test scenario where there is a failed assertion
Test scenario where there is a failed assertion
Java
apache-2.0
realityforge/arez,realityforge/arez,realityforge/arez
java
## Code Before: package org.realityforge.arez.api2; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class NodeTest extends AbstractArezTest { static class TestNode extends Node { TestNode( @Nonnull final ArezContext context, @Nullable final String name ) { super( context, name ); } } @Test public void basicOperation() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final TestNode node = new TestNode( context, name ); assertEquals( node.getName(), name ); assertEquals( node.getContext(), context ); assertEquals( node.toString(), name ); } @Test public void basicOperation_namesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); final TestNode node = new TestNode( context, null ); assertThrows( node::getName ); assertEquals( node.getContext(), context ); assertTrue( node.toString().startsWith( node.getClass().getName() + "@" ), "node.toString() == " + node ); } } ## Instruction: Test scenario where there is a failed assertion ## Code After: package org.realityforge.arez.api2; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class NodeTest extends AbstractArezTest { static class TestNode extends Node { TestNode( @Nonnull final ArezContext context, @Nullable final String name ) { super( context, name ); } } @Test public void basicOperation() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final TestNode node = new TestNode( context, name ); assertEquals( node.getName(), name ); assertEquals( node.getContext(), context ); assertEquals( node.toString(), name ); } @Test public void noNameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); final TestNode node = new TestNode( context, null ); assertThrows( node::getName ); assertEquals( node.getContext(), context ); assertTrue( node.toString().startsWith( node.getClass().getName() + "@" ), "node.toString() == " + node ); } @Test public void nameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); assertThrows( () -> new TestNode( context, ValueUtil.randomString() ) ); } }
# ... existing code ... } @Test public void noNameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); # ... modified code ... assertEquals( node.getContext(), context ); assertTrue( node.toString().startsWith( node.getClass().getName() + "@" ), "node.toString() == " + node ); } @Test public void nameSuppliedWhenNamesDisabled() throws Exception { final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider(); provider.setEnableNames( false ); final ArezContext context = new ArezContext(); assertThrows( () -> new TestNode( context, ValueUtil.randomString() ) ); } } # ... rest of the code ...
6b4b51a7f8e89e023c933f99aaa3a8329c05e750
salt/runners/ssh.py
salt/runners/ssh.py
''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
Fix pylint errors that snuck into 2015.2
Fix pylint errors that snuck into 2015.2
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg) ## Instruction: Fix pylint errors that snuck into 2015.2 ## Code After: ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
... ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, ...
01920b5dcced36e72a5623bf9c08c5cecfa38753
src/scrapy_redis/dupefilter.py
src/scrapy_redis/dupefilter.py
import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key)
import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = self.request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def request_fingerprint(self, request): return request_fingerprint(request) def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key)
Allow to override request fingerprint call.
Allow to override request fingerprint call.
Python
mit
darkrho/scrapy-redis,rolando/scrapy-redis
python
## Code Before: import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key) ## Instruction: Allow to override request fingerprint call. ## Code After: import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = self.request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def request_fingerprint(self, request): return request_fingerprint(request) def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key)
... return cls.from_settings(crawler.settings) def request_seen(self, request): fp = self.request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def request_fingerprint(self, request): return request_fingerprint(request) def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" ...
45188467843baa33e9a0e2868fade3b24371a11a
gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResult.java
gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResult.java
package com.conveyal.gtfs.validator.json; import java.util.Collection; import java.util.Date; import com.conveyal.gtfs.model.ValidationResult; /** * A class to hold all of the results of a validation on a single feed. * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of * a particular type of error. * @author mattwigway * */ public class FeedValidationResult { /** Were we able to load the GTFS at all (note that this should only indicate corrupted files, * not missing ones; that should raise an exception instead.) */ public LoadStatus loadStatus; /** * Additional description of why the feed failed to load. */ public String loadFailureReason; /** * The name of the feed on the file system */ public String feedFileName; /** * All of the agencies in the feed */ public Collection<String> agencies; public ValidationResult routes; public ValidationResult stops; public ValidationResult trips; public ValidationResult shapes; // statistics public int agencyCount; public int routeCount; public int tripCount; public int stopTimesCount; /** The first date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date startDate; /** The last date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date endDate; }
package com.conveyal.gtfs.validator.json; import java.util.Collection; import java.util.Date; import com.conveyal.gtfs.model.ValidationResult; import com.fasterxml.jackson.annotation.JsonProperty; /** * A class to hold all of the results of a validation on a single feed. * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of * a particular type of error. * @author mattwigway * */ public class FeedValidationResult { /** Were we able to load the GTFS at all (note that this should only indicate corrupted files, * not missing ones; that should raise an exception instead.) */ @JsonProperty public LoadStatus loadStatus; /** * Additional description of why the feed failed to load. */ public String loadFailureReason; /** * The name of the feed on the file system */ public String feedFileName; /** * All of the agencies in the feed */ public Collection<String> agencies; public ValidationResult routes; public ValidationResult stops; public ValidationResult trips; public ValidationResult shapes; // statistics public int agencyCount; public int routeCount; public int tripCount; public int stopTimesCount; /** The first date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date startDate; /** The last date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date endDate; }
Make loadstatus end up in the json.
Make loadstatus end up in the json.
Java
mit
laidig/gtfs-validator,laidig/gtfs-validator,conveyal/gtfs-validator,conveyal/gtfs-validator,laidig/gtfs-validator,conveyal/gtfs-validator,laidig/gtfs-validator,conveyal/gtfs-validator
java
## Code Before: package com.conveyal.gtfs.validator.json; import java.util.Collection; import java.util.Date; import com.conveyal.gtfs.model.ValidationResult; /** * A class to hold all of the results of a validation on a single feed. * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of * a particular type of error. * @author mattwigway * */ public class FeedValidationResult { /** Were we able to load the GTFS at all (note that this should only indicate corrupted files, * not missing ones; that should raise an exception instead.) */ public LoadStatus loadStatus; /** * Additional description of why the feed failed to load. */ public String loadFailureReason; /** * The name of the feed on the file system */ public String feedFileName; /** * All of the agencies in the feed */ public Collection<String> agencies; public ValidationResult routes; public ValidationResult stops; public ValidationResult trips; public ValidationResult shapes; // statistics public int agencyCount; public int routeCount; public int tripCount; public int stopTimesCount; /** The first date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date startDate; /** The last date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date endDate; } ## Instruction: Make loadstatus end up in the json. ## Code After: package com.conveyal.gtfs.validator.json; import java.util.Collection; import java.util.Date; import com.conveyal.gtfs.model.ValidationResult; import com.fasterxml.jackson.annotation.JsonProperty; /** * A class to hold all of the results of a validation on a single feed. * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of * a particular type of error. * @author mattwigway * */ public class FeedValidationResult { /** Were we able to load the GTFS at all (note that this should only indicate corrupted files, * not missing ones; that should raise an exception instead.) */ @JsonProperty public LoadStatus loadStatus; /** * Additional description of why the feed failed to load. */ public String loadFailureReason; /** * The name of the feed on the file system */ public String feedFileName; /** * All of the agencies in the feed */ public Collection<String> agencies; public ValidationResult routes; public ValidationResult stops; public ValidationResult trips; public ValidationResult shapes; // statistics public int agencyCount; public int routeCount; public int tripCount; public int stopTimesCount; /** The first date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date startDate; /** The last date the feed has service, either in calendar.txt or calendar_dates.txt */ public Date endDate; }
// ... existing code ... import java.util.Date; import com.conveyal.gtfs.model.ValidationResult; import com.fasterxml.jackson.annotation.JsonProperty; /** * A class to hold all of the results of a validation on a single feed. // ... modified code ... /** Were we able to load the GTFS at all (note that this should only indicate corrupted files, * not missing ones; that should raise an exception instead.) */ @JsonProperty public LoadStatus loadStatus; /** // ... rest of the code ...
f75e245f461e57cc868ee5452c88aea92b6681bf
chainer/functions/parameter.py
chainer/functions/parameter.py
import numpy from chainer import function class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: array: Initial parameter array. """ parameter_names = 'W', gradient_names = 'gW', def __init__(self, array): self.W = array self.gW = numpy.empty_like(array) def forward(self, x): return self.W, def backward(self, x, gy): self.gW += gy[0] return ()
import numpy from chainer import function from chainer.utils import type_check class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: array: Initial parameter array. """ parameter_names = 'W', gradient_names = 'gW', def __init__(self, array): self.W = array self.gW = numpy.empty_like(array) def check_type_forward(self, in_types): type_check.expect(in_types.size() == 0) def forward(self, x): return self.W, def backward(self, x, gy): self.gW += gy[0] return ()
Add typecheck to Parameter function
Add typecheck to Parameter function
Python
mit
t-abe/chainer,chainer/chainer,pfnet/chainer,jnishi/chainer,sou81821/chainer,ikasumi/chainer,tigerneil/chainer,delta2323/chainer,1986ks/chainer,chainer/chainer,yanweifu/chainer,ronekko/chainer,muupan/chainer,truongdq/chainer,chainer/chainer,muupan/chainer,okuta/chainer,jnishi/chainer,anaruse/chainer,hvy/chainer,cupy/cupy,cupy/cupy,truongdq/chainer,ktnyt/chainer,keisuke-umezawa/chainer,jfsantos/chainer,ytoyama/yans_chainer_hackathon,masia02/chainer,niboshi/chainer,jnishi/chainer,kikusu/chainer,AlpacaDB/chainer,woodshop/chainer,keisuke-umezawa/chainer,jnishi/chainer,ktnyt/chainer,cupy/cupy,elviswf/chainer,kiyukuta/chainer,tkerola/chainer,Kaisuke5/chainer,keisuke-umezawa/chainer,rezoo/chainer,niboshi/chainer,kuwa32/chainer,kikusu/chainer,wavelets/chainer,benob/chainer,okuta/chainer,AlpacaDB/chainer,hidenori-t/chainer,okuta/chainer,woodshop/complex-chainer,wkentaro/chainer,t-abe/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,cemoody/chainer,ktnyt/chainer,benob/chainer,niboshi/chainer,wkentaro/chainer,laysakura/chainer,niboshi/chainer,tscohen/chainer,hvy/chainer,ysekky/chainer,cupy/cupy,hvy/chainer,aonotas/chainer,chainer/chainer,sinhrks/chainer,ktnyt/chainer,kashif/chainer,wkentaro/chainer,sinhrks/chainer,minhpqn/chainer,umitanuki/chainer
python
## Code Before: import numpy from chainer import function class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: array: Initial parameter array. """ parameter_names = 'W', gradient_names = 'gW', def __init__(self, array): self.W = array self.gW = numpy.empty_like(array) def forward(self, x): return self.W, def backward(self, x, gy): self.gW += gy[0] return () ## Instruction: Add typecheck to Parameter function ## Code After: import numpy from chainer import function from chainer.utils import type_check class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: array: Initial parameter array. """ parameter_names = 'W', gradient_names = 'gW', def __init__(self, array): self.W = array self.gW = numpy.empty_like(array) def check_type_forward(self, in_types): type_check.expect(in_types.size() == 0) def forward(self, x): return self.W, def backward(self, x, gy): self.gW += gy[0] return ()
... import numpy from chainer import function from chainer.utils import type_check class Parameter(function.Function): ... self.W = array self.gW = numpy.empty_like(array) def check_type_forward(self, in_types): type_check.expect(in_types.size() == 0) def forward(self, x): return self.W, ...
a2430b67423ce036d2a96541e86d356ace04db69
Twitch/cogs/words.py
Twitch/cogs/words.py
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) else: await ctx.send("Definition not found.")
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
Use f-string for define command
[TwitchIO] Use f-string for define command
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
python
## Code Before: from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) else: await ctx.send("Definition not found.") ## Instruction: [TwitchIO] Use f-string for define command ## Code After: from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
// ... existing code ... async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.") // ... rest of the code ...