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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
45a528d16859ae0ae1ffa81839783e06dea86a0f
|
src/main/java/org/cyclops/commoncapabilities/core/Helpers.java
|
src/main/java/org/cyclops/commoncapabilities/core/Helpers.java
|
package org.cyclops.commoncapabilities.core;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Helper methods.
* @author rubensworks
*/
public class Helpers {
public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
if (method != null) {
try {
return (R) method.invoke(instance, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
public static <R> R getFieldValue(Object instance, @Nullable Field field) {
if (field != null) {
try {
return (R) field.get(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
try {
return ReflectionHelper.findMethod(clazz, null, new String[]{method}, methodTypes);
} catch (ReflectionHelper.UnableToFindMethodException e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String field) {
try {
return ReflectionHelper.findField(clazz, field);
} catch (ReflectionHelper.UnableToFindFieldException e) {
e.printStackTrace();
return null;
}
}
}
|
package org.cyclops.commoncapabilities.core;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Helper methods.
* @author rubensworks
*/
public class Helpers {
public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
if (method != null) {
try {
return (R) method.invoke(instance, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
public static <R> R getFieldValue(Object instance, @Nullable Field field) {
if (field != null) {
try {
return (R) field.get(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
try {
return ReflectionHelper.findMethod(clazz, method, null, methodTypes);
} catch (ReflectionHelper.UnableToFindMethodException e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String field) {
try {
return ReflectionHelper.findField(clazz, field);
} catch (ReflectionHelper.UnableToFindFieldException e) {
e.printStackTrace();
return null;
}
}
}
|
Fix compilation issue because of latest Forge RB
|
Fix compilation issue because of latest Forge RB
|
Java
|
mit
|
CyclopsMC/CommonCapabilities
|
java
|
## Code Before:
package org.cyclops.commoncapabilities.core;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Helper methods.
* @author rubensworks
*/
public class Helpers {
public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
if (method != null) {
try {
return (R) method.invoke(instance, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
public static <R> R getFieldValue(Object instance, @Nullable Field field) {
if (field != null) {
try {
return (R) field.get(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
try {
return ReflectionHelper.findMethod(clazz, null, new String[]{method}, methodTypes);
} catch (ReflectionHelper.UnableToFindMethodException e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String field) {
try {
return ReflectionHelper.findField(clazz, field);
} catch (ReflectionHelper.UnableToFindFieldException e) {
e.printStackTrace();
return null;
}
}
}
## Instruction:
Fix compilation issue because of latest Forge RB
## Code After:
package org.cyclops.commoncapabilities.core;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Helper methods.
* @author rubensworks
*/
public class Helpers {
public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
if (method != null) {
try {
return (R) method.invoke(instance, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
public static <R> R getFieldValue(Object instance, @Nullable Field field) {
if (field != null) {
try {
return (R) field.get(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
try {
return ReflectionHelper.findMethod(clazz, method, null, methodTypes);
} catch (ReflectionHelper.UnableToFindMethodException e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class<?> clazz, String field) {
try {
return ReflectionHelper.findField(clazz, field);
} catch (ReflectionHelper.UnableToFindFieldException e) {
e.printStackTrace();
return null;
}
}
}
|
...
public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
try {
return ReflectionHelper.findMethod(clazz, method, null, methodTypes);
} catch (ReflectionHelper.UnableToFindMethodException e) {
e.printStackTrace();
return null;
...
|
55ad95c141b0962dda7f3d530e6ec9c7f143ec1d
|
test/src/main.c
|
test/src/main.c
|
int main() {
printf("Test goes here.\n");
}
|
int tests_run = 0;
static char *test_all_kept() {
for (int count = 0; count < 1000; count++) {
rtree_t *rt = rtree_create();
for (uintptr_t i = 0; i < count; i++) {
rtree_add(rt, (void *) i, (double) drand48());
}
char *recvd = calloc(count, sizeof(char));
for (int i = 0; i < count; i++) {
int pos = (int) ((uintptr_t) rtree_rpop(rt));
recvd[pos]++;
}
for (int i = 0; i < count; i++) {
char *err_msg = calloc(80, sizeof(char));
sprintf(err_msg, "Expected exactly 1 elt with value %d, but was %d\n", i,
recvd[i]);
mu_assert(err_msg, recvd[i] == 1);
free(err_msg);
}
free(recvd);
rtree_destroy(rt);
}
return 0;
}
static char *all_tests() {
mu_run_test(test_all_kept);
return 0;
}
int main() {
char *result = all_tests();
if (result != 0) {
printf("%s\n", result);
}
else {
printf("All tests passed.\n");
}
printf("Tests run: %d\n", tests_run);
return result != 0;
}
|
Add in check to ensure all elements are included.
|
Add in check to ensure all elements are included.
|
C
|
mit
|
hyPiRion/roulette-tree,hyPiRion/roulette-tree
|
c
|
## Code Before:
int main() {
printf("Test goes here.\n");
}
## Instruction:
Add in check to ensure all elements are included.
## Code After:
int tests_run = 0;
static char *test_all_kept() {
for (int count = 0; count < 1000; count++) {
rtree_t *rt = rtree_create();
for (uintptr_t i = 0; i < count; i++) {
rtree_add(rt, (void *) i, (double) drand48());
}
char *recvd = calloc(count, sizeof(char));
for (int i = 0; i < count; i++) {
int pos = (int) ((uintptr_t) rtree_rpop(rt));
recvd[pos]++;
}
for (int i = 0; i < count; i++) {
char *err_msg = calloc(80, sizeof(char));
sprintf(err_msg, "Expected exactly 1 elt with value %d, but was %d\n", i,
recvd[i]);
mu_assert(err_msg, recvd[i] == 1);
free(err_msg);
}
free(recvd);
rtree_destroy(rt);
}
return 0;
}
static char *all_tests() {
mu_run_test(test_all_kept);
return 0;
}
int main() {
char *result = all_tests();
if (result != 0) {
printf("%s\n", result);
}
else {
printf("All tests passed.\n");
}
printf("Tests run: %d\n", tests_run);
return result != 0;
}
|
# ... existing code ...
int tests_run = 0;
static char *test_all_kept() {
for (int count = 0; count < 1000; count++) {
rtree_t *rt = rtree_create();
for (uintptr_t i = 0; i < count; i++) {
rtree_add(rt, (void *) i, (double) drand48());
}
char *recvd = calloc(count, sizeof(char));
for (int i = 0; i < count; i++) {
int pos = (int) ((uintptr_t) rtree_rpop(rt));
recvd[pos]++;
}
for (int i = 0; i < count; i++) {
char *err_msg = calloc(80, sizeof(char));
sprintf(err_msg, "Expected exactly 1 elt with value %d, but was %d\n", i,
recvd[i]);
mu_assert(err_msg, recvd[i] == 1);
free(err_msg);
}
free(recvd);
rtree_destroy(rt);
}
return 0;
}
static char *all_tests() {
mu_run_test(test_all_kept);
return 0;
}
int main() {
char *result = all_tests();
if (result != 0) {
printf("%s\n", result);
}
else {
printf("All tests passed.\n");
}
printf("Tests run: %d\n", tests_run);
return result != 0;
}
# ... rest of the code ...
|
1bf1cb68b380ea0f5e1d3dc6b808673aac940572
|
vivarium-swing/src/main/java/com/johnuckele/vivarium/visualization/animation/SwingGraphics.java
|
vivarium-swing/src/main/java/com/johnuckele/vivarium/visualization/animation/SwingGraphics.java
|
package com.johnuckele.vivarium.visualization.animation;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import com.johnuckele.vivarium.core.Direction;
import com.johnuckele.vivarium.visualization.GraphicalSystem;
public class SwingGraphics extends GraphicalSystem
{
private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
private static Image IMAGE = IMAGE_ICON.getImage();
private Graphics2D _graphics;
private ImageObserver _observer;
public SwingGraphics()
{
}
public void setResources(Graphics2D graphics, ImageObserver observer)
{
_graphics = graphics;
_observer = observer;
}
@Override
public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
{
_graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);
_graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
_graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);
}
}
|
package com.johnuckele.vivarium.visualization.animation;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import com.johnuckele.vivarium.core.Direction;
public class SwingGraphics extends GraphicalSystem
{
private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
private static Image IMAGE = IMAGE_ICON.getImage();
private Graphics2D _graphics;
private ImageObserver _observer;
public SwingGraphics()
{
}
public void setResources(Graphics2D graphics, ImageObserver observer)
{
_graphics = graphics;
_observer = observer;
}
@Override
public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
{
_graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
_graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
_graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
}
}
|
Fix to division by int warning
|
Fix to division by int warning
|
Java
|
mit
|
juckele/vivarium,juckele/vivarium,juckele/vivarium
|
java
|
## Code Before:
package com.johnuckele.vivarium.visualization.animation;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import com.johnuckele.vivarium.core.Direction;
import com.johnuckele.vivarium.visualization.GraphicalSystem;
public class SwingGraphics extends GraphicalSystem
{
private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
private static Image IMAGE = IMAGE_ICON.getImage();
private Graphics2D _graphics;
private ImageObserver _observer;
public SwingGraphics()
{
}
public void setResources(Graphics2D graphics, ImageObserver observer)
{
_graphics = graphics;
_observer = observer;
}
@Override
public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
{
_graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);
_graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
_graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);
}
}
## Instruction:
Fix to division by int warning
## Code After:
package com.johnuckele.vivarium.visualization.animation;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import com.johnuckele.vivarium.core.Direction;
public class SwingGraphics extends GraphicalSystem
{
private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
private static Image IMAGE = IMAGE_ICON.getImage();
private Graphics2D _graphics;
private ImageObserver _observer;
public SwingGraphics()
{
}
public void setResources(Graphics2D graphics, ImageObserver observer)
{
_graphics = graphics;
_observer = observer;
}
@Override
public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
{
_graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
_graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
_graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
}
}
|
// ... existing code ...
import javax.swing.ImageIcon;
import com.johnuckele.vivarium.core.Direction;
public class SwingGraphics extends GraphicalSystem
{
// ... modified code ...
@Override
public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
{
_graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
_graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
_graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
}
// ... rest of the code ...
|
220b6a9fee0f307d4de1e48b29093812f7dd10ec
|
var/spack/repos/builtin/packages/m4/package.py
|
var/spack/repos/builtin/packages/m4/package.py
|
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
|
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
|
Make libsigsegv an optional dependency
|
Make libsigsegv an optional dependency
|
Python
|
lgpl-2.1
|
lgarren/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,TheTimmy/spack,lgarren/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,mfherbst/spack,matthiasdiener/spack,matthiasdiener/spack,mfherbst/spack,krafczyk/spack,iulian787/spack,iulian787/spack,matthiasdiener/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,lgarren/spack,EmreAtes/spack,EmreAtes/spack,mfherbst/spack,lgarren/spack,LLNL/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,EmreAtes/spack,iulian787/spack,tmerrick1/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,skosukhin/spack,tmerrick1/spack,tmerrick1/spack,skosukhin/spack,EmreAtes/spack,matthiasdiener/spack
|
python
|
## Code Before:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
## Instruction:
Make libsigsegv an optional dependency
## Code After:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
|
# ... existing code ...
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
# ... rest of the code ...
|
47025defa689cf4af9f79f39f2cf45ba18b7e10b
|
core/src/main/java/org/elasticsearch/bootstrap/BootstrapInfo.java
|
core/src/main/java/org/elasticsearch/bootstrap/BootstrapInfo.java
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the 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.elasticsearch.bootstrap;
import java.util.Collections;
import java.util.Set;
/**
* Exposes system startup information
*/
public final class BootstrapInfo {
/** no instantiation */
private BootstrapInfo() {}
/**
* Returns true if we successfully loaded native libraries.
* <p>
* If this returns false, then native operations such as locking
* memory did not work.
*/
public static boolean isNativesAvailable() {
return Natives.JNA_AVAILABLE;
}
/**
* Returns true if we were able to lock the process's address space.
*/
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
/**
* Returns set of insecure plugins.
* <p>
* These are plugins with unresolved issues in third-party libraries,
* that require additional privileges as a workaround.
*/
public static Set<String> getInsecurePluginList() {
return Collections.unmodifiableSet(Security.SPECIAL_PLUGINS.keySet());
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the 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.elasticsearch.bootstrap;
/**
* Exposes system startup information
*/
public final class BootstrapInfo {
/** no instantiation */
private BootstrapInfo() {}
/**
* Returns true if we successfully loaded native libraries.
* <p>
* If this returns false, then native operations such as locking
* memory did not work.
*/
public static boolean isNativesAvailable() {
return Natives.JNA_AVAILABLE;
}
/**
* Returns true if we were able to lock the process's address space.
*/
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
}
|
Remove this: we are gonna manage these right
|
Remove this: we are gonna manage these right
|
Java
|
apache-2.0
|
palecur/elasticsearch,masterweb121/elasticsearch,strapdata/elassandra5-rc,lmtwga/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,areek/elasticsearch,liweinan0423/elasticsearch,petabytedata/elasticsearch,lks21c/elasticsearch,fernandozhu/elasticsearch,episerver/elasticsearch,wbowling/elasticsearch,mikemccand/elasticsearch,mm0/elasticsearch,myelin/elasticsearch,xuzha/elasticsearch,MichaelLiZhou/elasticsearch,cwurm/elasticsearch,sneivandt/elasticsearch,ricardocerq/elasticsearch,kunallimaye/elasticsearch,vroyer/elasticassandra,fernandozhu/elasticsearch,hafkensite/elasticsearch,kaneshin/elasticsearch,ZTE-PaaS/elasticsearch,LewayneNaidoo/elasticsearch,jchampion/elasticsearch,iacdingping/elasticsearch,cnfire/elasticsearch-1,camilojd/elasticsearch,lzo/elasticsearch-1,strapdata/elassandra,mortonsykes/elasticsearch,dpursehouse/elasticsearch,nomoa/elasticsearch,JackyMai/elasticsearch,lmtwga/elasticsearch,iacdingping/elasticsearch,mgalushka/elasticsearch,lmtwga/elasticsearch,cwurm/elasticsearch,myelin/elasticsearch,karthikjaps/elasticsearch,JSCooke/elasticsearch,liweinan0423/elasticsearch,nomoa/elasticsearch,kalburgimanjunath/elasticsearch,socialrank/elasticsearch,pozhidaevak/elasticsearch,wangtuo/elasticsearch,HonzaKral/elasticsearch,henakamaMSFT/elasticsearch,vroyer/elasticassandra,ivansun1010/elasticsearch,njlawton/elasticsearch,jeteve/elasticsearch,hafkensite/elasticsearch,martinstuga/elasticsearch,maddin2016/elasticsearch,girirajsharma/elasticsearch,zkidkid/elasticsearch,rlugojr/elasticsearch,cwurm/elasticsearch,bawse/elasticsearch,wbowling/elasticsearch,s1monw/elasticsearch,areek/elasticsearch,winstonewert/elasticsearch,MaineC/elasticsearch,JervyShi/elasticsearch,gingerwizard/elasticsearch,rlugojr/elasticsearch,HonzaKral/elasticsearch,davidvgalbraith/elasticsearch,IanvsPoplicola/elasticsearch,winstonewert/elasticsearch,YosuaMichael/elasticsearch,AndreKR/elasticsearch,masterweb121/elasticsearch,xuzha/elasticsearch,Shepard1212/elasticsearch,Shepard1212/elasticsearch,socialrank/elasticsearch,rlugojr/elasticsearch,drewr/elasticsearch,glefloch/elasticsearch,rhoml/elasticsearch,polyfractal/elasticsearch,diendt/elasticsearch,alexshadow007/elasticsearch,clintongormley/elasticsearch,andrejserafim/elasticsearch,sdauletau/elasticsearch,cnfire/elasticsearch-1,Charlesdong/elasticsearch,adrianbk/elasticsearch,snikch/elasticsearch,MetSystem/elasticsearch,MisterAndersen/elasticsearch,wangtuo/elasticsearch,myelin/elasticsearch,yynil/elasticsearch,dpursehouse/elasticsearch,jeteve/elasticsearch,qwerty4030/elasticsearch,F0lha/elasticsearch,avikurapati/elasticsearch,artnowo/elasticsearch,umeshdangat/elasticsearch,Rygbee/elasticsearch,liweinan0423/elasticsearch,davidvgalbraith/elasticsearch,infusionsoft/elasticsearch,schonfeld/elasticsearch,mbrukman/elasticsearch,nomoa/elasticsearch,tebriel/elasticsearch,LeoYao/elasticsearch,yanjunh/elasticsearch,nellicus/elasticsearch,mortonsykes/elasticsearch,KimTaehee/elasticsearch,obourgain/elasticsearch,caengcjd/elasticsearch,markwalkom/elasticsearch,GlenRSmith/elasticsearch,drewr/elasticsearch,nrkkalyan/elasticsearch,JervyShi/elasticsearch,mortonsykes/elasticsearch,mohit/elasticsearch,sdauletau/elasticsearch,sdauletau/elasticsearch,mbrukman/elasticsearch,alexshadow007/elasticsearch,drewr/elasticsearch,franklanganke/elasticsearch,vroyer/elassandra,Stacey-Gammon/elasticsearch,qwerty4030/elasticsearch,xingguang2013/elasticsearch,sneivandt/elasticsearch,geidies/elasticsearch,alexshadow007/elasticsearch,franklanganke/elasticsearch,gmarz/elasticsearch,mmaracic/elasticsearch,ivansun1010/elasticsearch,KimTaehee/elasticsearch,zkidkid/elasticsearch,weipinghe/elasticsearch,Helen-Zhao/elasticsearch,masaruh/elasticsearch,yanjunh/elasticsearch,maddin2016/elasticsearch,jango2015/elasticsearch,iacdingping/elasticsearch,PhaedrusTheGreek/elasticsearch,spiegela/elasticsearch,i-am-Nathan/elasticsearch,Collaborne/elasticsearch,tebriel/elasticsearch,yanjunh/elasticsearch,strapdata/elassandra,jango2015/elasticsearch,JSCooke/elasticsearch,njlawton/elasticsearch,wangtuo/elasticsearch,winstonewert/elasticsearch,robin13/elasticsearch,geidies/elasticsearch,diendt/elasticsearch,jprante/elasticsearch,s1monw/elasticsearch,KimTaehee/elasticsearch,MichaelLiZhou/elasticsearch,coding0011/elasticsearch,martinstuga/elasticsearch,nazarewk/elasticsearch,jimczi/elasticsearch,polyfractal/elasticsearch,onegambler/elasticsearch,strapdata/elassandra5-rc,palecur/elasticsearch,kalimatas/elasticsearch,episerver/elasticsearch,obourgain/elasticsearch,weipinghe/elasticsearch,scottsom/elasticsearch,bestwpw/elasticsearch,lmtwga/elasticsearch,elasticdog/elasticsearch,karthikjaps/elasticsearch,iacdingping/elasticsearch,nrkkalyan/elasticsearch,girirajsharma/elasticsearch,bestwpw/elasticsearch,mnylen/elasticsearch,gingerwizard/elasticsearch,adrianbk/elasticsearch,mcku/elasticsearch,ESamir/elasticsearch,martinstuga/elasticsearch,AndreKR/elasticsearch,njlawton/elasticsearch,vietlq/elasticsearch,ulkas/elasticsearch,schonfeld/elasticsearch,glefloch/elasticsearch,henakamaMSFT/elasticsearch,PhaedrusTheGreek/elasticsearch,andrejserafim/elasticsearch,ouyangkongtong/elasticsearch,i-am-Nathan/elasticsearch,IanvsPoplicola/elasticsearch,nezirus/elasticsearch,davidvgalbraith/elasticsearch,LewayneNaidoo/elasticsearch,a2lin/elasticsearch,jimczi/elasticsearch,jeteve/elasticsearch,lzo/elasticsearch-1,spiegela/elasticsearch,scorpionvicky/elasticsearch,YosuaMichael/elasticsearch,uschindler/elasticsearch,mikemccand/elasticsearch,naveenhooda2000/elasticsearch,shreejay/elasticsearch,vietlq/elasticsearch,masaruh/elasticsearch,ulkas/elasticsearch,yynil/elasticsearch,nknize/elasticsearch,diendt/elasticsearch,F0lha/elasticsearch,Charlesdong/elasticsearch,elasticdog/elasticsearch,avikurapati/elasticsearch,nrkkalyan/elasticsearch,weipinghe/elasticsearch,AndreKR/elasticsearch,nilabhsagar/elasticsearch,scorpionvicky/elasticsearch,petabytedata/elasticsearch,weipinghe/elasticsearch,ThiagoGarciaAlves/elasticsearch,karthikjaps/elasticsearch,mjason3/elasticsearch,sneivandt/elasticsearch,franklanganke/elasticsearch,xingguang2013/elasticsearch,infusionsoft/elasticsearch,uschindler/elasticsearch,markharwood/elasticsearch,lzo/elasticsearch-1,bawse/elasticsearch,nellicus/elasticsearch,uschindler/elasticsearch,trangvh/elasticsearch,mmaracic/elasticsearch,ThiagoGarciaAlves/elasticsearch,gfyoung/elasticsearch,strapdata/elassandra,C-Bish/elasticsearch,petabytedata/elasticsearch,cwurm/elasticsearch,s1monw/elasticsearch,masaruh/elasticsearch,ouyangkongtong/elasticsearch,MichaelLiZhou/elasticsearch,infusionsoft/elasticsearch,mikemccand/elasticsearch,rajanm/elasticsearch,mcku/elasticsearch,MisterAndersen/elasticsearch,MetSystem/elasticsearch,sreeramjayan/elasticsearch,Collaborne/elasticsearch,YosuaMichael/elasticsearch,vietlq/elasticsearch,JSCooke/elasticsearch,F0lha/elasticsearch,mm0/elasticsearch,umeshdangat/elasticsearch,infusionsoft/elasticsearch,wbowling/elasticsearch,mbrukman/elasticsearch,sdauletau/elasticsearch,KimTaehee/elasticsearch,AndreKR/elasticsearch,nrkkalyan/elasticsearch,fred84/elasticsearch,drewr/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,spiegela/elasticsearch,geidies/elasticsearch,LewayneNaidoo/elasticsearch,Rygbee/elasticsearch,Stacey-Gammon/elasticsearch,elancom/elasticsearch,drewr/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,achow/elasticsearch,fernandozhu/elasticsearch,nazarewk/elasticsearch,YosuaMichael/elasticsearch,C-Bish/elasticsearch,xingguang2013/elasticsearch,gmarz/elasticsearch,kaneshin/elasticsearch,andrejserafim/elasticsearch,iacdingping/elasticsearch,F0lha/elasticsearch,areek/elasticsearch,jprante/elasticsearch,Charlesdong/elasticsearch,i-am-Nathan/elasticsearch,petabytedata/elasticsearch,nellicus/elasticsearch,IanvsPoplicola/elasticsearch,maddin2016/elasticsearch,rajanm/elasticsearch,StefanGor/elasticsearch,dpursehouse/elasticsearch,clintongormley/elasticsearch,nezirus/elasticsearch,elancom/elasticsearch,jprante/elasticsearch,mjason3/elasticsearch,AndreKR/elasticsearch,kalimatas/elasticsearch,jprante/elasticsearch,C-Bish/elasticsearch,masterweb121/elasticsearch,ESamir/elasticsearch,andrestc/elasticsearch,karthikjaps/elasticsearch,mortonsykes/elasticsearch,lzo/elasticsearch-1,fforbeck/elasticsearch,KimTaehee/elasticsearch,achow/elasticsearch,qwerty4030/elasticsearch,drewr/elasticsearch,nomoa/elasticsearch,palecur/elasticsearch,wbowling/elasticsearch,markwalkom/elasticsearch,mohit/elasticsearch,bestwpw/elasticsearch,davidvgalbraith/elasticsearch,masterweb121/elasticsearch,ouyangkongtong/elasticsearch,gingerwizard/elasticsearch,geidies/elasticsearch,henakamaMSFT/elasticsearch,kunallimaye/elasticsearch,markharwood/elasticsearch,jbertouch/elasticsearch,jango2015/elasticsearch,mapr/elasticsearch,markwalkom/elasticsearch,nilabhsagar/elasticsearch,mgalushka/elasticsearch,LeoYao/elasticsearch,rmuir/elasticsearch,nezirus/elasticsearch,petabytedata/elasticsearch,dongjoon-hyun/elasticsearch,palecur/elasticsearch,lzo/elasticsearch-1,pozhidaevak/elasticsearch,jchampion/elasticsearch,markharwood/elasticsearch,strapdata/elassandra5-rc,nknize/elasticsearch,mnylen/elasticsearch,strapdata/elassandra,ricardocerq/elasticsearch,trangvh/elasticsearch,gmarz/elasticsearch,Charlesdong/elasticsearch,fforbeck/elasticsearch,fernandozhu/elasticsearch,Helen-Zhao/elasticsearch,kaneshin/elasticsearch,iacdingping/elasticsearch,caengcjd/elasticsearch,s1monw/elasticsearch,zkidkid/elasticsearch,jprante/elasticsearch,adrianbk/elasticsearch,Helen-Zhao/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,rajanm/elasticsearch,andrestc/elasticsearch,ouyangkongtong/elasticsearch,achow/elasticsearch,jbertouch/elasticsearch,MisterAndersen/elasticsearch,C-Bish/elasticsearch,ESamir/elasticsearch,shreejay/elasticsearch,kunallimaye/elasticsearch,andrejserafim/elasticsearch,IanvsPoplicola/elasticsearch,nilabhsagar/elasticsearch,karthikjaps/elasticsearch,GlenRSmith/elasticsearch,andrestc/elasticsearch,franklanganke/elasticsearch,huanzhong/elasticsearch,dpursehouse/elasticsearch,palecur/elasticsearch,mnylen/elasticsearch,andrestc/elasticsearch,mohit/elasticsearch,fforbeck/elasticsearch,rmuir/elasticsearch,clintongormley/elasticsearch,yanjunh/elasticsearch,xuzha/elasticsearch,camilojd/elasticsearch,umeshdangat/elasticsearch,artnowo/elasticsearch,Helen-Zhao/elasticsearch,fernandozhu/elasticsearch,caengcjd/elasticsearch,cnfire/elasticsearch-1,sneivandt/elasticsearch,maddin2016/elasticsearch,wbowling/elasticsearch,myelin/elasticsearch,camilojd/elasticsearch,rmuir/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,polyfractal/elasticsearch,HonzaKral/elasticsearch,huanzhong/elasticsearch,mnylen/elasticsearch,myelin/elasticsearch,AndreKR/elasticsearch,gfyoung/elasticsearch,wbowling/elasticsearch,vietlq/elasticsearch,ZTE-PaaS/elasticsearch,bestwpw/elasticsearch,onegambler/elasticsearch,obourgain/elasticsearch,YosuaMichael/elasticsearch,Collaborne/elasticsearch,lks21c/elasticsearch,fforbeck/elasticsearch,ricardocerq/elasticsearch,pozhidaevak/elasticsearch,Collaborne/elasticsearch,weipinghe/elasticsearch,davidvgalbraith/elasticsearch,andrejserafim/elasticsearch,zkidkid/elasticsearch,episerver/elasticsearch,glefloch/elasticsearch,rhoml/elasticsearch,wuranbo/elasticsearch,umeshdangat/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Shepard1212/elasticsearch,sdauletau/elasticsearch,markwalkom/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,cwurm/elasticsearch,jchampion/elasticsearch,PhaedrusTheGreek/elasticsearch,gfyoung/elasticsearch,ouyangkongtong/elasticsearch,naveenhooda2000/elasticsearch,shreejay/elasticsearch,MetSystem/elasticsearch,YosuaMichael/elasticsearch,areek/elasticsearch,IanvsPoplicola/elasticsearch,cnfire/elasticsearch-1,lks21c/elasticsearch,artnowo/elasticsearch,wbowling/elasticsearch,girirajsharma/elasticsearch,MisterAndersen/elasticsearch,markharwood/elasticsearch,clintongormley/elasticsearch,Rygbee/elasticsearch,nellicus/elasticsearch,avikurapati/elasticsearch,StefanGor/elasticsearch,lzo/elasticsearch-1,mapr/elasticsearch,onegambler/elasticsearch,martinstuga/elasticsearch,Helen-Zhao/elasticsearch,qwerty4030/elasticsearch,markwalkom/elasticsearch,mjason3/elasticsearch,GlenRSmith/elasticsearch,ouyangkongtong/elasticsearch,sreeramjayan/elasticsearch,ivansun1010/elasticsearch,Rygbee/elasticsearch,yynil/elasticsearch,strapdata/elassandra,robin13/elasticsearch,lks21c/elasticsearch,caengcjd/elasticsearch,maddin2016/elasticsearch,dongjoon-hyun/elasticsearch,LeoYao/elasticsearch,jchampion/elasticsearch,ThiagoGarciaAlves/elasticsearch,trangvh/elasticsearch,jbertouch/elasticsearch,naveenhooda2000/elasticsearch,nezirus/elasticsearch,geidies/elasticsearch,kaneshin/elasticsearch,ulkas/elasticsearch,franklanganke/elasticsearch,vietlq/elasticsearch,wenpos/elasticsearch,wangtuo/elasticsearch,MetSystem/elasticsearch,ivansun1010/elasticsearch,rlugojr/elasticsearch,weipinghe/elasticsearch,JSCooke/elasticsearch,HonzaKral/elasticsearch,StefanGor/elasticsearch,mjason3/elasticsearch,MichaelLiZhou/elasticsearch,mgalushka/elasticsearch,ricardocerq/elasticsearch,achow/elasticsearch,wuranbo/elasticsearch,kalimatas/elasticsearch,andrejserafim/elasticsearch,jeteve/elasticsearch,Charlesdong/elasticsearch,awislowski/elasticsearch,nellicus/elasticsearch,rmuir/elasticsearch,ThiagoGarciaAlves/elasticsearch,mgalushka/elasticsearch,franklanganke/elasticsearch,mcku/elasticsearch,cnfire/elasticsearch-1,socialrank/elasticsearch,onegambler/elasticsearch,fred84/elasticsearch,kaneshin/elasticsearch,Stacey-Gammon/elasticsearch,mbrukman/elasticsearch,petabytedata/elasticsearch,ivansun1010/elasticsearch,MetSystem/elasticsearch,Collaborne/elasticsearch,glefloch/elasticsearch,girirajsharma/elasticsearch,jpountz/elasticsearch,snikch/elasticsearch,PhaedrusTheGreek/elasticsearch,YosuaMichael/elasticsearch,kalburgimanjunath/elasticsearch,nazarewk/elasticsearch,mohit/elasticsearch,vroyer/elassandra,rmuir/elasticsearch,xuzha/elasticsearch,yynil/elasticsearch,a2lin/elasticsearch,rhoml/elasticsearch,bawse/elasticsearch,geidies/elasticsearch,snikch/elasticsearch,strapdata/elassandra5-rc,elancom/elasticsearch,sneivandt/elasticsearch,LeoYao/elasticsearch,MaineC/elasticsearch,awislowski/elasticsearch,infusionsoft/elasticsearch,trangvh/elasticsearch,MisterAndersen/elasticsearch,cnfire/elasticsearch-1,rajanm/elasticsearch,sdauletau/elasticsearch,rhoml/elasticsearch,mgalushka/elasticsearch,ESamir/elasticsearch,schonfeld/elasticsearch,fred84/elasticsearch,mgalushka/elasticsearch,Collaborne/elasticsearch,clintongormley/elasticsearch,tebriel/elasticsearch,jbertouch/elasticsearch,robin13/elasticsearch,brandonkearby/elasticsearch,jango2015/elasticsearch,MaineC/elasticsearch,ulkas/elasticsearch,mjason3/elasticsearch,wangtuo/elasticsearch,lmtwga/elasticsearch,vroyer/elassandra,PhaedrusTheGreek/elasticsearch,fforbeck/elasticsearch,fred84/elasticsearch,umeshdangat/elasticsearch,Stacey-Gammon/elasticsearch,wenpos/elasticsearch,PhaedrusTheGreek/elasticsearch,schonfeld/elasticsearch,hafkensite/elasticsearch,brandonkearby/elasticsearch,mcku/elasticsearch,jango2015/elasticsearch,nilabhsagar/elasticsearch,henakamaMSFT/elasticsearch,jimczi/elasticsearch,LeoYao/elasticsearch,ZTE-PaaS/elasticsearch,spiegela/elasticsearch,diendt/elasticsearch,camilojd/elasticsearch,trangvh/elasticsearch,mohit/elasticsearch,avikurapati/elasticsearch,kalburgimanjunath/elasticsearch,F0lha/elasticsearch,jpountz/elasticsearch,cnfire/elasticsearch-1,areek/elasticsearch,wuranbo/elasticsearch,kunallimaye/elasticsearch,hafkensite/elasticsearch,ESamir/elasticsearch,Shepard1212/elasticsearch,brandonkearby/elasticsearch,Rygbee/elasticsearch,coding0011/elasticsearch,franklanganke/elasticsearch,obourgain/elasticsearch,JervyShi/elasticsearch,nrkkalyan/elasticsearch,kalburgimanjunath/elasticsearch,karthikjaps/elasticsearch,sreeramjayan/elasticsearch,kunallimaye/elasticsearch,mnylen/elasticsearch,fred84/elasticsearch,ricardocerq/elasticsearch,jbertouch/elasticsearch,glefloch/elasticsearch,jchampion/elasticsearch,dongjoon-hyun/elasticsearch,elancom/elasticsearch,mmaracic/elasticsearch,gingerwizard/elasticsearch,liweinan0423/elasticsearch,avikurapati/elasticsearch,infusionsoft/elasticsearch,wuranbo/elasticsearch,JackyMai/elasticsearch,scorpionvicky/elasticsearch,ulkas/elasticsearch,sdauletau/elasticsearch,mapr/elasticsearch,kunallimaye/elasticsearch,Shepard1212/elasticsearch,sreeramjayan/elasticsearch,GlenRSmith/elasticsearch,lzo/elasticsearch-1,jeteve/elasticsearch,sreeramjayan/elasticsearch,mmaracic/elasticsearch,Rygbee/elasticsearch,socialrank/elasticsearch,obourgain/elasticsearch,mm0/elasticsearch,socialrank/elasticsearch,polyfractal/elasticsearch,JervyShi/elasticsearch,jpountz/elasticsearch,caengcjd/elasticsearch,jpountz/elasticsearch,andrestc/elasticsearch,camilojd/elasticsearch,alexshadow007/elasticsearch,LewayneNaidoo/elasticsearch,rhoml/elasticsearch,mcku/elasticsearch,markharwood/elasticsearch,dongjoon-hyun/elasticsearch,rajanm/elasticsearch,areek/elasticsearch,rmuir/elasticsearch,gmarz/elasticsearch,adrianbk/elasticsearch,bawse/elasticsearch,C-Bish/elasticsearch,scorpionvicky/elasticsearch,ESamir/elasticsearch,schonfeld/elasticsearch,schonfeld/elasticsearch,nezirus/elasticsearch,i-am-Nathan/elasticsearch,bestwpw/elasticsearch,mcku/elasticsearch,girirajsharma/elasticsearch,jbertouch/elasticsearch,MaineC/elasticsearch,rhoml/elasticsearch,achow/elasticsearch,shreejay/elasticsearch,henakamaMSFT/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,petabytedata/elasticsearch,mbrukman/elasticsearch,JackyMai/elasticsearch,qwerty4030/elasticsearch,achow/elasticsearch,elasticdog/elasticsearch,njlawton/elasticsearch,polyfractal/elasticsearch,mikemccand/elasticsearch,hafkensite/elasticsearch,Rygbee/elasticsearch,MetSystem/elasticsearch,huanzhong/elasticsearch,xuzha/elasticsearch,Charlesdong/elasticsearch,jango2015/elasticsearch,mm0/elasticsearch,xingguang2013/elasticsearch,masterweb121/elasticsearch,ThiagoGarciaAlves/elasticsearch,scottsom/elasticsearch,F0lha/elasticsearch,lmtwga/elasticsearch,jango2015/elasticsearch,mbrukman/elasticsearch,polyfractal/elasticsearch,awislowski/elasticsearch,JackyMai/elasticsearch,ivansun1010/elasticsearch,yynil/elasticsearch,nomoa/elasticsearch,mm0/elasticsearch,strapdata/elassandra5-rc,episerver/elasticsearch,tebriel/elasticsearch,yynil/elasticsearch,mm0/elasticsearch,adrianbk/elasticsearch,hafkensite/elasticsearch,socialrank/elasticsearch,ThiagoGarciaAlves/elasticsearch,gingerwizard/elasticsearch,andrestc/elasticsearch,martinstuga/elasticsearch,huanzhong/elasticsearch,artnowo/elasticsearch,sreeramjayan/elasticsearch,scottsom/elasticsearch,nellicus/elasticsearch,MichaelLiZhou/elasticsearch,xingguang2013/elasticsearch,ulkas/elasticsearch,jimczi/elasticsearch,weipinghe/elasticsearch,JervyShi/elasticsearch,wenpos/elasticsearch,adrianbk/elasticsearch,xingguang2013/elasticsearch,coding0011/elasticsearch,huanzhong/elasticsearch,nrkkalyan/elasticsearch,elasticdog/elasticsearch,bawse/elasticsearch,clintongormley/elasticsearch,rajanm/elasticsearch,nazarewk/elasticsearch,scorpionvicky/elasticsearch,rlugojr/elasticsearch,elancom/elasticsearch,StefanGor/elasticsearch,andrestc/elasticsearch,MaineC/elasticsearch,onegambler/elasticsearch,LeoYao/elasticsearch,kalimatas/elasticsearch,JackyMai/elasticsearch,jeteve/elasticsearch,ZTE-PaaS/elasticsearch,vroyer/elasticassandra,vietlq/elasticsearch,mapr/elasticsearch,KimTaehee/elasticsearch,kunallimaye/elasticsearch,masterweb121/elasticsearch,xingguang2013/elasticsearch,mortonsykes/elasticsearch,spiegela/elasticsearch,elancom/elasticsearch,mmaracic/elasticsearch,winstonewert/elasticsearch,scottsom/elasticsearch,huanzhong/elasticsearch,gingerwizard/elasticsearch,a2lin/elasticsearch,zkidkid/elasticsearch,yanjunh/elasticsearch,masterweb121/elasticsearch,winstonewert/elasticsearch,jpountz/elasticsearch,girirajsharma/elasticsearch,onegambler/elasticsearch,infusionsoft/elasticsearch,huanzhong/elasticsearch,mikemccand/elasticsearch,davidvgalbraith/elasticsearch,markwalkom/elasticsearch,lks21c/elasticsearch,a2lin/elasticsearch,diendt/elasticsearch,achow/elasticsearch,wuranbo/elasticsearch,elasticdog/elasticsearch,kalburgimanjunath/elasticsearch,masaruh/elasticsearch,alexshadow007/elasticsearch,coding0011/elasticsearch,onegambler/elasticsearch,lmtwga/elasticsearch,wenpos/elasticsearch,awislowski/elasticsearch,snikch/elasticsearch,snikch/elasticsearch,drewr/elasticsearch,markharwood/elasticsearch,mgalushka/elasticsearch,jpountz/elasticsearch,jchampion/elasticsearch,pozhidaevak/elasticsearch,StefanGor/elasticsearch,artnowo/elasticsearch,vietlq/elasticsearch,robin13/elasticsearch,i-am-Nathan/elasticsearch,diendt/elasticsearch,snikch/elasticsearch,nilabhsagar/elasticsearch,mm0/elasticsearch,bestwpw/elasticsearch,gmarz/elasticsearch,bestwpw/elasticsearch,njlawton/elasticsearch,a2lin/elasticsearch,dpursehouse/elasticsearch,caengcjd/elasticsearch,MichaelLiZhou/elasticsearch,nellicus/elasticsearch,nazarewk/elasticsearch,ulkas/elasticsearch,PhaedrusTheGreek/elasticsearch,kalimatas/elasticsearch,xuzha/elasticsearch,MetSystem/elasticsearch,awislowski/elasticsearch,KimTaehee/elasticsearch,gfyoung/elasticsearch,brandonkearby/elasticsearch,pozhidaevak/elasticsearch,kalburgimanjunath/elasticsearch,mapr/elasticsearch,martinstuga/elasticsearch,LeoYao/elasticsearch,mnylen/elasticsearch,hafkensite/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,camilojd/elasticsearch,masaruh/elasticsearch,ouyangkongtong/elasticsearch,mapr/elasticsearch,iacdingping/elasticsearch,schonfeld/elasticsearch,shreejay/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,adrianbk/elasticsearch,elancom/elasticsearch,LewayneNaidoo/elasticsearch,JSCooke/elasticsearch,gingerwizard/elasticsearch,naveenhooda2000/elasticsearch,liweinan0423/elasticsearch,naveenhooda2000/elasticsearch,kalburgimanjunath/elasticsearch,mnylen/elasticsearch,karthikjaps/elasticsearch,s1monw/elasticsearch,JervyShi/elasticsearch,areek/elasticsearch,jimczi/elasticsearch,dongjoon-hyun/elasticsearch,Charlesdong/elasticsearch,nknize/elasticsearch,scottsom/elasticsearch,ZTE-PaaS/elasticsearch,Collaborne/elasticsearch,socialrank/elasticsearch,jeteve/elasticsearch,wenpos/elasticsearch,mmaracic/elasticsearch,episerver/elasticsearch,brandonkearby/elasticsearch,tebriel/elasticsearch,GlenRSmith/elasticsearch,nrkkalyan/elasticsearch,mcku/elasticsearch,Stacey-Gammon/elasticsearch,MichaelLiZhou/elasticsearch,robin13/elasticsearch,tebriel/elasticsearch,kaneshin/elasticsearch,caengcjd/elasticsearch,mbrukman/elasticsearch
|
java
|
## Code Before:
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the 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.elasticsearch.bootstrap;
import java.util.Collections;
import java.util.Set;
/**
* Exposes system startup information
*/
public final class BootstrapInfo {
/** no instantiation */
private BootstrapInfo() {}
/**
* Returns true if we successfully loaded native libraries.
* <p>
* If this returns false, then native operations such as locking
* memory did not work.
*/
public static boolean isNativesAvailable() {
return Natives.JNA_AVAILABLE;
}
/**
* Returns true if we were able to lock the process's address space.
*/
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
/**
* Returns set of insecure plugins.
* <p>
* These are plugins with unresolved issues in third-party libraries,
* that require additional privileges as a workaround.
*/
public static Set<String> getInsecurePluginList() {
return Collections.unmodifiableSet(Security.SPECIAL_PLUGINS.keySet());
}
}
## Instruction:
Remove this: we are gonna manage these right
## Code After:
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the 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.elasticsearch.bootstrap;
/**
* Exposes system startup information
*/
public final class BootstrapInfo {
/** no instantiation */
private BootstrapInfo() {}
/**
* Returns true if we successfully loaded native libraries.
* <p>
* If this returns false, then native operations such as locking
* memory did not work.
*/
public static boolean isNativesAvailable() {
return Natives.JNA_AVAILABLE;
}
/**
* Returns true if we were able to lock the process's address space.
*/
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
}
|
# ... existing code ...
*/
package org.elasticsearch.bootstrap;
/**
* Exposes system startup information
# ... modified code ...
public static boolean isMemoryLocked() {
return Natives.isMemoryLocked();
}
}
# ... rest of the code ...
|
c61929f0d0d8dbf53ef3c9ff2a98cf8f249bfca4
|
handlers/base_handler.py
|
handlers/base_handler.py
|
from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
if offset < 0:
raise IndexError("File offset must be greater than 0")
if offset + size >= len(self.file):
raise IndexError("Cannot read beyond the end of the file")
return self.file[offset:offset + size]
|
from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
|
Revert "Add bounds checking to BaseHandler.read()"
|
Revert "Add bounds checking to BaseHandler.read()"
This reverts commit 045ead44ef69d6ebf2cb0dddf084762efcc62995.
|
Python
|
mit
|
drx/rom-info
|
python
|
## Code Before:
from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
if offset < 0:
raise IndexError("File offset must be greater than 0")
if offset + size >= len(self.file):
raise IndexError("Cannot read beyond the end of the file")
return self.file[offset:offset + size]
## Instruction:
Revert "Add bounds checking to BaseHandler.read()"
This reverts commit 045ead44ef69d6ebf2cb0dddf084762efcc62995.
## Code After:
from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
|
...
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
...
|
4d1d2e12d8882084ce8deb80c3b3e162cc71b20b
|
osmaxx-py/osmaxx/excerptexport/forms/new_excerpt_form.py
|
osmaxx-py/osmaxx/excerptexport/forms/new_excerpt_form.py
|
from django import forms
from django.utils.translation import gettext_lazy
class NewExcerptForm(forms.Form):
new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name'))
new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North'))
new_excerpt_bounding_box_west = forms.CharField(label=gettext_lazy('West'))
new_excerpt_bounding_box_east = forms.CharField(label=gettext_lazy('East'))
new_excerpt_bounding_box_south = forms.CharField(label=gettext_lazy('South'))
new_excerpt_is_public = forms.BooleanField(label=gettext_lazy('Public'))
|
from django import forms
from django.utils.translation import gettext_lazy
class NewExcerptForm(forms.Form):
new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name'))
new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North'))
new_excerpt_bounding_box_west = forms.CharField(label=gettext_lazy('West'))
new_excerpt_bounding_box_east = forms.CharField(label=gettext_lazy('East'))
new_excerpt_bounding_box_south = forms.CharField(label=gettext_lazy('South'))
new_excerpt_is_public = forms.BooleanField(label=gettext_lazy('Public'), required=False)
|
Allow private excerpts (form validation)
|
Bugfix: Allow private excerpts (form validation)
|
Python
|
mit
|
geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend
|
python
|
## Code Before:
from django import forms
from django.utils.translation import gettext_lazy
class NewExcerptForm(forms.Form):
new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name'))
new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North'))
new_excerpt_bounding_box_west = forms.CharField(label=gettext_lazy('West'))
new_excerpt_bounding_box_east = forms.CharField(label=gettext_lazy('East'))
new_excerpt_bounding_box_south = forms.CharField(label=gettext_lazy('South'))
new_excerpt_is_public = forms.BooleanField(label=gettext_lazy('Public'))
## Instruction:
Bugfix: Allow private excerpts (form validation)
## Code After:
from django import forms
from django.utils.translation import gettext_lazy
class NewExcerptForm(forms.Form):
new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name'))
new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North'))
new_excerpt_bounding_box_west = forms.CharField(label=gettext_lazy('West'))
new_excerpt_bounding_box_east = forms.CharField(label=gettext_lazy('East'))
new_excerpt_bounding_box_south = forms.CharField(label=gettext_lazy('South'))
new_excerpt_is_public = forms.BooleanField(label=gettext_lazy('Public'), required=False)
|
...
new_excerpt_bounding_box_west = forms.CharField(label=gettext_lazy('West'))
new_excerpt_bounding_box_east = forms.CharField(label=gettext_lazy('East'))
new_excerpt_bounding_box_south = forms.CharField(label=gettext_lazy('South'))
new_excerpt_is_public = forms.BooleanField(label=gettext_lazy('Public'), required=False)
...
|
4b46ecb6304527b38d0c2f8951b996f8d28f0bff
|
config/freetype2/__init__.py
|
config/freetype2/__init__.py
|
import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OSError:
pass
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not conf.CheckOSXFramework('CoreServices'):
raise Exception('Need CoreServices framework')
conf.CBRequireCHeader('ft2build.h')
conf.CBRequireLib('freetype')
conf.CBConfig('zlib')
conf.CBCheckLib('png')
return True
def generate(env):
env.CBAddConfigTest('freetype2', configure)
env.CBLoadTools('osx zlib')
def exists():
return 1
|
import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OSError:
try:
env.ParseConfig('freetype-config --cflags')
except OSError:
pass
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not conf.CheckOSXFramework('CoreServices'):
raise Exception('Need CoreServices framework')
conf.CBRequireCHeader('ft2build.h')
conf.CBRequireLib('freetype')
conf.CBConfig('zlib')
conf.CBCheckLib('png')
return True
def generate(env):
env.CBAddConfigTest('freetype2', configure)
env.CBLoadTools('osx zlib')
def exists():
return 1
|
Add fallback to freetype-config for compatibility.
|
Add fallback to freetype-config for compatibility.
|
Python
|
lgpl-2.1
|
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
|
python
|
## Code Before:
import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OSError:
pass
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not conf.CheckOSXFramework('CoreServices'):
raise Exception('Need CoreServices framework')
conf.CBRequireCHeader('ft2build.h')
conf.CBRequireLib('freetype')
conf.CBConfig('zlib')
conf.CBCheckLib('png')
return True
def generate(env):
env.CBAddConfigTest('freetype2', configure)
env.CBLoadTools('osx zlib')
def exists():
return 1
## Instruction:
Add fallback to freetype-config for compatibility.
## Code After:
import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OSError:
try:
env.ParseConfig('freetype-config --cflags')
except OSError:
pass
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not conf.CheckOSXFramework('CoreServices'):
raise Exception('Need CoreServices framework')
conf.CBRequireCHeader('ft2build.h')
conf.CBRequireLib('freetype')
conf.CBConfig('zlib')
conf.CBCheckLib('png')
return True
def generate(env):
env.CBAddConfigTest('freetype2', configure)
env.CBLoadTools('osx zlib')
def exists():
return 1
|
...
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OSError:
try:
env.ParseConfig('freetype-config --cflags')
except OSError:
pass
if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)):
if not conf.CheckOSXFramework('CoreServices'):
...
|
3c735d18bdcff28bbdd765b131649ba57fb612b0
|
hy/models/string.py
|
hy/models/string.py
|
from hy.models import HyObject
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
class HyString(HyObject, str_type):
"""
Generic Hy String object. Helpful to store string literals from Hy
scripts. It's either a ``str`` or a ``unicode``, depending on the
Python version.
"""
def __new__(cls, value):
obj = str_type.__new__(cls, value)
return obj
|
from hy.models import HyObject
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
class HyString(HyObject, str_type):
"""
Generic Hy String object. Helpful to store string literals from Hy
scripts. It's either a ``str`` or a ``unicode``, depending on the
Python version.
"""
pass
|
Revert "Revert "Remove useless code""
|
Revert "Revert "Remove useless code""
This reverts commit 262da59c7790cdadd60ea9612bc9e3c1616863fd.
Conflicts:
hy/models/string.py
|
Python
|
mit
|
ALSchwalm/hy,aisk/hy,paultag/hy,tianon/hy,hcarvalhoalves/hy,Foxboron/hy,Tritlo/hy,mtmiller/hy,michel-slm/hy,farhaven/hy,freezas/hy,zackmdavis/hy,tianon/hy,gilch/hy,aisk/hy,larme/hy,tuturto/hy,timmartin/hy,farhaven/hy,kirbyfan64/hy,farhaven/hy,algernon/hy,Foxboron/hy,hcarvalhoalves/hy,kirbyfan64/hy,adamfeuer/hy,jakirkham/hy,tianon/hy,larme/hy,larme/hy,kartikm/hy,aisk/hy
|
python
|
## Code Before:
from hy.models import HyObject
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
class HyString(HyObject, str_type):
"""
Generic Hy String object. Helpful to store string literals from Hy
scripts. It's either a ``str`` or a ``unicode``, depending on the
Python version.
"""
def __new__(cls, value):
obj = str_type.__new__(cls, value)
return obj
## Instruction:
Revert "Revert "Remove useless code""
This reverts commit 262da59c7790cdadd60ea9612bc9e3c1616863fd.
Conflicts:
hy/models/string.py
## Code After:
from hy.models import HyObject
import sys
if sys.version_info[0] >= 3:
str_type = str
else:
str_type = unicode
class HyString(HyObject, str_type):
"""
Generic Hy String object. Helpful to store string literals from Hy
scripts. It's either a ``str`` or a ``unicode``, depending on the
Python version.
"""
pass
|
# ... existing code ...
scripts. It's either a ``str`` or a ``unicode``, depending on the
Python version.
"""
pass
# ... rest of the code ...
|
923d49c753acf7d8945d6b79efbdb08363e130a2
|
noseprogressive/tests/test_utils.py
|
noseprogressive/tests/test_utils.py
|
from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
|
from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), NotImplementedError,
NotImplementedError(), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
|
Bring test_frame_of_test_null_file up to date with new signature of frame_of_test().
|
Bring test_frame_of_test_null_file up to date with new signature of frame_of_test().
|
Python
|
mit
|
pmclanahan/pytest-progressive,erikrose/nose-progressive,veo-labs/nose-progressive,olivierverdier/nose-progressive
|
python
|
## Code Before:
from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
## Instruction:
Bring test_frame_of_test_null_file up to date with new signature of frame_of_test().
## Code After:
from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), NotImplementedError,
NotImplementedError(), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
|
...
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), NotImplementedError,
NotImplementedError(), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
...
|
5141826b24641572fddd06bfe376eddba2e3ff69
|
src/main/java/algorithms/MaxPairwiseProduct.java
|
src/main/java/algorithms/MaxPairwiseProduct.java
|
package algorithms;
import java.util.Arrays;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Arrays.sort(numbers, (x, y) -> x - y);
int lastIndex = numbers.length - 1;
long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
return bigResult;
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
|
package algorithms;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Integer maxIndex1 = null;
Integer maxIndex2 = null;
for (int i = 0; i < numbers.length; ++i) {
if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
maxIndex2 = maxIndex1;
maxIndex1 = i;
} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
maxIndex2 = i;
}
}
return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
|
Improve efficiency to constant O(n)
|
Improve efficiency to constant O(n)
|
Java
|
mit
|
bink81/java-experiments
|
java
|
## Code Before:
package algorithms;
import java.util.Arrays;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Arrays.sort(numbers, (x, y) -> x - y);
int lastIndex = numbers.length - 1;
long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
return bigResult;
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
## Instruction:
Improve efficiency to constant O(n)
## Code After:
package algorithms;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Integer maxIndex1 = null;
Integer maxIndex2 = null;
for (int i = 0; i < numbers.length; ++i) {
if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
maxIndex2 = maxIndex1;
maxIndex1 = i;
} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
maxIndex2 = i;
}
}
return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
|
...
package algorithms;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
...
if (numbers.length == 1) {
return 0;
}
Integer maxIndex1 = null;
Integer maxIndex2 = null;
for (int i = 0; i < numbers.length; ++i) {
if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
maxIndex2 = maxIndex1;
maxIndex1 = i;
} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
maxIndex2 = i;
}
}
return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
}
public static void main(String[] args) {
...
|
9014dfde50d5f54cf79c544ce01e81266effa87d
|
game_info/tests/test_commands.py
|
game_info/tests/test_commands.py
|
from django.core.management import call_command
from django.test import TestCase
class ServerTest(TestCase):
def test_update_game_info(self):
call_command('update_game_info')
|
from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server
class ServerTest(TestCase):
def create_server(self, title="Test Server", host="example.org", port=27015):
return Server.objects.create(title=title, host=host, port=port)
def test_update_game_info(self):
self.create_server().save()
call_command('update_game_info')
|
Fix testing on update_game_info management command
|
Fix testing on update_game_info management command
|
Python
|
bsd-3-clause
|
Azelphur-Servers/django-game-info
|
python
|
## Code Before:
from django.core.management import call_command
from django.test import TestCase
class ServerTest(TestCase):
def test_update_game_info(self):
call_command('update_game_info')
## Instruction:
Fix testing on update_game_info management command
## Code After:
from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server
class ServerTest(TestCase):
def create_server(self, title="Test Server", host="example.org", port=27015):
return Server.objects.create(title=title, host=host, port=port)
def test_update_game_info(self):
self.create_server().save()
call_command('update_game_info')
|
// ... existing code ...
from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server
class ServerTest(TestCase):
def create_server(self, title="Test Server", host="example.org", port=27015):
return Server.objects.create(title=title, host=host, port=port)
def test_update_game_info(self):
self.create_server().save()
call_command('update_game_info')
// ... rest of the code ...
|
0c25bef5514913239db942d96a00a499144282c0
|
tests/test_config.py
|
tests/test_config.py
|
from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
assert isinstance(incomplete_config.riemann, RiemannConfig)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
|
from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
obj = incomplete_config.riemann
assert isinstance(obj, RiemannConfig)
assert isinstance(obj._data, dict)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
|
Check more data about riemann
|
Check more data about riemann
|
Python
|
mit
|
CodersOfTheNight/oshino
|
python
|
## Code Before:
from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
assert isinstance(incomplete_config.riemann, RiemannConfig)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
## Instruction:
Check more data about riemann
## Code After:
from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
obj = incomplete_config.riemann
assert isinstance(obj, RiemannConfig)
assert isinstance(obj._data, dict)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
|
...
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
obj = incomplete_config.riemann
assert isinstance(obj, RiemannConfig)
assert isinstance(obj._data, dict)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
...
|
d5f782fc7a8c7835af0d4d2810a923d218dea938
|
mplwidget.py
|
mplwidget.py
|
from PyQt4 import QtGui
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def resizeEvent(self, event):
FigureCanvas.resizeEvent(self, event)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.canvas.setParent(self)
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
|
from PyQt4 import QtGui,QtCore
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def sizeHint(self):
w, h = self.get_width_height()
return QtCore.QSize(w,h)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self.canvas)
|
Expand figure when window is resized
|
Expand figure when window is resized
|
Python
|
apache-2.0
|
scholi/pyOmicron
|
python
|
## Code Before:
from PyQt4 import QtGui
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def resizeEvent(self, event):
FigureCanvas.resizeEvent(self, event)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.canvas.setParent(self)
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
## Instruction:
Expand figure when window is resized
## Code After:
from PyQt4 import QtGui,QtCore
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def sizeHint(self):
w, h = self.get_width_height()
return QtCore.QSize(w,h)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self.canvas)
|
// ... existing code ...
from PyQt4 import QtGui,QtCore
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
// ... modified code ...
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def sizeHint(self):
w, h = self.get_width_height()
return QtCore.QSize(w,h)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self.canvas)
// ... rest of the code ...
|
62a5d2db5c0ff5e96d66d91bfaa6a35ef9a0ef94
|
src/main/java/com/gmail/nossr50/listeners/HardcoreListener.java
|
src/main/java/com/gmail/nossr50/listeners/HardcoreListener.java
|
package com.gmail.nossr50.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
public class HardcoreListener implements Listener {
/**
* Monitor PlayerDeath events.
*
* @param event The event to monitor
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (Misc.isNPCPlayer(player)) {
return;
}
if (!Permissions.hardcoremodeBypass(player)) {
Player killer = player.getKiller();
if (killer != null && Hardcore.vampirismEnabled) {
Hardcore.invokeVampirism(killer, player);
}
Hardcore.invokeStatPenalty(player);
}
}
}
|
package com.gmail.nossr50.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
public class HardcoreListener implements Listener {
/**
* Monitor PlayerDeath events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (Misc.isNPCPlayer(player)) {
return;
}
if (!Permissions.hardcoremodeBypass(player)) {
Player killer = player.getKiller();
if (killer != null && Hardcore.vampirismEnabled) {
Hardcore.invokeVampirism(killer, player);
}
Hardcore.invokeStatPenalty(player);
}
}
}
|
Make sure we ignore cancelled events.
|
Make sure we ignore cancelled events.
|
Java
|
agpl-3.0
|
EvilOlaf/mcMMO,jhonMalcom79/mcMMO_pers,isokissa3/mcMMO,Maximvdw/mcMMO,virustotalop/mcMMO
|
java
|
## Code Before:
package com.gmail.nossr50.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
public class HardcoreListener implements Listener {
/**
* Monitor PlayerDeath events.
*
* @param event The event to monitor
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (Misc.isNPCPlayer(player)) {
return;
}
if (!Permissions.hardcoremodeBypass(player)) {
Player killer = player.getKiller();
if (killer != null && Hardcore.vampirismEnabled) {
Hardcore.invokeVampirism(killer, player);
}
Hardcore.invokeStatPenalty(player);
}
}
}
## Instruction:
Make sure we ignore cancelled events.
## Code After:
package com.gmail.nossr50.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
public class HardcoreListener implements Listener {
/**
* Monitor PlayerDeath events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (Misc.isNPCPlayer(player)) {
return;
}
if (!Permissions.hardcoremodeBypass(player)) {
Player killer = player.getKiller();
if (killer != null && Hardcore.vampirismEnabled) {
Hardcore.invokeVampirism(killer, player);
}
Hardcore.invokeStatPenalty(player);
}
}
}
|
...
/**
* Monitor PlayerDeath events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
...
|
5923d751d9541758a67915db67ee799ba0d1cd6d
|
polling_stations/api/mixins.py
|
polling_stations/api/mixins.py
|
from rest_framework.decorators import list_route
from rest_framework.response import Response
class PollingEntityMixin():
def output(self, request):
if not self.validate_request():
return Response(
{'detail': 'council_id parameter must be specified'}, 400)
queryset = self.get_queryset()
serializer = self.get_serializer(
queryset, many=True, read_only=True, context={'request': request})
return Response(serializer.data)
def list(self, request, *args, **kwargs):
self.geo = False
return self.output(request)
@list_route(url_path='geo')
def geo(self, request, format=None):
self.geo = True
return self.output(request)
|
from rest_framework.decorators import list_route
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
class LargeResultsSetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 1000
class PollingEntityMixin():
pagination_class = LargeResultsSetPagination
def output(self, request):
if not self.validate_request():
return Response(
{'detail': 'council_id parameter must be specified'}, 400)
queryset = self.get_queryset()
if 'council_id' not in request.query_params:
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(
page,
many=True,
read_only=True,
context={'request': request}
)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(
queryset,
many=True,
read_only=True,
context={'request': request}
)
return Response(serializer.data)
def list(self, request, *args, **kwargs):
self.geo = False
return self.output(request)
@list_route(url_path='geo')
def geo(self, request, format=None):
self.geo = True
return self.output(request)
|
Use pagination on stations and districts endpoints with no filter
|
Use pagination on stations and districts endpoints with no filter
If no filter is passed to /pollingstations or /pollingdistricts
use pagination (when filtering, there is no pagination)
This means:
- HTML outputs stay responsive/useful
- People can't tie up our server with a query that says
'give me boundaries for all polling districts in the country'
|
Python
|
bsd-3-clause
|
chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
|
python
|
## Code Before:
from rest_framework.decorators import list_route
from rest_framework.response import Response
class PollingEntityMixin():
def output(self, request):
if not self.validate_request():
return Response(
{'detail': 'council_id parameter must be specified'}, 400)
queryset = self.get_queryset()
serializer = self.get_serializer(
queryset, many=True, read_only=True, context={'request': request})
return Response(serializer.data)
def list(self, request, *args, **kwargs):
self.geo = False
return self.output(request)
@list_route(url_path='geo')
def geo(self, request, format=None):
self.geo = True
return self.output(request)
## Instruction:
Use pagination on stations and districts endpoints with no filter
If no filter is passed to /pollingstations or /pollingdistricts
use pagination (when filtering, there is no pagination)
This means:
- HTML outputs stay responsive/useful
- People can't tie up our server with a query that says
'give me boundaries for all polling districts in the country'
## Code After:
from rest_framework.decorators import list_route
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
class LargeResultsSetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 1000
class PollingEntityMixin():
pagination_class = LargeResultsSetPagination
def output(self, request):
if not self.validate_request():
return Response(
{'detail': 'council_id parameter must be specified'}, 400)
queryset = self.get_queryset()
if 'council_id' not in request.query_params:
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(
page,
many=True,
read_only=True,
context={'request': request}
)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(
queryset,
many=True,
read_only=True,
context={'request': request}
)
return Response(serializer.data)
def list(self, request, *args, **kwargs):
self.geo = False
return self.output(request)
@list_route(url_path='geo')
def geo(self, request, format=None):
self.geo = True
return self.output(request)
|
...
from rest_framework.decorators import list_route
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
class LargeResultsSetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 1000
class PollingEntityMixin():
pagination_class = LargeResultsSetPagination
def output(self, request):
if not self.validate_request():
...
{'detail': 'council_id parameter must be specified'}, 400)
queryset = self.get_queryset()
if 'council_id' not in request.query_params:
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(
page,
many=True,
read_only=True,
context={'request': request}
)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(
queryset,
many=True,
read_only=True,
context={'request': request}
)
return Response(serializer.data)
def list(self, request, *args, **kwargs):
...
|
beb1a9f08feed88aab8184d405403a8e78c5d47d
|
src/main/java/org/buddycloud/channelserver/pubsub/publishmodel/PublishModels.java
|
src/main/java/org/buddycloud/channelserver/pubsub/publishmodel/PublishModels.java
|
package org.buddycloud.channelserver.pubsub.publishmodel;
public enum PublishModels {
publishers,
subscribers,
open;
public static PublishModels createFromString(String asString) {
if("publishers".equals(asString)) {
return publishers;
} else if ("subscribers".equals(asString)) {
return subscribers;
} else if ("open".equals(asString)) {
return open;
}
return publishers;
}
}
|
package org.buddycloud.channelserver.pubsub.publishmodel;
public enum PublishModels {
owner,
moderator,
publisher,
member,
outcast;
public static PublishModels createFromString(String asString) {
if ("owner".equals(asString)) {
return owner;
} else if ("moderator".equals(asString)) {
return moderator;
} else if ("publisher".equals(asString)) {
return publisher;
} else if ("outcast".equals(asString)) {
return outcast;
}
return member;
}
}
|
Create channels with correct default affiliations
|
Create channels with correct default affiliations
|
Java
|
apache-2.0
|
surevine/buddycloud-server-java,ashward/buddycloud-server-java,enom/buddycloud-server-java,webhost/buddycloud-server-java,buddycloud/buddycloud-server-java,webhost/buddycloud-server-java,buddycloud/buddycloud-server-java,enom/buddycloud-server-java,ashward/buddycloud-server-java,surevine/buddycloud-server-java
|
java
|
## Code Before:
package org.buddycloud.channelserver.pubsub.publishmodel;
public enum PublishModels {
publishers,
subscribers,
open;
public static PublishModels createFromString(String asString) {
if("publishers".equals(asString)) {
return publishers;
} else if ("subscribers".equals(asString)) {
return subscribers;
} else if ("open".equals(asString)) {
return open;
}
return publishers;
}
}
## Instruction:
Create channels with correct default affiliations
## Code After:
package org.buddycloud.channelserver.pubsub.publishmodel;
public enum PublishModels {
owner,
moderator,
publisher,
member,
outcast;
public static PublishModels createFromString(String asString) {
if ("owner".equals(asString)) {
return owner;
} else if ("moderator".equals(asString)) {
return moderator;
} else if ("publisher".equals(asString)) {
return publisher;
} else if ("outcast".equals(asString)) {
return outcast;
}
return member;
}
}
|
# ... existing code ...
public enum PublishModels {
owner,
moderator,
publisher,
member,
outcast;
public static PublishModels createFromString(String asString) {
if ("owner".equals(asString)) {
return owner;
} else if ("moderator".equals(asString)) {
return moderator;
} else if ("publisher".equals(asString)) {
return publisher;
} else if ("outcast".equals(asString)) {
return outcast;
}
return member;
}
}
# ... rest of the code ...
|
cc5d2aa34b4426a290e1807c6dee824a1d10fd73
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = [
'pyramid',
'cornice',
'colander',
'couchdb',
]
test_requires = requires + ['lettuce', ]
setup(name='daybed',
version='0.0',
description='daybed',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="daybed.tests",
entry_points="""\
[paste.app_factory]
main = daybed:main
""",
)
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = [
'pyramid',
'cornice',
'colander',
'couchdb',
]
test_requires = requires + ['lettuce', ]
setup(name='daybed',
version='0.0',
description='daybed',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
dependency_links = [
"https://github.com/mozilla-services/cornice/tarball/spore-support#egg=cornice"
],
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="daybed.tests",
entry_points="""\
[paste.app_factory]
main = daybed:main
""",
)
|
Install the spore branch of cornice
|
Install the spore branch of cornice
|
Python
|
bsd-3-clause
|
spiral-project/daybed,spiral-project/daybed
|
python
|
## Code Before:
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = [
'pyramid',
'cornice',
'colander',
'couchdb',
]
test_requires = requires + ['lettuce', ]
setup(name='daybed',
version='0.0',
description='daybed',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="daybed.tests",
entry_points="""\
[paste.app_factory]
main = daybed:main
""",
)
## Instruction:
Install the spore branch of cornice
## Code After:
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = [
'pyramid',
'cornice',
'colander',
'couchdb',
]
test_requires = requires + ['lettuce', ]
setup(name='daybed',
version='0.0',
description='daybed',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
dependency_links = [
"https://github.com/mozilla-services/cornice/tarball/spore-support#egg=cornice"
],
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=test_requires,
test_suite="daybed.tests",
entry_points="""\
[paste.app_factory]
main = daybed:main
""",
)
|
// ... existing code ...
url='',
keywords='web pyramid pylons',
packages=find_packages(),
dependency_links = [
"https://github.com/mozilla-services/cornice/tarball/spore-support#egg=cornice"
],
include_package_data=True,
zip_safe=False,
install_requires=requires,
// ... rest of the code ...
|
b18e2d7842de719b60e2902f201d745897749c4b
|
mt.h
|
mt.h
|
//#if defined(_MSC_VER) && (_MSC_VER <= 1600) // sufficient
#if defined(_MSC_VER) // better?
typedef unsigned __int32 uint32_t;
#elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(__APPLE__)
#include <stdint.h>
#elif defined(__osf__)
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
enum { N = 624, M = 397 };
struct mt {
uint32_t mt[N];
int mti;
uint32_t seed;
};
struct mt *mt_init(void);
void mt_free(struct mt *self);
uint32_t mt_get_seed(struct mt *self);
void mt_init_seed(struct mt *self, uint32_t seed);
void mt_setup_array(struct mt *self, uint32_t *array, int n);
double mt_genrand(struct mt *self);
#endif
|
typedef unsigned __int32 uint32_t;
#elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(_MSC_VER) || defined(__APPLE__)
#include <stdint.h>
#elif defined(__osf__)
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
enum { N = 624, M = 397 };
struct mt {
uint32_t mt[N];
int mti;
uint32_t seed;
};
struct mt *mt_init(void);
void mt_free(struct mt *self);
uint32_t mt_get_seed(struct mt *self);
void mt_init_seed(struct mt *self, uint32_t seed);
void mt_setup_array(struct mt *self, uint32_t *array, int n);
double mt_genrand(struct mt *self);
#endif
|
Include <stdint.h> for MS Visual Studio 2010 and above
|
Include <stdint.h> for MS Visual Studio 2010 and above
|
C
|
bsd-3-clause
|
amenonsen/Math-Random-MT,amenonsen/Math-Random-MT
|
c
|
## Code Before:
//#if defined(_MSC_VER) && (_MSC_VER <= 1600) // sufficient
#if defined(_MSC_VER) // better?
typedef unsigned __int32 uint32_t;
#elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(__APPLE__)
#include <stdint.h>
#elif defined(__osf__)
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
enum { N = 624, M = 397 };
struct mt {
uint32_t mt[N];
int mti;
uint32_t seed;
};
struct mt *mt_init(void);
void mt_free(struct mt *self);
uint32_t mt_get_seed(struct mt *self);
void mt_init_seed(struct mt *self, uint32_t seed);
void mt_setup_array(struct mt *self, uint32_t *array, int n);
double mt_genrand(struct mt *self);
#endif
## Instruction:
Include <stdint.h> for MS Visual Studio 2010 and above
## Code After:
typedef unsigned __int32 uint32_t;
#elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(_MSC_VER) || defined(__APPLE__)
#include <stdint.h>
#elif defined(__osf__)
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
enum { N = 624, M = 397 };
struct mt {
uint32_t mt[N];
int mti;
uint32_t seed;
};
struct mt *mt_init(void);
void mt_free(struct mt *self);
uint32_t mt_get_seed(struct mt *self);
void mt_init_seed(struct mt *self, uint32_t seed);
void mt_setup_array(struct mt *self, uint32_t *array, int n);
double mt_genrand(struct mt *self);
#endif
|
// ... existing code ...
typedef unsigned __int32 uint32_t;
#elif defined(__linux__) || defined(__GLIBC__) || defined(__WIN32__) || defined(_MSC_VER) || defined(__APPLE__)
#include <stdint.h>
#elif defined(__osf__)
#include <inttypes.h>
// ... rest of the code ...
|
8d217c9797f19d4276484fd070a4a5f3de623e84
|
tapioca_toggl/__init__.py
|
tapioca_toggl/__init__.py
|
__version__ = '0.1.0'
|
__version__ = '0.1.0'
from .tapioca_toggl import Toggl # noqa
|
Make api accessible from python package
|
Make api accessible from python package
|
Python
|
mit
|
hackebrot/tapioca-toggl
|
python
|
## Code Before:
__version__ = '0.1.0'
## Instruction:
Make api accessible from python package
## Code After:
__version__ = '0.1.0'
from .tapioca_toggl import Toggl # noqa
|
// ... existing code ...
__version__ = '0.1.0'
from .tapioca_toggl import Toggl # noqa
// ... rest of the code ...
|
1d32debc1ea2ce8d11c8bc1abad048d6e4937520
|
froide_campaign/listeners.py
|
froide_campaign/listeners.py
|
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
if not ident:
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
Fix non-iobj campaign request connection
|
Fix non-iobj campaign request connection
|
Python
|
mit
|
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
|
python
|
## Code Before:
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
## Instruction:
Fix non-iobj campaign request connection
## Code After:
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
if not ident:
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
// ... existing code ...
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
if not ident:
return
try:
// ... rest of the code ...
|
df47c33fdeac90025ff271293b8fbedcd5010622
|
src/test/java/sherlock/CommitParserTest.java
|
src/test/java/sherlock/CommitParserTest.java
|
package sherlock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
public class CommitParserTest {
public void testA() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("migration-task.diff");
List<String> commits = new CommitParser(is).getCommits().collect(Collectors.toList());
System.out.println(commits);
}
}
|
package sherlock;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import static junit.framework.Assert.assertEquals;
public class CommitParserTest {
public void testA() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("migration-task.diff");
List<String> commits = new CommitParser(is).getCommits().collect(Collectors.toList());
assertEquals(4, commits.size());
}
}
|
Test for SVN commit parser
|
Test for SVN commit parser
|
Java
|
mit
|
antonlogvinenko/sherlock
|
java
|
## Code Before:
package sherlock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
public class CommitParserTest {
public void testA() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("migration-task.diff");
List<String> commits = new CommitParser(is).getCommits().collect(Collectors.toList());
System.out.println(commits);
}
}
## Instruction:
Test for SVN commit parser
## Code After:
package sherlock;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import static junit.framework.Assert.assertEquals;
public class CommitParserTest {
public void testA() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("migration-task.diff");
List<String> commits = new CommitParser(is).getCommits().collect(Collectors.toList());
assertEquals(4, commits.size());
}
}
|
# ... existing code ...
package sherlock;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import static junit.framework.Assert.assertEquals;
public class CommitParserTest {
# ... modified code ...
public void testA() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("migration-task.diff");
List<String> commits = new CommitParser(is).getCommits().collect(Collectors.toList());
assertEquals(4, commits.size());
}
}
# ... rest of the code ...
|
1579eb8d2de5aa49ad7012ab08350659a20725e1
|
basis/managers.py
|
basis/managers.py
|
from django.db import models
class BasisModelManager(models.Manager):
def get_query_set(self):
return super(BasisModelManager, self).get_query_set().filter(deleted=False)
|
from django.db import models
from .compat import DJANGO16
if DJANGO16:
class BasisModelManager(models.Manager):
def get_queryset(self):
return super(BasisModelManager, self).get_queryset().filter(deleted=False)
else:
class BasisModelManager(models.Manager):
def get_query_set(self):
return super(BasisModelManager, self).get_query_set().filter(deleted=False)
|
Fix deprecation warning for get_query_set
|
Fix deprecation warning for get_query_set
get_query_set was renamed get_queryset in django 1.6
|
Python
|
mit
|
frecar/django-basis
|
python
|
## Code Before:
from django.db import models
class BasisModelManager(models.Manager):
def get_query_set(self):
return super(BasisModelManager, self).get_query_set().filter(deleted=False)
## Instruction:
Fix deprecation warning for get_query_set
get_query_set was renamed get_queryset in django 1.6
## Code After:
from django.db import models
from .compat import DJANGO16
if DJANGO16:
class BasisModelManager(models.Manager):
def get_queryset(self):
return super(BasisModelManager, self).get_queryset().filter(deleted=False)
else:
class BasisModelManager(models.Manager):
def get_query_set(self):
return super(BasisModelManager, self).get_query_set().filter(deleted=False)
|
# ... existing code ...
from django.db import models
from .compat import DJANGO16
if DJANGO16:
class BasisModelManager(models.Manager):
def get_queryset(self):
return super(BasisModelManager, self).get_queryset().filter(deleted=False)
else:
class BasisModelManager(models.Manager):
def get_query_set(self):
return super(BasisModelManager, self).get_query_set().filter(deleted=False)
# ... rest of the code ...
|
6bfcfaffcb1695f142c11b6864951f9471e52d60
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
try:
with open("requirements.txt", "r") as f:
install_requires = [x.strip() for x in f.readlines()]
except IOError:
install_requires = []
setup(name="status",
author="Science For Life Laboratory",
author_email="[email protected]",
description="Webapp for keeping track of metadata status at SciLifeLab",
license="MIT",
scripts=["status_app.py"],
install_requires=install_requires,
packages=find_packages()
)
|
from setuptools import setup, find_packages
try:
with open("requirements.txt", "r") as f:
install_requires = [x.strip() for x in f.readlines()]
except IOError:
install_requires = []
setup(name="status",
author="Science For Life Laboratory",
author_email="[email protected]",
description="Webapp for keeping track of metadata status at SciLifeLab",
license="MIT",
scripts=["status_app.py", "scripts/update_suggestion_box"],
install_requires=install_requires,
packages=find_packages()
)
|
Add suggestion box script to PATH
|
Add suggestion box script to PATH
|
Python
|
mit
|
remiolsen/status,remiolsen/status,ewels/genomics-status,ewels/genomics-status,SciLifeLab/genomics-status,SciLifeLab/genomics-status,Galithil/status,Galithil/status,remiolsen/status,ewels/genomics-status,Galithil/status,kate-v-stepanova/genomics-status,kate-v-stepanova/genomics-status,kate-v-stepanova/genomics-status,SciLifeLab/genomics-status
|
python
|
## Code Before:
from setuptools import setup, find_packages
try:
with open("requirements.txt", "r") as f:
install_requires = [x.strip() for x in f.readlines()]
except IOError:
install_requires = []
setup(name="status",
author="Science For Life Laboratory",
author_email="[email protected]",
description="Webapp for keeping track of metadata status at SciLifeLab",
license="MIT",
scripts=["status_app.py"],
install_requires=install_requires,
packages=find_packages()
)
## Instruction:
Add suggestion box script to PATH
## Code After:
from setuptools import setup, find_packages
try:
with open("requirements.txt", "r") as f:
install_requires = [x.strip() for x in f.readlines()]
except IOError:
install_requires = []
setup(name="status",
author="Science For Life Laboratory",
author_email="[email protected]",
description="Webapp for keeping track of metadata status at SciLifeLab",
license="MIT",
scripts=["status_app.py", "scripts/update_suggestion_box"],
install_requires=install_requires,
packages=find_packages()
)
|
...
author_email="[email protected]",
description="Webapp for keeping track of metadata status at SciLifeLab",
license="MIT",
scripts=["status_app.py", "scripts/update_suggestion_box"],
install_requires=install_requires,
packages=find_packages()
)
...
|
9568efceab48f87ed8302ec4f9bad4b15aac4c5a
|
tests/test_action.py
|
tests/test_action.py
|
import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="[email protected]")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
|
import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="[email protected]")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
def test_connection_closed_after_sending_mail(self, mock_smtp_class):
mock_smtp = mock_smtp_class.return_value
self.action.execute("MSFT has crossed $10 price level")
mock_smtp.send_message.assert_called_with(mock.ANY)
self.assertTrue(mock_smtp.quit.called)
mock_smtp.assert_has_calls([
mock.call.send_message(mock.ANY),
mock.call.quit()
])
|
Add test to check if connection is closed after email is sent.
|
Add test to check if connection is closed after email is sent.
|
Python
|
mit
|
bsmukasa/stock_alerter
|
python
|
## Code Before:
import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="[email protected]")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
## Instruction:
Add test to check if connection is closed after email is sent.
## Code After:
import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="[email protected]")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
def test_connection_closed_after_sending_mail(self, mock_smtp_class):
mock_smtp = mock_smtp_class.return_value
self.action.execute("MSFT has crossed $10 price level")
mock_smtp.send_message.assert_called_with(mock.ANY)
self.assertTrue(mock_smtp.quit.called)
mock_smtp.assert_has_calls([
mock.call.send_message(mock.ANY),
mock.call.quit()
])
|
# ... existing code ...
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
def test_connection_closed_after_sending_mail(self, mock_smtp_class):
mock_smtp = mock_smtp_class.return_value
self.action.execute("MSFT has crossed $10 price level")
mock_smtp.send_message.assert_called_with(mock.ANY)
self.assertTrue(mock_smtp.quit.called)
mock_smtp.assert_has_calls([
mock.call.send_message(mock.ANY),
mock.call.quit()
])
# ... rest of the code ...
|
e00dc2a5725faeb3b11c6aac0d9ed0be0a55d33f
|
OIPA/iati/parser/schema_validators.py
|
OIPA/iati/parser/schema_validators.py
|
import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as xml_errors:
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
|
import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as e:
xml_errors = e
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
|
Fix another bug related to logging dataset errors
|
Fix another bug related to logging dataset errors
OIPA-612 / #589
|
Python
|
agpl-3.0
|
openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA
|
python
|
## Code Before:
import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as xml_errors:
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
## Instruction:
Fix another bug related to logging dataset errors
OIPA-612 / #589
## Code After:
import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as e:
xml_errors = e
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
|
// ... existing code ...
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as e:
xml_errors = e
pass
if xml_errors:
// ... rest of the code ...
|
c2fe4483ba70f0ca37b4713a51baf0804a68accd
|
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
|
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
|
from wiki.core.plugins.base import BasePlugin
from wiki.core.plugins import registry as plugin_registry
from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video
class ExtendMarkdownPlugin(BasePlugin):
"""
This plugin simply loads all of the markdown extensions we use in edX.
"""
markdown_extensions = [
mdx_mathjax.MathJaxExtension(configs={}),
mdx_video.VideoExtension(configs={})]
plugin_registry.register(ExtendMarkdownPlugin)
|
from wiki.core.plugins.base import BasePlugin
from wiki.core.plugins import registry as plugin_registry
from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video
class ExtendMarkdownPlugin(BasePlugin):
"""
This plugin simply loads all of the markdown extensions we use in edX.
"""
markdown_extensions = [
mdx_mathjax.MathJaxExtension(configs={}),
mdx_video.VideoExtension(configs={}),
]
plugin_registry.register(ExtendMarkdownPlugin)
|
Fix PEP8: E126 continuation line over-indented
|
Fix PEP8: E126 continuation line over-indented
for hanging indent
|
Python
|
agpl-3.0
|
IndonesiaX/edx-platform,mbareta/edx-platform-ft,proversity-org/edx-platform,IONISx/edx-platform,Edraak/edx-platform,doganov/edx-platform,shabab12/edx-platform,lduarte1991/edx-platform,deepsrijit1105/edx-platform,pomegranited/edx-platform,prarthitm/edxplatform,fintech-circle/edx-platform,prarthitm/edxplatform,waheedahmed/edx-platform,xingyepei/edx-platform,jbzdak/edx-platform,louyihua/edx-platform,TeachAtTUM/edx-platform,stvstnfrd/edx-platform,nttks/edx-platform,cognitiveclass/edx-platform,jjmiranda/edx-platform,Endika/edx-platform,antoviaque/edx-platform,JCBarahona/edX,ampax/edx-platform,zubair-arbi/edx-platform,wwj718/edx-platform,bigdatauniversity/edx-platform,zhenzhai/edx-platform,ahmadiga/min_edx,synergeticsedx/deployment-wipro,doganov/edx-platform,waheedahmed/edx-platform,itsjeyd/edx-platform,waheedahmed/edx-platform,solashirai/edx-platform,miptliot/edx-platform,inares/edx-platform,MakeHer/edx-platform,JCBarahona/edX,edx-solutions/edx-platform,bigdatauniversity/edx-platform,teltek/edx-platform,fintech-circle/edx-platform,amir-qayyum-khan/edx-platform,hamzehd/edx-platform,IONISx/edx-platform,caesar2164/edx-platform,Livit/Livit.Learn.EdX,cpennington/edx-platform,defance/edx-platform,stvstnfrd/edx-platform,amir-qayyum-khan/edx-platform,tanmaykm/edx-platform,eduNEXT/edunext-platform,ahmedaljazzar/edx-platform,UOMx/edx-platform,iivic/BoiseStateX,CourseTalk/edx-platform,ovnicraft/edx-platform,kmoocdev2/edx-platform,arbrandes/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,defance/edx-platform,franosincic/edx-platform,arbrandes/edx-platform,IONISx/edx-platform,arbrandes/edx-platform,halvertoluke/edx-platform,IONISx/edx-platform,Lektorium-LLC/edx-platform,halvertoluke/edx-platform,Edraak/edraak-platform,kmoocdev2/edx-platform,devs1991/test_edx_docmode,simbs/edx-platform,solashirai/edx-platform,Edraak/circleci-edx-platform,marcore/edx-platform,Stanford-Online/edx-platform,Endika/edx-platform,tanmaykm/edx-platform,hamzehd/edx-platform,pomegranited/edx-platform,procangroup/edx-platform,msegado/edx-platform,zubair-arbi/edx-platform,procangroup/edx-platform,deepsrijit1105/edx-platform,nttks/edx-platform,RPI-OPENEDX/edx-platform,appsembler/edx-platform,shurihell/testasia,kursitet/edx-platform,edx-solutions/edx-platform,ahmedaljazzar/edx-platform,zubair-arbi/edx-platform,longmen21/edx-platform,a-parhom/edx-platform,ahmedaljazzar/edx-platform,devs1991/test_edx_docmode,wwj718/edx-platform,jzoldak/edx-platform,cognitiveclass/edx-platform,antoviaque/edx-platform,naresh21/synergetics-edx-platform,edx/edx-platform,gsehub/edx-platform,MakeHer/edx-platform,alexthered/kienhoc-platform,jbzdak/edx-platform,Livit/Livit.Learn.EdX,ahmadiga/min_edx,Edraak/circleci-edx-platform,caesar2164/edx-platform,pabloborrego93/edx-platform,defance/edx-platform,IndonesiaX/edx-platform,cognitiveclass/edx-platform,waheedahmed/edx-platform,wwj718/edx-platform,synergeticsedx/deployment-wipro,stvstnfrd/edx-platform,Endika/edx-platform,alu042/edx-platform,Edraak/edraak-platform,ZLLab-Mooc/edx-platform,CourseTalk/edx-platform,IndonesiaX/edx-platform,longmen21/edx-platform,amir-qayyum-khan/edx-platform,appsembler/edx-platform,romain-li/edx-platform,chrisndodge/edx-platform,lduarte1991/edx-platform,jbzdak/edx-platform,cecep-edu/edx-platform,wwj718/edx-platform,naresh21/synergetics-edx-platform,EDUlib/edx-platform,Lektorium-LLC/edx-platform,ampax/edx-platform,jzoldak/edx-platform,Ayub-Khan/edx-platform,shurihell/testasia,philanthropy-u/edx-platform,antoviaque/edx-platform,alu042/edx-platform,nttks/edx-platform,philanthropy-u/edx-platform,ZLLab-Mooc/edx-platform,BehavioralInsightsTeam/edx-platform,solashirai/edx-platform,franosincic/edx-platform,caesar2164/edx-platform,CredoReference/edx-platform,10clouds/edx-platform,eduNEXT/edx-platform,RPI-OPENEDX/edx-platform,Lektorium-LLC/edx-platform,hastexo/edx-platform,itsjeyd/edx-platform,a-parhom/edx-platform,raccoongang/edx-platform,nttks/edx-platform,jzoldak/edx-platform,mbareta/edx-platform-ft,mcgachey/edx-platform,JCBarahona/edX,pomegranited/edx-platform,marcore/edx-platform,a-parhom/edx-platform,JioEducation/edx-platform,shurihell/testasia,ZLLab-Mooc/edx-platform,bigdatauniversity/edx-platform,teltek/edx-platform,inares/edx-platform,edx/edx-platform,lduarte1991/edx-platform,mcgachey/edx-platform,chrisndodge/edx-platform,synergeticsedx/deployment-wipro,pomegranited/edx-platform,JCBarahona/edX,RPI-OPENEDX/edx-platform,stvstnfrd/edx-platform,appsembler/edx-platform,alexthered/kienhoc-platform,CourseTalk/edx-platform,teltek/edx-platform,Stanford-Online/edx-platform,mbareta/edx-platform-ft,EDUlib/edx-platform,eduNEXT/edunext-platform,prarthitm/edxplatform,longmen21/edx-platform,xingyepei/edx-platform,romain-li/edx-platform,devs1991/test_edx_docmode,cecep-edu/edx-platform,simbs/edx-platform,BehavioralInsightsTeam/edx-platform,cognitiveclass/edx-platform,jolyonb/edx-platform,pepeportela/edx-platform,proversity-org/edx-platform,mbareta/edx-platform-ft,proversity-org/edx-platform,IndonesiaX/edx-platform,iivic/BoiseStateX,cpennington/edx-platform,ZLLab-Mooc/edx-platform,hamzehd/edx-platform,xingyepei/edx-platform,hamzehd/edx-platform,zhenzhai/edx-platform,ESOedX/edx-platform,miptliot/edx-platform,mitocw/edx-platform,eduNEXT/edx-platform,Edraak/circleci-edx-platform,RPI-OPENEDX/edx-platform,jbzdak/edx-platform,JCBarahona/edX,jjmiranda/edx-platform,kursitet/edx-platform,fintech-circle/edx-platform,ampax/edx-platform,edx-solutions/edx-platform,alu042/edx-platform,Edraak/circleci-edx-platform,raccoongang/edx-platform,TeachAtTUM/edx-platform,itsjeyd/edx-platform,ampax/edx-platform,JioEducation/edx-platform,jolyonb/edx-platform,UOMx/edx-platform,ESOedX/edx-platform,hastexo/edx-platform,iivic/BoiseStateX,Stanford-Online/edx-platform,mcgachey/edx-platform,gsehub/edx-platform,proversity-org/edx-platform,angelapper/edx-platform,CredoReference/edx-platform,CredoReference/edx-platform,zubair-arbi/edx-platform,solashirai/edx-platform,romain-li/edx-platform,cecep-edu/edx-platform,Ayub-Khan/edx-platform,franosincic/edx-platform,pepeportela/edx-platform,10clouds/edx-platform,Ayub-Khan/edx-platform,halvertoluke/edx-platform,tanmaykm/edx-platform,appsembler/edx-platform,ZLLab-Mooc/edx-platform,eduNEXT/edunext-platform,gsehub/edx-platform,Edraak/edx-platform,solashirai/edx-platform,inares/edx-platform,angelapper/edx-platform,msegado/edx-platform,RPI-OPENEDX/edx-platform,JioEducation/edx-platform,tanmaykm/edx-platform,kursitet/edx-platform,nttks/edx-platform,pabloborrego93/edx-platform,simbs/edx-platform,longmen21/edx-platform,MakeHer/edx-platform,gymnasium/edx-platform,MakeHer/edx-platform,ovnicraft/edx-platform,a-parhom/edx-platform,shabab12/edx-platform,xingyepei/edx-platform,EDUlib/edx-platform,kmoocdev2/edx-platform,jzoldak/edx-platform,defance/edx-platform,franosincic/edx-platform,philanthropy-u/edx-platform,longmen21/edx-platform,prarthitm/edxplatform,eduNEXT/edx-platform,gsehub/edx-platform,itsjeyd/edx-platform,angelapper/edx-platform,gymnasium/edx-platform,analyseuc3m/ANALYSE-v1,zhenzhai/edx-platform,analyseuc3m/ANALYSE-v1,edx/edx-platform,simbs/edx-platform,devs1991/test_edx_docmode,kmoocdev2/edx-platform,alexthered/kienhoc-platform,Stanford-Online/edx-platform,teltek/edx-platform,msegado/edx-platform,Edraak/edraak-platform,Ayub-Khan/edx-platform,alexthered/kienhoc-platform,pepeportela/edx-platform,bigdatauniversity/edx-platform,mitocw/edx-platform,romain-li/edx-platform,cognitiveclass/edx-platform,waheedahmed/edx-platform,BehavioralInsightsTeam/edx-platform,Edraak/edx-platform,synergeticsedx/deployment-wipro,cecep-edu/edx-platform,deepsrijit1105/edx-platform,Edraak/edx-platform,devs1991/test_edx_docmode,louyihua/edx-platform,Ayub-Khan/edx-platform,procangroup/edx-platform,jolyonb/edx-platform,shurihell/testasia,10clouds/edx-platform,pepeportela/edx-platform,jolyonb/edx-platform,eduNEXT/edx-platform,alexthered/kienhoc-platform,IONISx/edx-platform,TeachAtTUM/edx-platform,antoviaque/edx-platform,gymnasium/edx-platform,cpennington/edx-platform,hamzehd/edx-platform,simbs/edx-platform,MakeHer/edx-platform,jjmiranda/edx-platform,doganov/edx-platform,naresh21/synergetics-edx-platform,ahmedaljazzar/edx-platform,10clouds/edx-platform,chrisndodge/edx-platform,naresh21/synergetics-edx-platform,Livit/Livit.Learn.EdX,cecep-edu/edx-platform,zubair-arbi/edx-platform,deepsrijit1105/edx-platform,ovnicraft/edx-platform,mitocw/edx-platform,ovnicraft/edx-platform,marcore/edx-platform,gymnasium/edx-platform,Edraak/circleci-edx-platform,iivic/BoiseStateX,louyihua/edx-platform,Edraak/edraak-platform,xingyepei/edx-platform,ahmadiga/min_edx,inares/edx-platform,marcore/edx-platform,angelapper/edx-platform,alu042/edx-platform,zhenzhai/edx-platform,procangroup/edx-platform,Endika/edx-platform,TeachAtTUM/edx-platform,jjmiranda/edx-platform,mcgachey/edx-platform,jbzdak/edx-platform,CourseTalk/edx-platform,miptliot/edx-platform,wwj718/edx-platform,ESOedX/edx-platform,raccoongang/edx-platform,pabloborrego93/edx-platform,UOMx/edx-platform,iivic/BoiseStateX,mcgachey/edx-platform,raccoongang/edx-platform,kursitet/edx-platform,eduNEXT/edunext-platform,ahmadiga/min_edx,shabab12/edx-platform,chrisndodge/edx-platform,devs1991/test_edx_docmode,caesar2164/edx-platform,Livit/Livit.Learn.EdX,romain-li/edx-platform,shurihell/testasia,halvertoluke/edx-platform,BehavioralInsightsTeam/edx-platform,halvertoluke/edx-platform,devs1991/test_edx_docmode,JioEducation/edx-platform,pomegranited/edx-platform,msegado/edx-platform,inares/edx-platform,UOMx/edx-platform,hastexo/edx-platform,amir-qayyum-khan/edx-platform,msegado/edx-platform,ESOedX/edx-platform,kursitet/edx-platform,arbrandes/edx-platform,franosincic/edx-platform,ovnicraft/edx-platform,IndonesiaX/edx-platform,pabloborrego93/edx-platform,hastexo/edx-platform,mitocw/edx-platform,doganov/edx-platform,louyihua/edx-platform,bigdatauniversity/edx-platform,doganov/edx-platform,philanthropy-u/edx-platform,zhenzhai/edx-platform,lduarte1991/edx-platform,kmoocdev2/edx-platform,ahmadiga/min_edx,miptliot/edx-platform,Edraak/edx-platform,edx/edx-platform,analyseuc3m/ANALYSE-v1,CredoReference/edx-platform,analyseuc3m/ANALYSE-v1,devs1991/test_edx_docmode,shabab12/edx-platform,Lektorium-LLC/edx-platform,fintech-circle/edx-platform,EDUlib/edx-platform
|
python
|
## Code Before:
from wiki.core.plugins.base import BasePlugin
from wiki.core.plugins import registry as plugin_registry
from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video
class ExtendMarkdownPlugin(BasePlugin):
"""
This plugin simply loads all of the markdown extensions we use in edX.
"""
markdown_extensions = [
mdx_mathjax.MathJaxExtension(configs={}),
mdx_video.VideoExtension(configs={})]
plugin_registry.register(ExtendMarkdownPlugin)
## Instruction:
Fix PEP8: E126 continuation line over-indented
for hanging indent
## Code After:
from wiki.core.plugins.base import BasePlugin
from wiki.core.plugins import registry as plugin_registry
from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video
class ExtendMarkdownPlugin(BasePlugin):
"""
This plugin simply loads all of the markdown extensions we use in edX.
"""
markdown_extensions = [
mdx_mathjax.MathJaxExtension(configs={}),
mdx_video.VideoExtension(configs={}),
]
plugin_registry.register(ExtendMarkdownPlugin)
|
// ... existing code ...
"""
markdown_extensions = [
mdx_mathjax.MathJaxExtension(configs={}),
mdx_video.VideoExtension(configs={}),
]
plugin_registry.register(ExtendMarkdownPlugin)
// ... rest of the code ...
|
89826f41bd5c96e6b13692d03d08049c912b9365
|
cat.c
|
cat.c
|
char buf[512];
void
cat(int fd)
{
int n;
while((n = read(fd, buf, sizeof(buf))) > 0)
write(1, buf, n);
if(n < 0){
printf(1, "cat: read error\n");
exit();
}
}
int
main(int argc, char *argv[])
{
int fd, i;
if(argc <= 1){
cat(0);
exit();
}
for(i = 1; i < argc; i++){
if((fd = open(argv[i], 0)) < 0){
printf(1, "cat: cannot open %s\n", argv[i]);
exit();
}
cat(fd);
close(fd);
}
exit();
}
|
char buf[512];
void
cat(int fd)
{
int n;
while((n = read(fd, buf, sizeof(buf))) > 0) {
if (write(1, buf, n) != n) {
printf(1, "cat: write error\n");
exit();
}
}
if(n < 0){
printf(1, "cat: read error\n");
exit();
}
}
int
main(int argc, char *argv[])
{
int fd, i;
if(argc <= 1){
cat(0);
exit();
}
for(i = 1; i < argc; i++){
if((fd = open(argv[i], 0)) < 0){
printf(1, "cat: cannot open %s\n", argv[i]);
exit();
}
cat(fd);
close(fd);
}
exit();
}
|
Check result of write (thans to Alexander Kapshuk <alexander.kapshuk@gmail)
|
Check result of write (thans to Alexander Kapshuk <alexander.kapshuk@gmail)
|
C
|
mit
|
shyandsy/xv6,shyandsy/xv6,shyandsy/xv6,ManaPoustizadeh/OS-finalProject,shyandsy/xv6,ManaPoustizadeh/OS-finalProject,gw/xv6,phf/xv6-public,voytovichs/xv6-public,voytovichs/xv6-public,ManaPoustizadeh/OS-finalProject,voytovichs/xv6-public,gw/xv6,phf/xv6-public,voytovichs/xv6-public,voytovichs/xv6-public,phf/xv6-public,phf/xv6-public,ManaPoustizadeh/OS-finalProject,gw/xv6,gw/xv6,gw/xv6,shyandsy/xv6
|
c
|
## Code Before:
char buf[512];
void
cat(int fd)
{
int n;
while((n = read(fd, buf, sizeof(buf))) > 0)
write(1, buf, n);
if(n < 0){
printf(1, "cat: read error\n");
exit();
}
}
int
main(int argc, char *argv[])
{
int fd, i;
if(argc <= 1){
cat(0);
exit();
}
for(i = 1; i < argc; i++){
if((fd = open(argv[i], 0)) < 0){
printf(1, "cat: cannot open %s\n", argv[i]);
exit();
}
cat(fd);
close(fd);
}
exit();
}
## Instruction:
Check result of write (thans to Alexander Kapshuk <alexander.kapshuk@gmail)
## Code After:
char buf[512];
void
cat(int fd)
{
int n;
while((n = read(fd, buf, sizeof(buf))) > 0) {
if (write(1, buf, n) != n) {
printf(1, "cat: write error\n");
exit();
}
}
if(n < 0){
printf(1, "cat: read error\n");
exit();
}
}
int
main(int argc, char *argv[])
{
int fd, i;
if(argc <= 1){
cat(0);
exit();
}
for(i = 1; i < argc; i++){
if((fd = open(argv[i], 0)) < 0){
printf(1, "cat: cannot open %s\n", argv[i]);
exit();
}
cat(fd);
close(fd);
}
exit();
}
|
// ... existing code ...
{
int n;
while((n = read(fd, buf, sizeof(buf))) > 0) {
if (write(1, buf, n) != n) {
printf(1, "cat: write error\n");
exit();
}
}
if(n < 0){
printf(1, "cat: read error\n");
exit();
// ... rest of the code ...
|
3474ac2f726df685479e89e6c9a72175d5c7b17e
|
src/main/java/com/faforever/client/fx/contextmenu/ShowPlayerInfoMenuItem.java
|
src/main/java/com/faforever/client/fx/contextmenu/ShowPlayerInfoMenuItem.java
|
package com.faforever.client.fx.contextmenu;
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.player.SocialStatus;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {
private final I18n i18n;
private final UiService uiService;
@Override
protected void onClicked() {
Assert.checkNullIllegalState(object, "no player has been set");
PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
controller.setPlayer(object);
controller.setOwnerWindow(getParentPopup().getOwnerWindow());
controller.show();
}
@Override
protected boolean isItemVisible() {
return object != null && object.getSocialStatus() != SocialStatus.SELF;
}
@Override
protected String getItemText() {
return i18n.get("chat.userContext.userInfo");
}
}
|
package com.faforever.client.fx.contextmenu;
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {
private final I18n i18n;
private final UiService uiService;
@Override
protected void onClicked() {
Assert.checkNullIllegalState(object, "no player has been set");
PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
controller.setPlayer(object);
controller.setOwnerWindow(getParentPopup().getOwnerWindow());
controller.show();
}
@Override
protected boolean isItemVisible() {
return object != null;
}
@Override
protected String getItemText() {
return i18n.get("chat.userContext.userInfo");
}
}
|
Allow players to see their own stats
|
Allow players to see their own stats
|
Java
|
mit
|
FAForever/downlords-faf-client,FAForever/downlords-faf-client,FAForever/downlords-faf-client
|
java
|
## Code Before:
package com.faforever.client.fx.contextmenu;
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.player.SocialStatus;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {
private final I18n i18n;
private final UiService uiService;
@Override
protected void onClicked() {
Assert.checkNullIllegalState(object, "no player has been set");
PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
controller.setPlayer(object);
controller.setOwnerWindow(getParentPopup().getOwnerWindow());
controller.show();
}
@Override
protected boolean isItemVisible() {
return object != null && object.getSocialStatus() != SocialStatus.SELF;
}
@Override
protected String getItemText() {
return i18n.get("chat.userContext.userInfo");
}
}
## Instruction:
Allow players to see their own stats
## Code After:
package com.faforever.client.fx.contextmenu;
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {
private final I18n i18n;
private final UiService uiService;
@Override
protected void onClicked() {
Assert.checkNullIllegalState(object, "no player has been set");
PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
controller.setPlayer(object);
controller.setOwnerWindow(getParentPopup().getOwnerWindow());
controller.show();
}
@Override
protected boolean isItemVisible() {
return object != null;
}
@Override
protected String getItemText() {
return i18n.get("chat.userContext.userInfo");
}
}
|
...
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
...
@Override
protected boolean isItemVisible() {
return object != null;
}
@Override
...
|
cd22543319e4c21b693f91768adcc1cd42aa08a3
|
calexicon/fn/overflow.py
|
calexicon/fn/overflow.py
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
Remove this line - it is redundant and missing code coverage.
|
Remove this line - it is redundant and missing code coverage.
|
Python
|
apache-2.0
|
jwg4/qual,jwg4/calexicon
|
python
|
## Code Before:
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
## Instruction:
Remove this line - it is redundant and missing code coverage.
## Code After:
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
...
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
...
|
db3de3779b73a2919c193fa3bd85d1295a0e54ef
|
src/vast/query/search.h
|
src/vast/query/search.h
|
namespace vast {
namespace query {
class search : public cppa::sb_actor<search>
{
friend class cppa::sb_actor<search>;
public:
search(cppa::actor_ptr archive, cppa::actor_ptr index);
private:
std::vector<cppa::actor_ptr> queries_;
std::multimap<cppa::actor_ptr, cppa::actor_ptr> clients_;
cppa::actor_ptr archive_;
cppa::actor_ptr index_;
cppa::behavior init_state;
};
} // namespace query
} // namespace vast
#endif
|
namespace vast {
namespace query {
class search : public cppa::sb_actor<search>
{
friend class cppa::sb_actor<search>;
public:
search(cppa::actor_ptr archive, cppa::actor_ptr index);
private:
std::vector<cppa::actor_ptr> queries_;
std::unordered_multimap<cppa::actor_ptr, cppa::actor_ptr> clients_;
cppa::actor_ptr archive_;
cppa::actor_ptr index_;
cppa::behavior init_state;
};
} // namespace query
} // namespace vast
#endif
|
Use an unordered map to track clients.
|
Use an unordered map to track clients.
|
C
|
bsd-3-clause
|
pmos69/vast,mavam/vast,vast-io/vast,vast-io/vast,pmos69/vast,pmos69/vast,mavam/vast,vast-io/vast,mavam/vast,mavam/vast,vast-io/vast,pmos69/vast,vast-io/vast
|
c
|
## Code Before:
namespace vast {
namespace query {
class search : public cppa::sb_actor<search>
{
friend class cppa::sb_actor<search>;
public:
search(cppa::actor_ptr archive, cppa::actor_ptr index);
private:
std::vector<cppa::actor_ptr> queries_;
std::multimap<cppa::actor_ptr, cppa::actor_ptr> clients_;
cppa::actor_ptr archive_;
cppa::actor_ptr index_;
cppa::behavior init_state;
};
} // namespace query
} // namespace vast
#endif
## Instruction:
Use an unordered map to track clients.
## Code After:
namespace vast {
namespace query {
class search : public cppa::sb_actor<search>
{
friend class cppa::sb_actor<search>;
public:
search(cppa::actor_ptr archive, cppa::actor_ptr index);
private:
std::vector<cppa::actor_ptr> queries_;
std::unordered_multimap<cppa::actor_ptr, cppa::actor_ptr> clients_;
cppa::actor_ptr archive_;
cppa::actor_ptr index_;
cppa::behavior init_state;
};
} // namespace query
} // namespace vast
#endif
|
// ... existing code ...
private:
std::vector<cppa::actor_ptr> queries_;
std::unordered_multimap<cppa::actor_ptr, cppa::actor_ptr> clients_;
cppa::actor_ptr archive_;
cppa::actor_ptr index_;
cppa::behavior init_state;
// ... rest of the code ...
|
de0bbf978695d206189ee4effb124234968525cb
|
django_afip/views.py
|
django_afip/views.py
|
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
|
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
|
Add a view to display PDF receipts
|
Add a view to display PDF receipts
Fixes #23
Closes !7
Closes !8
|
Python
|
isc
|
hobarrera/django-afip,hobarrera/django-afip
|
python
|
## Code Before:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
## Instruction:
Add a view to display PDF receipts
Fixes #23
Closes !7
Closes !8
## Code After:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
|
# ... existing code ...
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
# ... modified code ...
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
...
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
# ... rest of the code ...
|
dbb223d64d1058e34c35867dcca2665766d0edbf
|
synapse/tests/test_config.py
|
synapse/tests/test_config.py
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
Update test to ensure that default configuration values are available via getConfOpt
|
Update test to ensure that default configuration values are available via getConfOpt
|
Python
|
apache-2.0
|
vertexproject/synapse,vertexproject/synapse,vertexproject/synapse,vivisect/synapse
|
python
|
## Code Before:
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
## Instruction:
Update test to ensure that default configuration values are available via getConfOpt
## Code After:
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
# ... existing code ...
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
# ... rest of the code ...
|
e5eaf68490098cb89cf9d6ad8b4eaa96bafd0450
|
compose/cli/docker_client.py
|
compose/cli/docker_client.py
|
import logging
import os
import ssl
from docker import Client
from docker import tls
from ..const import HTTP_TIMEOUT
log = logging.getLogger(__name__)
def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
if cert_path == '':
cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')
base_url = os.environ.get('DOCKER_HOST')
api_version = os.environ.get('COMPOSE_API_VERSION', '1.19')
tls_config = None
if os.environ.get('DOCKER_TLS_VERIFY', '') != '':
parts = base_url.split('://', 1)
base_url = '%s://%s' % ('https', parts[1])
client_cert = (os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem'))
ca_cert = os.path.join(cert_path, 'ca.pem')
tls_config = tls.TLSConfig(
ssl_version=ssl.PROTOCOL_TLSv1,
verify=True,
assert_hostname=False,
client_cert=client_cert,
ca_cert=ca_cert,
)
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. Please use COMPOSE_HTTP_TIMEOUT instead.')
return Client(base_url=base_url, tls=tls_config, version=api_version, timeout=HTTP_TIMEOUT)
|
import logging
import os
from docker import Client
from docker.utils import kwargs_from_env
from ..const import HTTP_TIMEOUT
log = logging.getLogger(__name__)
def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. Please use COMPOSE_HTTP_TIMEOUT instead.')
kwargs = kwargs_from_env(assert_hostname=False)
kwargs['version'] = os.environ.get('COMPOSE_API_VERSION', '1.19')
kwargs['timeout'] = HTTP_TIMEOUT
return Client(**kwargs)
|
Remove custom docker client initialization logic
|
Remove custom docker client initialization logic
Signed-off-by: Aanand Prasad <[email protected]>
|
Python
|
apache-2.0
|
phiroict/docker,denverdino/docker.github.io,phiroict/docker,denverdino/docker.github.io,jzwlqx/denverdino.github.io,docker/docker.github.io,shin-/docker.github.io,swoopla/compose,rillig/docker.github.io,jiekechoo/compose,bdwill/docker.github.io,joeuo/docker.github.io,sanscontext/docker.github.io,amitsaha/compose,GM-Alex/compose,mohitsoni/compose,charleswhchan/compose,troy0820/docker.github.io,thaJeztah/compose,kikkomep/compose,KevinGreene/compose,thaJeztah/docker.github.io,phiroict/docker,joaofnfernandes/docker.github.io,goloveychuk/compose,docker-zh/docker.github.io,sdurrheimer/compose,talolard/compose,alexisbellido/docker.github.io,londoncalling/docker.github.io,denverdino/docker.github.io,londoncalling/docker.github.io,mnowster/compose,londoncalling/docker.github.io,dbdd4us/compose,goloveychuk/compose,johnstep/docker.github.io,sanscontext/docker.github.io,swoopla/compose,rillig/docker.github.io,j-fuentes/compose,twitherspoon/compose,menglingwei/denverdino.github.io,danix800/docker.github.io,shubheksha/docker.github.io,viranch/compose,TomasTomecek/compose,bdwill/docker.github.io,denverdino/denverdino.github.io,jzwlqx/denverdino.github.io,shubheksha/docker.github.io,j-fuentes/compose,albers/compose,viranch/compose,funkyfuture/docker-compose,londoncalling/docker.github.io,joeuo/docker.github.io,johnstep/docker.github.io,docker-zh/docker.github.io,bdwill/docker.github.io,au-phiware/compose,jiekechoo/compose,moxiegirl/compose,phiroict/docker,docker/docker.github.io,denverdino/denverdino.github.io,jeanpralo/compose,kojiromike/compose,tiry/compose,aduermael/docker.github.io,albers/compose,twitherspoon/compose,denverdino/compose,mdaue/compose,kikkomep/compose,TomasTomecek/compose,denverdino/denverdino.github.io,johnstep/docker.github.io,londoncalling/docker.github.io,mrfuxi/compose,alexandrev/compose,hoogenm/compose,troy0820/docker.github.io,jeanpralo/compose,joaofnfernandes/docker.github.io,schmunk42/compose,LuisBosquez/docker.github.io,alexisbellido/docker.github.io,andrewgee/compose,vdemeester/compose,joaofnfernandes/docker.github.io,shin-/compose,jorgeLuizChaves/compose,shubheksha/docker.github.io,BSWANG/denverdino.github.io,KalleDK/compose,menglingwei/denverdino.github.io,jonaseck2/compose,shin-/docker.github.io,anweiss/docker.github.io,jrabbit/compose,dnephin/compose,mnowster/compose,amitsaha/compose,shin-/docker.github.io,docker-zh/docker.github.io,LuisBosquez/docker.github.io,joaofnfernandes/docker.github.io,BSWANG/denverdino.github.io,bdwill/docker.github.io,au-phiware/compose,vdemeester/compose,anweiss/docker.github.io,mohitsoni/compose,aduermael/docker.github.io,aduermael/docker.github.io,denverdino/docker.github.io,alexisbellido/docker.github.io,tiry/compose,anweiss/docker.github.io,shubheksha/docker.github.io,hoogenm/compose,JimGalasyn/docker.github.io,jorgeLuizChaves/compose,michael-k/docker-compose,funkyfuture/docker-compose,ChrisChinchilla/compose,talolard/compose,sdurrheimer/compose,thaJeztah/docker.github.io,alexisbellido/docker.github.io,kojiromike/compose,joeuo/docker.github.io,KevinGreene/compose,thaJeztah/docker.github.io,joeuo/docker.github.io,thaJeztah/compose,alexandrev/compose,troy0820/docker.github.io,docker/docker.github.io,danix800/docker.github.io,LuisBosquez/docker.github.io,GM-Alex/compose,sanscontext/docker.github.io,troy0820/docker.github.io,sanscontext/docker.github.io,shubheksha/docker.github.io,docker-zh/docker.github.io,rillig/docker.github.io,JimGalasyn/docker.github.io,schmunk42/compose,jzwlqx/denverdino.github.io,moxiegirl/compose,phiroict/docker,BSWANG/denverdino.github.io,rgbkrk/compose,dbdd4us/compose,thaJeztah/docker.github.io,michael-k/docker-compose,KalleDK/compose,jzwlqx/denverdino.github.io,johnstep/docker.github.io,gdevillele/docker.github.io,BSWANG/denverdino.github.io,ChrisChinchilla/compose,JimGalasyn/docker.github.io,gdevillele/docker.github.io,danix800/docker.github.io,gdevillele/docker.github.io,mrfuxi/compose,shin-/docker.github.io,aduermael/docker.github.io,docker/docker.github.io,sanscontext/docker.github.io,docker-zh/docker.github.io,danix800/docker.github.io,JimGalasyn/docker.github.io,denverdino/compose,dnephin/compose,shin-/docker.github.io,rillig/docker.github.io,gdevillele/docker.github.io,rgbkrk/compose,LuisBosquez/docker.github.io,anweiss/docker.github.io,LuisBosquez/docker.github.io,bdwill/docker.github.io,JimGalasyn/docker.github.io,denverdino/denverdino.github.io,jzwlqx/denverdino.github.io,menglingwei/denverdino.github.io,denverdino/docker.github.io,johnstep/docker.github.io,docker/docker.github.io,menglingwei/denverdino.github.io,mdaue/compose,jonaseck2/compose,gdevillele/docker.github.io,anweiss/docker.github.io,BSWANG/denverdino.github.io,menglingwei/denverdino.github.io,thaJeztah/docker.github.io,shin-/compose,joaofnfernandes/docker.github.io,alexisbellido/docker.github.io,charleswhchan/compose,andrewgee/compose,denverdino/denverdino.github.io,jrabbit/compose,joeuo/docker.github.io
|
python
|
## Code Before:
import logging
import os
import ssl
from docker import Client
from docker import tls
from ..const import HTTP_TIMEOUT
log = logging.getLogger(__name__)
def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
if cert_path == '':
cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')
base_url = os.environ.get('DOCKER_HOST')
api_version = os.environ.get('COMPOSE_API_VERSION', '1.19')
tls_config = None
if os.environ.get('DOCKER_TLS_VERIFY', '') != '':
parts = base_url.split('://', 1)
base_url = '%s://%s' % ('https', parts[1])
client_cert = (os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem'))
ca_cert = os.path.join(cert_path, 'ca.pem')
tls_config = tls.TLSConfig(
ssl_version=ssl.PROTOCOL_TLSv1,
verify=True,
assert_hostname=False,
client_cert=client_cert,
ca_cert=ca_cert,
)
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. Please use COMPOSE_HTTP_TIMEOUT instead.')
return Client(base_url=base_url, tls=tls_config, version=api_version, timeout=HTTP_TIMEOUT)
## Instruction:
Remove custom docker client initialization logic
Signed-off-by: Aanand Prasad <[email protected]>
## Code After:
import logging
import os
from docker import Client
from docker.utils import kwargs_from_env
from ..const import HTTP_TIMEOUT
log = logging.getLogger(__name__)
def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. Please use COMPOSE_HTTP_TIMEOUT instead.')
kwargs = kwargs_from_env(assert_hostname=False)
kwargs['version'] = os.environ.get('COMPOSE_API_VERSION', '1.19')
kwargs['timeout'] = HTTP_TIMEOUT
return Client(**kwargs)
|
// ... existing code ...
import logging
import os
from docker import Client
from docker.utils import kwargs_from_env
from ..const import HTTP_TIMEOUT
// ... modified code ...
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. Please use COMPOSE_HTTP_TIMEOUT instead.')
kwargs = kwargs_from_env(assert_hostname=False)
kwargs['version'] = os.environ.get('COMPOSE_API_VERSION', '1.19')
kwargs['timeout'] = HTTP_TIMEOUT
return Client(**kwargs)
// ... rest of the code ...
|
cf94fb86cab2fc892b762b66b760a80ed268e8b3
|
social/accounts/__init__.py
|
social/accounts/__init__.py
|
"""Import and register all account types."""
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching the
breadcrumbs. Otherwise, you're just mean.
"""
pass
@staticmethod
@abstractmethod
def match(*breadcrumbs):
"""
Return truthy if the breadcrumbs match the account.
The breadcrumbs are described below, but match functions should be
written to gracefully accept more or less keys in the breadcrumbs.
:param dict breadcrumbs: Dictionary containing at least one of the
following breadcrumbs:
- url: A URL that probably points to their profile.
- email: An email that could be used to find the profile.
- username: A username for the account.
"""
pass
@abstractmethod
def expand(self, info):
"""
Return an iterable of breadcrumb structs!
:param info: A dictionary that should contain information about the
person. It should be updated with any information you come across,
and you may want to use any info in it to help narrow down your
search.
"""
pass
|
"""Import and register all account types."""
from abc import ABC, abstractmethod
__all__ = ['github']
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching the
breadcrumbs. Otherwise, you're just mean.
"""
pass
@staticmethod
@abstractmethod
def match(*breadcrumbs):
"""
Return truthy if the breadcrumbs match the account.
The breadcrumbs are described below, but match functions should be
written to gracefully accept more or less keys in the breadcrumbs.
:param dict breadcrumbs: Dictionary containing at least one of the
following breadcrumbs:
- url: A URL that probably points to their profile.
- email: An email that could be used to find the profile.
- username: A username for the account.
"""
pass
@abstractmethod
def expand(self, info):
"""
Return an iterable of breadcrumb structs!
:param info: A dictionary that should contain information about the
person. It should be updated with any information you come across,
and you may want to use any info in it to help narrow down your
search.
"""
pass
|
Add github to the accounts package.
|
Add github to the accounts package.
|
Python
|
bsd-3-clause
|
brenns10/social,brenns10/social
|
python
|
## Code Before:
"""Import and register all account types."""
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching the
breadcrumbs. Otherwise, you're just mean.
"""
pass
@staticmethod
@abstractmethod
def match(*breadcrumbs):
"""
Return truthy if the breadcrumbs match the account.
The breadcrumbs are described below, but match functions should be
written to gracefully accept more or less keys in the breadcrumbs.
:param dict breadcrumbs: Dictionary containing at least one of the
following breadcrumbs:
- url: A URL that probably points to their profile.
- email: An email that could be used to find the profile.
- username: A username for the account.
"""
pass
@abstractmethod
def expand(self, info):
"""
Return an iterable of breadcrumb structs!
:param info: A dictionary that should contain information about the
person. It should be updated with any information you come across,
and you may want to use any info in it to help narrow down your
search.
"""
pass
## Instruction:
Add github to the accounts package.
## Code After:
"""Import and register all account types."""
from abc import ABC, abstractmethod
__all__ = ['github']
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching the
breadcrumbs. Otherwise, you're just mean.
"""
pass
@staticmethod
@abstractmethod
def match(*breadcrumbs):
"""
Return truthy if the breadcrumbs match the account.
The breadcrumbs are described below, but match functions should be
written to gracefully accept more or less keys in the breadcrumbs.
:param dict breadcrumbs: Dictionary containing at least one of the
following breadcrumbs:
- url: A URL that probably points to their profile.
- email: An email that could be used to find the profile.
- username: A username for the account.
"""
pass
@abstractmethod
def expand(self, info):
"""
Return an iterable of breadcrumb structs!
:param info: A dictionary that should contain information about the
person. It should be updated with any information you come across,
and you may want to use any info in it to help narrow down your
search.
"""
pass
|
...
"""Import and register all account types."""
from abc import ABC, abstractmethod
__all__ = ['github']
class Account(ABC):
...
|
1f9a11640463df94166be8dffa824e57485154f8
|
tests/vaspy_test.py
|
tests/vaspy_test.py
|
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
|
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
from ani_test import AniFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
unittest.TestLoader().loadTestsFromTestCase(AniFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
|
Add test for animation file.
|
Add test for animation file.
|
Python
|
mit
|
PytLab/VASPy,PytLab/VASPy
|
python
|
## Code Before:
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
## Instruction:
Add test for animation file.
## Code After:
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
from ani_test import AniFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
unittest.TestLoader().loadTestsFromTestCase(AniFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
|
...
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
from ani_test import AniFileTest
def suite():
suite = unittest.TestSuite([
...
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
unittest.TestLoader().loadTestsFromTestCase(AniFileTest),
])
return suite
...
|
67337102eaa5b01da1a9ad2c1f6a48290d4ff044
|
src/test/java/com/quizdeck/analysis/QuizAnalysisFactoryTest.java
|
src/test/java/com/quizdeck/analysis/QuizAnalysisFactoryTest.java
|
package com.quizdeck.analysis;
import com.quizdeck.Application.QuizDeckApplication;
import com.quizdeck.analysis.exceptions.AnalysisException;
import com.quizdeck.analysis.inputs.*;
import com.quizdeck.analysis.outputs.QuizAnalysisData;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.LinkedList;
/**
* Test for the QuizAnalysisFactory
*
* @author Alex
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = QuizDeckApplication.class)
public class QuizAnalysisFactoryTest {
@Test
public void dummyTest() throws AnalysisException {
LinkedList<Question> questions = new LinkedList<>();
questions.add(new MockQuestion(1, new MockSelection('0')));
questions.add(new MockQuestion(2, new MockSelection('1')));
MockMember steve = new MockMember();
LinkedList<Response> responses = new LinkedList<>();
for(int i = 0; i < 50; i++)
responses.add(new MockResponse(steve, new MockSelection(Integer.toString(i).charAt(0)), questions.get(0), i));
QuizAnalysisFactory factory = new QuizAnalysisFactory();
factory.setResponses(responses);
factory.setQuestions(questions);
factory.setQuizID("Q1");
factory.setDeckID("D1");
factory.setOwner(steve);
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
analysis.performAnalysis();
QuizAnalysisData result = (QuizAnalysisData) analysis.getResults();
}
}
|
package com.quizdeck.analysis;
import com.quizdeck.Application.QuizDeckApplication;
import com.quizdeck.analysis.exceptions.AnalysisException;
import com.quizdeck.analysis.exceptions.InsufficientDataException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.LinkedList;
/**
* Test for the QuizAnalysisFactory
*
* @author Alex
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = QuizDeckApplication.class)
public class QuizAnalysisFactoryTest {
@Test(expected = InsufficientDataException.class)
public void insufficientDataTest() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
@Test
public void constructEmptyAnalysis() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
factory.setOwner(new MockMember());
factory.setDeckID("DeckID");
factory.setQuizID("QuizID");
factory.setQuestions(new LinkedList<>());
factory.setResponses(new LinkedList<>());
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
}
|
Make QuizAnalysisFactory unit tests more specific.
|
Make QuizAnalysisFactory unit tests more specific.
|
Java
|
mit
|
bcroden/QuizDeck-Server
|
java
|
## Code Before:
package com.quizdeck.analysis;
import com.quizdeck.Application.QuizDeckApplication;
import com.quizdeck.analysis.exceptions.AnalysisException;
import com.quizdeck.analysis.inputs.*;
import com.quizdeck.analysis.outputs.QuizAnalysisData;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.LinkedList;
/**
* Test for the QuizAnalysisFactory
*
* @author Alex
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = QuizDeckApplication.class)
public class QuizAnalysisFactoryTest {
@Test
public void dummyTest() throws AnalysisException {
LinkedList<Question> questions = new LinkedList<>();
questions.add(new MockQuestion(1, new MockSelection('0')));
questions.add(new MockQuestion(2, new MockSelection('1')));
MockMember steve = new MockMember();
LinkedList<Response> responses = new LinkedList<>();
for(int i = 0; i < 50; i++)
responses.add(new MockResponse(steve, new MockSelection(Integer.toString(i).charAt(0)), questions.get(0), i));
QuizAnalysisFactory factory = new QuizAnalysisFactory();
factory.setResponses(responses);
factory.setQuestions(questions);
factory.setQuizID("Q1");
factory.setDeckID("D1");
factory.setOwner(steve);
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
analysis.performAnalysis();
QuizAnalysisData result = (QuizAnalysisData) analysis.getResults();
}
}
## Instruction:
Make QuizAnalysisFactory unit tests more specific.
## Code After:
package com.quizdeck.analysis;
import com.quizdeck.Application.QuizDeckApplication;
import com.quizdeck.analysis.exceptions.AnalysisException;
import com.quizdeck.analysis.exceptions.InsufficientDataException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.LinkedList;
/**
* Test for the QuizAnalysisFactory
*
* @author Alex
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = QuizDeckApplication.class)
public class QuizAnalysisFactoryTest {
@Test(expected = InsufficientDataException.class)
public void insufficientDataTest() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
@Test
public void constructEmptyAnalysis() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
factory.setOwner(new MockMember());
factory.setDeckID("DeckID");
factory.setQuizID("QuizID");
factory.setQuestions(new LinkedList<>());
factory.setResponses(new LinkedList<>());
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
}
|
# ... existing code ...
import com.quizdeck.Application.QuizDeckApplication;
import com.quizdeck.analysis.exceptions.AnalysisException;
import com.quizdeck.analysis.exceptions.InsufficientDataException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
# ... modified code ...
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = QuizDeckApplication.class)
public class QuizAnalysisFactoryTest {
@Test(expected = InsufficientDataException.class)
public void insufficientDataTest() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
@Test
public void constructEmptyAnalysis() throws AnalysisException {
QuizAnalysisFactory factory = new QuizAnalysisFactory();
factory.setOwner(new MockMember());
factory.setDeckID("DeckID");
factory.setQuizID("QuizID");
factory.setQuestions(new LinkedList<>());
factory.setResponses(new LinkedList<>());
StaticAnalysis analysis = (StaticAnalysis) factory.getAnalysisUsing(QuizAlgorithm.ACCURACY);
}
}
# ... rest of the code ...
|
fd94904f4bffbcd8eec0ce025e7123fcb7569c03
|
tests/regression/06-symbeq/24-escape_rc.c
|
tests/regression/06-symbeq/24-escape_rc.c
|
// PARAM: --set ana.activated[+] "'var_eq'"
// Copy of 04/45 with var_eq enabled
// octApron needs to be included again and fixed
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
int *p = (int *) arg;
pthread_mutex_lock(&mutex1);
(*p)++;
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
int i = 0;
pthread_create(&id, NULL, t_fun, (void *) &i);
pthread_mutex_lock(&mutex2);
assert(i == 0); // UNKNOWN!
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
|
// PARAM: --set ana.activated[+] "'var_eq'"
// Copy of 04/45 with var_eq enabled
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
int *p = (int *) arg;
pthread_mutex_lock(&mutex1);
(*p)++;
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
int i = 0;
pthread_create(&id, NULL, t_fun, (void *) &i);
pthread_mutex_lock(&mutex2);
assert(i == 0); // UNKNOWN!
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
|
Remove outdated octApron comment from 06/24
|
Remove outdated octApron comment from 06/24
|
C
|
mit
|
goblint/analyzer,goblint/analyzer,goblint/analyzer,goblint/analyzer,goblint/analyzer
|
c
|
## Code Before:
// PARAM: --set ana.activated[+] "'var_eq'"
// Copy of 04/45 with var_eq enabled
// octApron needs to be included again and fixed
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
int *p = (int *) arg;
pthread_mutex_lock(&mutex1);
(*p)++;
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
int i = 0;
pthread_create(&id, NULL, t_fun, (void *) &i);
pthread_mutex_lock(&mutex2);
assert(i == 0); // UNKNOWN!
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
## Instruction:
Remove outdated octApron comment from 06/24
## Code After:
// PARAM: --set ana.activated[+] "'var_eq'"
// Copy of 04/45 with var_eq enabled
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
int *p = (int *) arg;
pthread_mutex_lock(&mutex1);
(*p)++;
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
int i = 0;
pthread_create(&id, NULL, t_fun, (void *) &i);
pthread_mutex_lock(&mutex2);
assert(i == 0); // UNKNOWN!
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
|
# ... existing code ...
// PARAM: --set ana.activated[+] "'var_eq'"
// Copy of 04/45 with var_eq enabled
#include <pthread.h>
#include <stdio.h>
# ... rest of the code ...
|
bdc554d18dc67cd4979bac3bc5d4b7d01b23b8b4
|
grako/rendering.py
|
grako/rendering.py
|
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
Allow override of template through return value of render_fields.
|
Allow override of template through return value of render_fields.
|
Python
|
bsd-2-clause
|
swayf/grako,swayf/grako
|
python
|
## Code Before:
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
## Instruction:
Allow override of template through return value of render_fields.
## Code After:
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
# ... existing code ...
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
# ... rest of the code ...
|
af796cf20532b517b9232d862b0f3d6444f162dc
|
demo-jda/src/main/java/com/sedmelluq/discord/lavaplayer/demo/jda/AudioPlayerSendHandler.java
|
demo-jda/src/main/java/com/sedmelluq/discord/lavaplayer/demo/jda/AudioPlayerSendHandler.java
|
package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
lastFrame = audioPlayer.provide();
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
return lastFrame.data;
}
@Override
public boolean isOpus() {
return true;
}
}
|
package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
byte[] data = lastFrame != null ? lastFrame.data : null;
lastFrame = null;
return data;
}
@Override
public boolean isOpus() {
return true;
}
}
|
Make it safe to call canProvide multiple times (or not at all).
|
Make it safe to call canProvide multiple times (or not at all).
|
Java
|
apache-2.0
|
sedmelluq/lavaplayer,sedmelluq/lavaplayer
|
java
|
## Code Before:
package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
lastFrame = audioPlayer.provide();
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
return lastFrame.data;
}
@Override
public boolean isOpus() {
return true;
}
}
## Instruction:
Make it safe to call canProvide multiple times (or not at all).
## Code After:
package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
byte[] data = lastFrame != null ? lastFrame.data : null;
lastFrame = null;
return data;
}
@Override
public boolean isOpus() {
return true;
}
}
|
# ... existing code ...
@Override
public boolean canProvide() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
byte[] data = lastFrame != null ? lastFrame.data : null;
lastFrame = null;
return data;
}
@Override
# ... rest of the code ...
|
8f247a0c4564af085bf6b3c9829d2892e818e565
|
tools/update_manifest.py
|
tools/update_manifest.py
|
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
|
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
Add a symlink to downloaded manifest.
|
Add a symlink to downloaded manifest.
|
Python
|
mit
|
zhirsch/destinykioskstatus,zhirsch/destinykioskstatus
|
python
|
## Code Before:
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
## Instruction:
Add a symlink to downloaded manifest.
## Code After:
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
// ... existing code ...
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
// ... rest of the code ...
|
5796a54d10eb3baebda51e3420a818a251406a5c
|
python/test.py
|
python/test.py
|
import sys
from PyQt5 import QtWidgets
from QHexEdit import QHexEdit, QHexEditData
class HexEdit(QHexEdit):
def __init__(self, fileName=None):
super(HexEdit, self).__init__()
file = open(fileName)
data = file.read()
self.setData(data)
self.setReadOnly(False)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# QHexEditData* hexeditdata = QHexEditData::fromFile("data.bin");
data = QHexEditData.fromFile('test.py')
# QHexEdit* hexedit = new QHexEdit();
# hexedit->setData(hexeditdata);
mainWin = QHexEdit()
mainWin.setData(data)
mainWin.show()
sys.exit(app.exec_())
|
import sys
from PyQt5 import QtWidgets, QtGui
from QHexEdit import QHexEdit, QHexEditData
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# QHexEditData* hexeditdata = QHexEditData::fromFile("test.py");
hexeditdata = QHexEditData.fromFile('test.py')
# QHexEdit* hexedit = new QHexEdit();
# hexedit->setData(hexeditdata);
hexedit = QHexEdit()
hexedit.setData(hexeditdata)
hexedit.show()
# hexedit->commentRange(0, 12, "I'm a comment!");
hexedit.commentRange(0, 12, "I'm a comment!")
# hexedit->highlightBackground(0, 10, QColor(Qt::Red));
hexedit.highlightBackground(0, 10, QtGui.QColor(255, 0, 0))
sys.exit(app.exec_())
|
Test more stuff in python
|
Test more stuff in python
|
Python
|
mit
|
parallaxinc/QHexEdit,parallaxinc/QHexEdit
|
python
|
## Code Before:
import sys
from PyQt5 import QtWidgets
from QHexEdit import QHexEdit, QHexEditData
class HexEdit(QHexEdit):
def __init__(self, fileName=None):
super(HexEdit, self).__init__()
file = open(fileName)
data = file.read()
self.setData(data)
self.setReadOnly(False)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# QHexEditData* hexeditdata = QHexEditData::fromFile("data.bin");
data = QHexEditData.fromFile('test.py')
# QHexEdit* hexedit = new QHexEdit();
# hexedit->setData(hexeditdata);
mainWin = QHexEdit()
mainWin.setData(data)
mainWin.show()
sys.exit(app.exec_())
## Instruction:
Test more stuff in python
## Code After:
import sys
from PyQt5 import QtWidgets, QtGui
from QHexEdit import QHexEdit, QHexEditData
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# QHexEditData* hexeditdata = QHexEditData::fromFile("test.py");
hexeditdata = QHexEditData.fromFile('test.py')
# QHexEdit* hexedit = new QHexEdit();
# hexedit->setData(hexeditdata);
hexedit = QHexEdit()
hexedit.setData(hexeditdata)
hexedit.show()
# hexedit->commentRange(0, 12, "I'm a comment!");
hexedit.commentRange(0, 12, "I'm a comment!")
# hexedit->highlightBackground(0, 10, QColor(Qt::Red));
hexedit.highlightBackground(0, 10, QtGui.QColor(255, 0, 0))
sys.exit(app.exec_())
|
...
import sys
from PyQt5 import QtWidgets, QtGui
from QHexEdit import QHexEdit, QHexEditData
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# QHexEditData* hexeditdata = QHexEditData::fromFile("test.py");
hexeditdata = QHexEditData.fromFile('test.py')
# QHexEdit* hexedit = new QHexEdit();
# hexedit->setData(hexeditdata);
hexedit = QHexEdit()
hexedit.setData(hexeditdata)
hexedit.show()
# hexedit->commentRange(0, 12, "I'm a comment!");
hexedit.commentRange(0, 12, "I'm a comment!")
# hexedit->highlightBackground(0, 10, QColor(Qt::Red));
hexedit.highlightBackground(0, 10, QtGui.QColor(255, 0, 0))
sys.exit(app.exec_())
...
|
806d3293ebbbd0f30f923e73def902e9c14a0879
|
tests/test_match.py
|
tests/test_match.py
|
import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
|
import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
def test_matchresult_region_when_first_pyramid_level_fails_to_match():
f = _imread("videotestsrc-full-frame.png")
assert stbt.Region(184, 0, width=92, height=160) == stbt.match(
"videotestsrc-redblue-flipped.png", frame=f).region
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
|
Add test for the region reported for a failed match
|
tests: Add test for the region reported for a failed match
If the match fails at the first level of the pyramid algorithm (when
we're searching in a down-scaled version of the frame) then we have to
up-scale the region we report for the best (but not good enough) match.
This passes currently, but there was no test for it and I want to make
sure I don't break it when I implement `stbt.match_all`.
|
Python
|
lgpl-2.1
|
martynjarvis/stb-tester,LewisHaley/stb-tester,LewisHaley/stb-tester,LewisHaley/stb-tester,martynjarvis/stb-tester,stb-tester/stb-tester,LewisHaley/stb-tester,martynjarvis/stb-tester,LewisHaley/stb-tester,stb-tester/stb-tester,martynjarvis/stb-tester,LewisHaley/stb-tester,martynjarvis/stb-tester,martynjarvis/stb-tester,stb-tester/stb-tester,LewisHaley/stb-tester,martynjarvis/stb-tester,stb-tester/stb-tester
|
python
|
## Code Before:
import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
## Instruction:
tests: Add test for the region reported for a failed match
If the match fails at the first level of the pyramid algorithm (when
we're searching in a down-scaled version of the frame) then we have to
up-scale the region we report for the best (but not good enough) match.
This passes currently, but there was no test for it and I want to make
sure I don't break it when I implement `stbt.match_all`.
## Code After:
import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
def test_matchresult_region_when_first_pyramid_level_fails_to_match():
f = _imread("videotestsrc-full-frame.png")
assert stbt.Region(184, 0, width=92, height=160) == stbt.match(
"videotestsrc-redblue-flipped.png", frame=f).region
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
|
// ... existing code ...
stbt.match(black(30, 30), frame=black()))
def test_matchresult_region_when_first_pyramid_level_fails_to_match():
f = _imread("videotestsrc-full-frame.png")
assert stbt.Region(184, 0, width=92, height=160) == stbt.match(
"videotestsrc-redblue-flipped.png", frame=f).region
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
// ... rest of the code ...
|
e2609690520f1913789f1f5283e9b5b06d1db08e
|
samples/java/computer-database/app/models/Computer.java
|
samples/java/computer-database/app/models/Computer.java
|
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import com.avaje.ebean.*;
/**
* Computer entity managed by Ebean
*/
@Entity
public class Computer extends Model {
@Id
public Long id;
@Constraints.Required
public String name;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date introduced;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date discontinued;
@ManyToOne
public Company company;
/**
* Generic query helper for entity Computer with id Long
*/
public static Finder<Long,Computer> find = new Finder<Long,Computer>(Long.class, Computer.class);
/**
* Return a page of computer
*
* @param page Page to display
* @param pageSize Number of computers per page
* @param sortBy Computer property used for sorting
* @param order Sort order (either or asc or desc)
* @param filter Filter applied on the name column
*/
public static Page<Computer> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
.getPage(page);
}
}
|
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import com.avaje.ebean.*;
/**
* Computer entity managed by Ebean
*/
@Entity
public class Computer extends Model {
@Id
public Long id;
@Constraints.Required
public String name;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date introduced;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date discontinued;
@ManyToOne
public Company company;
/**
* Generic query helper for entity Computer with id Long
*/
public static Finder<Long,Computer> find = new Finder<Long,Computer>(Long.class, Computer.class);
/**
* Return a page of computer
*
* @param page Page to display
* @param pageSize Number of computers per page
* @param sortBy Computer property used for sorting
* @param order Sort order (either or asc or desc)
* @param filter Filter applied on the name column
*/
public static Page<Computer> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
}
|
Fix to avoid asynchronous Ebean fetchAhead (automatically fetches the next page)
|
Fix to avoid asynchronous Ebean fetchAhead (automatically fetches the next page)
When a page is accessed, Ebean LimitOffsetPagingQuery.java automatically
starts a new background thread to fetch the next page. This thread uses
a database connection that can be still alive after the HTTP request was
processed. On heavy load, this problem causes the following exception:
java.sql.SQLException: Timed out waiting for a free available
connection.
FetchAhead is useless in a stateless web application. Therefore, it must
be disabled using setFetchAhead(false).
|
Java
|
apache-2.0
|
rajeshpg/playframework,benmccann/playframework,Shenker93/playframework,wegtam/playframework,wegtam/playframework,Shenker93/playframework,Shenker93/playframework,mkurz/playframework,playframework/playframework,Shruti9520/playframework,aradchykov/playframework,hagl/playframework,richdougherty/playframework,richdougherty/playframework,zaneli/playframework,Shruti9520/playframework,hagl/playframework,playframework/playframework,benmccann/playframework,wegtam/playframework,hagl/playframework,zaneli/playframework,wsargent/playframework,mkurz/playframework,ktoso/playframework,ktoso/playframework,zaneli/playframework,Shruti9520/playframework,marcospereira/playframework,richdougherty/playframework,wegtam/playframework,wsargent/playframework,mkurz/playframework,zaneli/playframework,richdougherty/playframework,aradchykov/playframework,Shruti9520/playframework,marcospereira/playframework,hagl/playframework,mkurz/playframework,rajeshpg/playframework,Shenker93/playframework,aradchykov/playframework,marcospereira/playframework,marcospereira/playframework,wsargent/playframework,aradchykov/playframework,rajeshpg/playframework,ktoso/playframework,rajeshpg/playframework,benmccann/playframework,benmccann/playframework,playframework/playframework,wsargent/playframework,ktoso/playframework
|
java
|
## Code Before:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import com.avaje.ebean.*;
/**
* Computer entity managed by Ebean
*/
@Entity
public class Computer extends Model {
@Id
public Long id;
@Constraints.Required
public String name;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date introduced;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date discontinued;
@ManyToOne
public Company company;
/**
* Generic query helper for entity Computer with id Long
*/
public static Finder<Long,Computer> find = new Finder<Long,Computer>(Long.class, Computer.class);
/**
* Return a page of computer
*
* @param page Page to display
* @param pageSize Number of computers per page
* @param sortBy Computer property used for sorting
* @param order Sort order (either or asc or desc)
* @param filter Filter applied on the name column
*/
public static Page<Computer> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
.getPage(page);
}
}
## Instruction:
Fix to avoid asynchronous Ebean fetchAhead (automatically fetches the next page)
When a page is accessed, Ebean LimitOffsetPagingQuery.java automatically
starts a new background thread to fetch the next page. This thread uses
a database connection that can be still alive after the HTTP request was
processed. On heavy load, this problem causes the following exception:
java.sql.SQLException: Timed out waiting for a free available
connection.
FetchAhead is useless in a stateless web application. Therefore, it must
be disabled using setFetchAhead(false).
## Code After:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import com.avaje.ebean.*;
/**
* Computer entity managed by Ebean
*/
@Entity
public class Computer extends Model {
@Id
public Long id;
@Constraints.Required
public String name;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date introduced;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date discontinued;
@ManyToOne
public Company company;
/**
* Generic query helper for entity Computer with id Long
*/
public static Finder<Long,Computer> find = new Finder<Long,Computer>(Long.class, Computer.class);
/**
* Return a page of computer
*
* @param page Page to display
* @param pageSize Number of computers per page
* @param sortBy Computer property used for sorting
* @param order Sort order (either or asc or desc)
* @param filter Filter applied on the name column
*/
public static Page<Computer> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
}
|
// ... existing code ...
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
// ... rest of the code ...
|
41886d53f3c007f5a23781361e3b638afb62ea6d
|
Include/node.h
|
Include/node.h
|
/* Parse tree node interface */
#ifndef Py_NODE_H
#define Py_NODE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _node {
short n_type;
char *n_str;
int n_lineno;
int n_nchildren;
struct _node *n_child;
} node;
extern DL_IMPORT(node *) PyNode_New(int type);
extern DL_IMPORT(int) PyNode_AddChild(node *n, int type,
char *str, int lineno);
extern DL_IMPORT(void) PyNode_Free(node *n);
/* Node access functions */
#define NCH(n) ((n)->n_nchildren)
#define CHILD(n, i) (&(n)->n_child[i])
#define TYPE(n) ((n)->n_type)
#define STR(n) ((n)->n_str)
/* Assert that the type of a node is what we expect */
#ifndef Py_DEBUG
#define REQ(n, type) { /*pass*/ ; }
#else
#define REQ(n, type) \
{ if (TYPE(n) != (type)) { \
fprintf(stderr, "FATAL: node type %d, required %d\n", \
TYPE(n), type); \
abort(); \
} }
#endif
extern DL_IMPORT(void) PyNode_ListTree(node *);
#ifdef __cplusplus
}
#endif
#endif /* !Py_NODE_H */
|
/* Parse tree node interface */
#ifndef Py_NODE_H
#define Py_NODE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _node {
short n_type;
char *n_str;
int n_lineno;
int n_nchildren;
struct _node *n_child;
} node;
extern DL_IMPORT(node *) PyNode_New(int type);
extern DL_IMPORT(int) PyNode_AddChild(node *n, int type,
char *str, int lineno);
extern DL_IMPORT(void) PyNode_Free(node *n);
/* Node access functions */
#define NCH(n) ((n)->n_nchildren)
#define CHILD(n, i) (&(n)->n_child[i])
#define TYPE(n) ((n)->n_type)
#define STR(n) ((n)->n_str)
/* Assert that the type of a node is what we expect */
#define REQ(n, type) assert(TYPE(n) == (type))
extern DL_IMPORT(void) PyNode_ListTree(node *);
#ifdef __cplusplus
}
#endif
#endif /* !Py_NODE_H */
|
Use an assert() for the REQ() macro instead of making up our own assertion.
|
Use an assert() for the REQ() macro instead of making up our own
assertion.
|
C
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
c
|
## Code Before:
/* Parse tree node interface */
#ifndef Py_NODE_H
#define Py_NODE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _node {
short n_type;
char *n_str;
int n_lineno;
int n_nchildren;
struct _node *n_child;
} node;
extern DL_IMPORT(node *) PyNode_New(int type);
extern DL_IMPORT(int) PyNode_AddChild(node *n, int type,
char *str, int lineno);
extern DL_IMPORT(void) PyNode_Free(node *n);
/* Node access functions */
#define NCH(n) ((n)->n_nchildren)
#define CHILD(n, i) (&(n)->n_child[i])
#define TYPE(n) ((n)->n_type)
#define STR(n) ((n)->n_str)
/* Assert that the type of a node is what we expect */
#ifndef Py_DEBUG
#define REQ(n, type) { /*pass*/ ; }
#else
#define REQ(n, type) \
{ if (TYPE(n) != (type)) { \
fprintf(stderr, "FATAL: node type %d, required %d\n", \
TYPE(n), type); \
abort(); \
} }
#endif
extern DL_IMPORT(void) PyNode_ListTree(node *);
#ifdef __cplusplus
}
#endif
#endif /* !Py_NODE_H */
## Instruction:
Use an assert() for the REQ() macro instead of making up our own
assertion.
## Code After:
/* Parse tree node interface */
#ifndef Py_NODE_H
#define Py_NODE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _node {
short n_type;
char *n_str;
int n_lineno;
int n_nchildren;
struct _node *n_child;
} node;
extern DL_IMPORT(node *) PyNode_New(int type);
extern DL_IMPORT(int) PyNode_AddChild(node *n, int type,
char *str, int lineno);
extern DL_IMPORT(void) PyNode_Free(node *n);
/* Node access functions */
#define NCH(n) ((n)->n_nchildren)
#define CHILD(n, i) (&(n)->n_child[i])
#define TYPE(n) ((n)->n_type)
#define STR(n) ((n)->n_str)
/* Assert that the type of a node is what we expect */
#define REQ(n, type) assert(TYPE(n) == (type))
extern DL_IMPORT(void) PyNode_ListTree(node *);
#ifdef __cplusplus
}
#endif
#endif /* !Py_NODE_H */
|
# ... existing code ...
#define STR(n) ((n)->n_str)
/* Assert that the type of a node is what we expect */
#define REQ(n, type) assert(TYPE(n) == (type))
extern DL_IMPORT(void) PyNode_ListTree(node *);
# ... rest of the code ...
|
69d88adcedaf3779e5bf5a5757a21c71d4aa3016
|
novajoin/errors.py
|
novajoin/errors.py
|
class ConfigurationError(StandardError):
def __init__(self, message):
StandardError.__init__(self, message)
|
class ConfigurationError(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
|
Use Exception instead of StandardError
|
Use Exception instead of StandardError
StandardError was deprecated in python 3.X.
|
Python
|
apache-2.0
|
rcritten/novajoin
|
python
|
## Code Before:
class ConfigurationError(StandardError):
def __init__(self, message):
StandardError.__init__(self, message)
## Instruction:
Use Exception instead of StandardError
StandardError was deprecated in python 3.X.
## Code After:
class ConfigurationError(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
|
// ... existing code ...
class ConfigurationError(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
// ... rest of the code ...
|
ddc44c6673cff4121eaaa47d8d075d63b82a85fe
|
runreport.py
|
runreport.py
|
import os
import json
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
result = test_case.run()
print(json.dumps(result))
|
import os
import json
import argparse
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pretty", help="Pretty print test results",
action="store_true")
args = parser.parse_args()
def test_passed(report):
""" Whether all components of a scraper test succeeded """
if report["status"] != "OK":
return False
for result in report["result"].values():
if result["missing"]:
return False
return True
def print_report(report):
""" Converts test report dictionary to a human-readable format """
if report["status"] == "OK":
result = "PASS" if test_passed(report) else "FAIL"
else:
result = "EXCEPTION"
print("{0} : {1}".format(result, report["url"]))
if report["status"] == "EXCEPTION":
print(report["message"])
elif test_passed(report):
r = report["result"]
stats = ", ".join(["{0} {1}".format(len(r[c]["found"]), c) for c in r])
print("Found " + stats)
else:
for category, result in report["result"].items():
if result["missing"]:
count = len(result["missing"])
print("Missing {0} {1}:".format(count, category))
for item in result["missing"]:
print(item)
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
report = test_case.run()
if args.pretty:
print_report(report)
print("\n")
else:
print(json.dumps(report))
|
Add optional pretty printing to test runner
|
Add optional pretty printing to test runner
|
Python
|
agpl-3.0
|
asm-products/saulify-web,asm-products/saulify-web,asm-products/saulify-web
|
python
|
## Code Before:
import os
import json
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
result = test_case.run()
print(json.dumps(result))
## Instruction:
Add optional pretty printing to test runner
## Code After:
import os
import json
import argparse
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pretty", help="Pretty print test results",
action="store_true")
args = parser.parse_args()
def test_passed(report):
""" Whether all components of a scraper test succeeded """
if report["status"] != "OK":
return False
for result in report["result"].values():
if result["missing"]:
return False
return True
def print_report(report):
""" Converts test report dictionary to a human-readable format """
if report["status"] == "OK":
result = "PASS" if test_passed(report) else "FAIL"
else:
result = "EXCEPTION"
print("{0} : {1}".format(result, report["url"]))
if report["status"] == "EXCEPTION":
print(report["message"])
elif test_passed(report):
r = report["result"]
stats = ", ".join(["{0} {1}".format(len(r[c]["found"]), c) for c in r])
print("Found " + stats)
else:
for category, result in report["result"].items():
if result["missing"]:
count = len(result["missing"])
print("Missing {0} {1}:".format(count, category))
for item in result["missing"]:
print(item)
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
report = test_case.run()
if args.pretty:
print_report(report)
print("\n")
else:
print(json.dumps(report))
|
# ... existing code ...
import os
import json
import argparse
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pretty", help="Pretty print test results",
action="store_true")
args = parser.parse_args()
def test_passed(report):
""" Whether all components of a scraper test succeeded """
if report["status"] != "OK":
return False
for result in report["result"].values():
if result["missing"]:
return False
return True
def print_report(report):
""" Converts test report dictionary to a human-readable format """
if report["status"] == "OK":
result = "PASS" if test_passed(report) else "FAIL"
else:
result = "EXCEPTION"
print("{0} : {1}".format(result, report["url"]))
if report["status"] == "EXCEPTION":
print(report["message"])
elif test_passed(report):
r = report["result"]
stats = ", ".join(["{0} {1}".format(len(r[c]["found"]), c) for c in r])
print("Found " + stats)
else:
for category, result in report["result"].items():
if result["missing"]:
count = len(result["missing"])
print("Missing {0} {1}:".format(count, category))
for item in result["missing"]:
print(item)
if __name__ == "__main__":
# ... modified code ...
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
report = test_case.run()
if args.pretty:
print_report(report)
print("\n")
else:
print(json.dumps(report))
# ... rest of the code ...
|
10c9dbbe075eb1e584dec88b3c78f71c84a8708f
|
src/main/java/com/raoulvdberge/refinedstorage/render/tesr/PatternItemStackTileRenderer.java
|
src/main/java/com/raoulvdberge/refinedstorage/render/tesr/PatternItemStackTileRenderer.java
|
package com.raoulvdberge.refinedstorage.render.tesr;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.CraftingPattern;
import com.raoulvdberge.refinedstorage.item.PatternItem;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.item.ItemStack;
public class PatternItemStackTileRenderer extends ItemStackTileEntityRenderer {
/* TODO @Override
public void renderByItem(ItemStack stack) {
CraftingPattern pattern = PatternItem.fromCache(null, stack);
ItemStack outputStack = pattern.getOutputs().get(0);
outputStack.getItem().getTileEntityItemStackRenderer().renderByItem(outputStack);
}*/
}
|
package com.raoulvdberge.refinedstorage.render.tesr;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.CraftingPattern;
import com.raoulvdberge.refinedstorage.item.PatternItem;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.item.ItemStack;
public class PatternItemStackTileRenderer extends ItemStackTileEntityRenderer {
@Override
public void func_228364_a_(ItemStack stack, MatrixStack matrixStack, IRenderTypeBuffer renderTypeBuffer, int p_228364_4_, int p_228364_5_) {
CraftingPattern pattern = PatternItem.fromCache(null, stack);
ItemStack outputStack = pattern.getOutputs().get(0);
outputStack.getItem().getTileEntityItemStackRenderer().func_228364_a_(outputStack, matrixStack, renderTypeBuffer, p_228364_4_, p_228364_5_);
}
}
|
Fix pattern item stack tile renderer
|
Fix pattern item stack tile renderer
|
Java
|
mit
|
raoulvdberge/refinedstorage,raoulvdberge/refinedstorage
|
java
|
## Code Before:
package com.raoulvdberge.refinedstorage.render.tesr;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.CraftingPattern;
import com.raoulvdberge.refinedstorage.item.PatternItem;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.item.ItemStack;
public class PatternItemStackTileRenderer extends ItemStackTileEntityRenderer {
/* TODO @Override
public void renderByItem(ItemStack stack) {
CraftingPattern pattern = PatternItem.fromCache(null, stack);
ItemStack outputStack = pattern.getOutputs().get(0);
outputStack.getItem().getTileEntityItemStackRenderer().renderByItem(outputStack);
}*/
}
## Instruction:
Fix pattern item stack tile renderer
## Code After:
package com.raoulvdberge.refinedstorage.render.tesr;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.CraftingPattern;
import com.raoulvdberge.refinedstorage.item.PatternItem;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.item.ItemStack;
public class PatternItemStackTileRenderer extends ItemStackTileEntityRenderer {
@Override
public void func_228364_a_(ItemStack stack, MatrixStack matrixStack, IRenderTypeBuffer renderTypeBuffer, int p_228364_4_, int p_228364_5_) {
CraftingPattern pattern = PatternItem.fromCache(null, stack);
ItemStack outputStack = pattern.getOutputs().get(0);
outputStack.getItem().getTileEntityItemStackRenderer().func_228364_a_(outputStack, matrixStack, renderTypeBuffer, p_228364_4_, p_228364_5_);
}
}
|
...
package com.raoulvdberge.refinedstorage.render.tesr;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.CraftingPattern;
import com.raoulvdberge.refinedstorage.item.PatternItem;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.item.ItemStack;
public class PatternItemStackTileRenderer extends ItemStackTileEntityRenderer {
@Override
public void func_228364_a_(ItemStack stack, MatrixStack matrixStack, IRenderTypeBuffer renderTypeBuffer, int p_228364_4_, int p_228364_5_) {
CraftingPattern pattern = PatternItem.fromCache(null, stack);
ItemStack outputStack = pattern.getOutputs().get(0);
outputStack.getItem().getTileEntityItemStackRenderer().func_228364_a_(outputStack, matrixStack, renderTypeBuffer, p_228364_4_, p_228364_5_);
}
}
...
|
29baa0a57fe49c790d4ef5dcdde1e744fc83efde
|
boundary/alarm_create.py
|
boundary/alarm_create.py
|
from boundary import AlarmModify
class AlarmCreate(AlarmModify):
def __init__(self, **kwargs):
AlarmModify.__init__(self, False)
self._kwargs = kwargs
self.method = "POST"
self._alarm_result = None
def add_arguments(self):
self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True,
metavar='alarm_name', help='Name of the alarm')
AlarmModify.add_arguments(self)
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
def get_api_parameters(self):
AlarmModify.get_api_parameters(self)
self.path = 'v1/alarms'
|
from boundary import AlarmModify
class AlarmCreate(AlarmModify):
def __init__(self, **kwargs):
AlarmModify.__init__(self, False)
self._kwargs = kwargs
self.method = "POST"
self._alarm_result = None
def add_arguments(self):
self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True,
metavar='alarm_name', help='Name of the alarm')
AlarmModify.add_arguments(self)
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
|
Remove no needed to duplicate parent behaviour
|
Remove no needed to duplicate parent behaviour
|
Python
|
apache-2.0
|
boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli
|
python
|
## Code Before:
from boundary import AlarmModify
class AlarmCreate(AlarmModify):
def __init__(self, **kwargs):
AlarmModify.__init__(self, False)
self._kwargs = kwargs
self.method = "POST"
self._alarm_result = None
def add_arguments(self):
self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True,
metavar='alarm_name', help='Name of the alarm')
AlarmModify.add_arguments(self)
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
def get_api_parameters(self):
AlarmModify.get_api_parameters(self)
self.path = 'v1/alarms'
## Instruction:
Remove no needed to duplicate parent behaviour
## Code After:
from boundary import AlarmModify
class AlarmCreate(AlarmModify):
def __init__(self, **kwargs):
AlarmModify.__init__(self, False)
self._kwargs = kwargs
self.method = "POST"
self._alarm_result = None
def add_arguments(self):
self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True,
metavar='alarm_name', help='Name of the alarm')
AlarmModify.add_arguments(self)
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
|
// ... existing code ...
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
// ... rest of the code ...
|
022d8b992a88fd4c489c068ba57b4b2fcf6dde98
|
cloudsizzle/studyplanner/completedstudies/models.py
|
cloudsizzle/studyplanner/completedstudies/models.py
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CompletedCourse(models.Model):
"""
Model for completed studies
"""
student = models.ForeignKey(User, related_name='completed_courses')
code = models.CharField(max_length=11)
name = models.CharField(max_length=100)
cr = models.IntegerField()
ocr = models.IntegerField()
grade = models.CharField(max_length=5)
date = models.DateField()
teacher = models.CharField(max_length=60)
class Teacher(models.Model):
"""
should be updated for the teachers to combine them with course information
"""
name = models.CharField(max_length = 30)
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CompletedCourse(models.Model):
"""
Model for completed studies
"""
student = models.ForeignKey(User, related_name='completed_courses')
code = models.CharField(max_length=11)
name = models.CharField(max_length=100)
cr = models.IntegerField(null=True)
ocr = models.IntegerField(null=True)
grade = models.CharField(max_length=5)
date = models.DateField()
teacher = models.CharField(max_length=60)
class Teacher(models.Model):
"""
should be updated for the teachers to combine them with course information
"""
name = models.CharField(max_length = 30)
|
Allow null values for ocr and cr fields of CompletedCourse
|
Allow null values for ocr and cr fields of CompletedCourse
|
Python
|
mit
|
jpvanhal/cloudsizzle,jpvanhal/cloudsizzle
|
python
|
## Code Before:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CompletedCourse(models.Model):
"""
Model for completed studies
"""
student = models.ForeignKey(User, related_name='completed_courses')
code = models.CharField(max_length=11)
name = models.CharField(max_length=100)
cr = models.IntegerField()
ocr = models.IntegerField()
grade = models.CharField(max_length=5)
date = models.DateField()
teacher = models.CharField(max_length=60)
class Teacher(models.Model):
"""
should be updated for the teachers to combine them with course information
"""
name = models.CharField(max_length = 30)
## Instruction:
Allow null values for ocr and cr fields of CompletedCourse
## Code After:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CompletedCourse(models.Model):
"""
Model for completed studies
"""
student = models.ForeignKey(User, related_name='completed_courses')
code = models.CharField(max_length=11)
name = models.CharField(max_length=100)
cr = models.IntegerField(null=True)
ocr = models.IntegerField(null=True)
grade = models.CharField(max_length=5)
date = models.DateField()
teacher = models.CharField(max_length=60)
class Teacher(models.Model):
"""
should be updated for the teachers to combine them with course information
"""
name = models.CharField(max_length = 30)
|
...
"""
Model for completed studies
"""
student = models.ForeignKey(User, related_name='completed_courses')
code = models.CharField(max_length=11)
name = models.CharField(max_length=100)
cr = models.IntegerField(null=True)
ocr = models.IntegerField(null=True)
grade = models.CharField(max_length=5)
date = models.DateField()
teacher = models.CharField(max_length=60)
class Teacher(models.Model):
"""
should be updated for the teachers to combine them with course information
...
|
a013927ee9772e05ae4255cff98ecfe4819f205c
|
flask_app/__init__.py
|
flask_app/__init__.py
|
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See configuration.py for possible configuration objects
app.config.from_object('flask_app.configuration.Development')
import flask_app.database
import flask_app.views
|
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See configuration.py for possible configuration objects
app.config.from_object('flask_app.configuration.Development')
import flask_app.database
import flask_app.views
|
Set login view for login_required
|
Set login view for login_required
|
Python
|
mit
|
szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft
|
python
|
## Code Before:
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See configuration.py for possible configuration objects
app.config.from_object('flask_app.configuration.Development')
import flask_app.database
import flask_app.views
## Instruction:
Set login view for login_required
## Code After:
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See configuration.py for possible configuration objects
app.config.from_object('flask_app.configuration.Development')
import flask_app.database
import flask_app.views
|
# ... existing code ...
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# ... rest of the code ...
|
c36301ec14e6d10762e613c0c52bf0e48baf9df9
|
goatools/godag/consts.py
|
goatools/godag/consts.py
|
"""GO-DAG constants."""
__copyright__ = "Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
NAMESPACE2NS = {
'biological_process' : 'BP',
'molecular_function' : 'MF',
'cellular_component' : 'CC'}
RELATIONSHIP_LIST = ['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']
def __init__(self):
self.relationships = set(self.RELATIONSHIP_LIST)
# Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved.
|
"""GO-DAG constants."""
__copyright__ = "Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
NAMESPACE2NS = {
'biological_process' : 'BP',
'molecular_function' : 'MF',
'cellular_component' : 'CC'}
# https://owlcollab.github.io/oboformat/doc/GO.format.obo-1_4.html
RELATIONSHIP_LIST = ['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']
def __init__(self):
self.relationships = set(self.RELATIONSHIP_LIST)
# Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved.
|
Add comment with link to more info
|
Add comment with link to more info
|
Python
|
bsd-2-clause
|
tanghaibao/goatools,tanghaibao/goatools
|
python
|
## Code Before:
"""GO-DAG constants."""
__copyright__ = "Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
NAMESPACE2NS = {
'biological_process' : 'BP',
'molecular_function' : 'MF',
'cellular_component' : 'CC'}
RELATIONSHIP_LIST = ['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']
def __init__(self):
self.relationships = set(self.RELATIONSHIP_LIST)
# Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved.
## Instruction:
Add comment with link to more info
## Code After:
"""GO-DAG constants."""
__copyright__ = "Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
NAMESPACE2NS = {
'biological_process' : 'BP',
'molecular_function' : 'MF',
'cellular_component' : 'CC'}
# https://owlcollab.github.io/oboformat/doc/GO.format.obo-1_4.html
RELATIONSHIP_LIST = ['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']
def __init__(self):
self.relationships = set(self.RELATIONSHIP_LIST)
# Copyright (C) 2010-2018, DV Klopfenstein, H Tang, All rights reserved.
|
// ... existing code ...
'molecular_function' : 'MF',
'cellular_component' : 'CC'}
# https://owlcollab.github.io/oboformat/doc/GO.format.obo-1_4.html
RELATIONSHIP_LIST = ['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']
def __init__(self):
// ... rest of the code ...
|
246c62e9bf2e8f1f98e2d8fada06e6dbefef500e
|
code/framework/java-server/src/main/java/io/github/ibuildthecloud/gdapi/util/ProxyUtils.java
|
code/framework/java-server/src/main/java/io/github/ibuildthecloud/gdapi/util/ProxyUtils.java
|
package io.github.ibuildthecloud.gdapi.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ProxyUtils {
@SuppressWarnings("unchecked")
public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
final Object obj = new Object();
return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(obj, args);
}
if (method.getName().startsWith("get")) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
Object val = map.get(name);
if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
return ((Long)val).intValue();
}
return val;
}
if (method.getName().startsWith("set") && args.length == 1) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
map.put(name, args[0]);
}
return null;
}
});
}
}
|
package io.github.ibuildthecloud.gdapi.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ProxyUtils {
@SuppressWarnings("unchecked")
public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
final Object obj = new Object();
return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
@SuppressWarnings("rawtypes")
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(obj, args);
}
if (method.getName().startsWith("get")) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
Object val = map.get(name);
if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
return ((Long)val).intValue();
}
if (val instanceof String && method.getReturnType().isEnum()) {
return Enum.valueOf((Class<? extends Enum>)method.getReturnType(), val.toString());
}
return val;
}
if (method.getName().startsWith("set") && args.length == 1) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
map.put(name, args[0]);
}
return null;
}
});
}
}
|
Support enums in proxying request objects
|
Support enums in proxying request objects
|
Java
|
apache-2.0
|
vincent99/cattle,rancher/cattle,cloudnautique/cattle,cjellick/cattle,cloudnautique/cattle,rancherio/cattle,rancherio/cattle,cjellick/cattle,cjellick/cattle,vincent99/cattle,cjellick/cattle,vincent99/cattle,rancherio/cattle,cloudnautique/cattle,cloudnautique/cattle,rancher/cattle,rancher/cattle
|
java
|
## Code Before:
package io.github.ibuildthecloud.gdapi.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ProxyUtils {
@SuppressWarnings("unchecked")
public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
final Object obj = new Object();
return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(obj, args);
}
if (method.getName().startsWith("get")) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
Object val = map.get(name);
if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
return ((Long)val).intValue();
}
return val;
}
if (method.getName().startsWith("set") && args.length == 1) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
map.put(name, args[0]);
}
return null;
}
});
}
}
## Instruction:
Support enums in proxying request objects
## Code After:
package io.github.ibuildthecloud.gdapi.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ProxyUtils {
@SuppressWarnings("unchecked")
public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
final Object obj = new Object();
return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
@SuppressWarnings("rawtypes")
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(obj, args);
}
if (method.getName().startsWith("get")) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
Object val = map.get(name);
if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
return ((Long)val).intValue();
}
if (val instanceof String && method.getReturnType().isEnum()) {
return Enum.valueOf((Class<? extends Enum>)method.getReturnType(), val.toString());
}
return val;
}
if (method.getName().startsWith("set") && args.length == 1) {
String name = StringUtils.uncapitalize(method.getName().substring(3));
map.put(name, args[0]);
}
return null;
}
});
}
}
|
...
final Object obj = new Object();
return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
@SuppressWarnings("rawtypes")
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
...
Object val = map.get(name);
if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
return ((Long)val).intValue();
}
if (val instanceof String && method.getReturnType().isEnum()) {
return Enum.valueOf((Class<? extends Enum>)method.getReturnType(), val.toString());
}
return val;
}
...
|
3feccc140c0371becccb3f80bef00d30b4bc15bf
|
corehq/sql_accessors/migrations/0056_add_hashlib_functions.py
|
corehq/sql_accessors/migrations/0056_add_hashlib_functions.py
|
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
Add comment about moving hashlib extention creation to test harness
|
Add comment about moving hashlib extention creation to test harness
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
python
|
## Code Before:
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
## Instruction:
Add comment about moving hashlib extention creation to test harness
## Code After:
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
// ... existing code ...
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
// ... rest of the code ...
|
4f776ca2260419c06c2594568c73ce279426d039
|
GenotypeNetwork/test_genotype_network.py
|
GenotypeNetwork/test_genotype_network.py
|
import GenotypeNetwork as gn
import os
import networkx as nx
GN = gn.GenotypeNetwork()
GN.read_sequences('test/Demo_052715.fasta')
GN.generate_genotype_network()
GN.write_genotype_network('test/Demo_052715.pkl')
GN.read_genotype_network('test/Demo_052715.pkl')
def test_read_sequences_works_correctly():
"""
Checks that GN.read_sequences reads in correct number of sequences.
"""
assert len(GN.sequences) == 3
def test_generate_genotype_network():
"""
Checks that the number of nodes equals the number of sequences
Checks number of edges
"""
assert len(GN.sequences) == len(GN.G.nodes())
assert len(GN.G.edges()) == 2 # This will change based on dataset
def test_write_genotype_network():
"""
Checks that the pickled network is written to disk.
"""
assert 'Demo_052715.pkl' in os.listdir('Test')
def test_read_genotype_network():
"""
Checks that the genotype network is being loaded correctly by counting
nodes in a test pkl file.
"""
G = nx.read_gpickle('Test/Demo_052715.pkl')
# The length of the test file
assert len(G.nodes()) == 3
|
import GenotypeNetwork as gn
import os
import networkx as nx
# Change cwd for tests to the current path.
here = os.path.dirname(os.path.realpath(__file__))
os.chdir(here)
GN = gn.GenotypeNetwork()
GN.read_sequences('test/Demo_052715.fasta')
GN.generate_genotype_network()
GN.write_genotype_network('test/Demo_052715.pkl')
GN.read_genotype_network('test/Demo_052715.pkl')
def test_read_sequences_works_correctly():
"""
Checks that GN.read_sequences reads in correct number of sequences.
"""
assert len(GN.sequences) == 3
def test_generate_genotype_network():
"""
Checks that the number of nodes equals the number of sequences
Checks number of edges
"""
assert len(GN.sequences) == len(GN.G.nodes())
assert len(GN.G.edges()) == 2 # This will change based on dataset
def test_write_genotype_network():
"""
Checks that the pickled network is written to disk.
"""
assert 'Demo_052715.pkl' in os.listdir('Test')
def test_read_genotype_network():
"""
Checks that the genotype network is being loaded correctly by counting
nodes in a test pkl file.
"""
G = nx.read_gpickle('Test/Demo_052715.pkl')
# The length of the test file
assert len(G.nodes()) == 3
|
Make tests run from correct directory.
|
Make tests run from correct directory.
|
Python
|
mit
|
ericmjl/genotype-network
|
python
|
## Code Before:
import GenotypeNetwork as gn
import os
import networkx as nx
GN = gn.GenotypeNetwork()
GN.read_sequences('test/Demo_052715.fasta')
GN.generate_genotype_network()
GN.write_genotype_network('test/Demo_052715.pkl')
GN.read_genotype_network('test/Demo_052715.pkl')
def test_read_sequences_works_correctly():
"""
Checks that GN.read_sequences reads in correct number of sequences.
"""
assert len(GN.sequences) == 3
def test_generate_genotype_network():
"""
Checks that the number of nodes equals the number of sequences
Checks number of edges
"""
assert len(GN.sequences) == len(GN.G.nodes())
assert len(GN.G.edges()) == 2 # This will change based on dataset
def test_write_genotype_network():
"""
Checks that the pickled network is written to disk.
"""
assert 'Demo_052715.pkl' in os.listdir('Test')
def test_read_genotype_network():
"""
Checks that the genotype network is being loaded correctly by counting
nodes in a test pkl file.
"""
G = nx.read_gpickle('Test/Demo_052715.pkl')
# The length of the test file
assert len(G.nodes()) == 3
## Instruction:
Make tests run from correct directory.
## Code After:
import GenotypeNetwork as gn
import os
import networkx as nx
# Change cwd for tests to the current path.
here = os.path.dirname(os.path.realpath(__file__))
os.chdir(here)
GN = gn.GenotypeNetwork()
GN.read_sequences('test/Demo_052715.fasta')
GN.generate_genotype_network()
GN.write_genotype_network('test/Demo_052715.pkl')
GN.read_genotype_network('test/Demo_052715.pkl')
def test_read_sequences_works_correctly():
"""
Checks that GN.read_sequences reads in correct number of sequences.
"""
assert len(GN.sequences) == 3
def test_generate_genotype_network():
"""
Checks that the number of nodes equals the number of sequences
Checks number of edges
"""
assert len(GN.sequences) == len(GN.G.nodes())
assert len(GN.G.edges()) == 2 # This will change based on dataset
def test_write_genotype_network():
"""
Checks that the pickled network is written to disk.
"""
assert 'Demo_052715.pkl' in os.listdir('Test')
def test_read_genotype_network():
"""
Checks that the genotype network is being loaded correctly by counting
nodes in a test pkl file.
"""
G = nx.read_gpickle('Test/Demo_052715.pkl')
# The length of the test file
assert len(G.nodes()) == 3
|
// ... existing code ...
import GenotypeNetwork as gn
import os
import networkx as nx
# Change cwd for tests to the current path.
here = os.path.dirname(os.path.realpath(__file__))
os.chdir(here)
GN = gn.GenotypeNetwork()
GN.read_sequences('test/Demo_052715.fasta')
// ... rest of the code ...
|
5fc72fab36b3c29ccadc64aac3ffcb8d6bf56c48
|
osf/models/subject.py
|
osf/models/subject.py
|
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73
parents = models.ManyToManyField('self', symmetrical=False, related_name='children')
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
@property
def child_count(self):
"""For v1 compat."""
return self.children.count()
def get_absolute_url(self):
return self.absolute_api_v2_url
|
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73
parents = models.ManyToManyField('self', symmetrical=False, related_name='children')
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
@property
def child_count(self):
"""For v1 compat."""
return self.children.count()
def get_absolute_url(self):
return self.absolute_api_v2_url
@property
def hierarchy(self):
if self.parents.exists():
return self.parents.first().hierarchy + [self._id]
return [self._id]
|
Add Subject.hierarchy to djangosf model
|
Add Subject.hierarchy to djangosf model
|
Python
|
apache-2.0
|
Johnetordoff/osf.io,mluo613/osf.io,acshi/osf.io,hmoco/osf.io,alexschiller/osf.io,adlius/osf.io,leb2dg/osf.io,adlius/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,baylee-d/osf.io,saradbowman/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,acshi/osf.io,erinspace/osf.io,mattclark/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,icereval/osf.io,acshi/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,binoculars/osf.io,acshi/osf.io,crcresearch/osf.io,alexschiller/osf.io,chennan47/osf.io,mluo613/osf.io,laurenrevere/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,adlius/osf.io,hmoco/osf.io,TomBaxter/osf.io,binoculars/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,chennan47/osf.io,adlius/osf.io,crcresearch/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,baylee-d/osf.io,baylee-d/osf.io,hmoco/osf.io,crcresearch/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,hmoco/osf.io,caseyrollins/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,caneruguz/osf.io,mattclark/osf.io,laurenrevere/osf.io,icereval/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,pattisdr/osf.io,chrisseto/osf.io,caneruguz/osf.io,TomBaxter/osf.io,caneruguz/osf.io,felliott/osf.io,sloria/osf.io,sloria/osf.io,mluo613/osf.io,chrisseto/osf.io,cslzchen/osf.io,erinspace/osf.io,cslzchen/osf.io,chrisseto/osf.io,icereval/osf.io,mattclark/osf.io,chennan47/osf.io,erinspace/osf.io,aaxelb/osf.io,cwisecarver/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,aaxelb/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,Nesiehr/osf.io,mluo613/osf.io,acshi/osf.io,felliott/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,laurenrevere/osf.io,felliott/osf.io,saradbowman/osf.io,pattisdr/osf.io,TomBaxter/osf.io,pattisdr/osf.io
|
python
|
## Code Before:
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73
parents = models.ManyToManyField('self', symmetrical=False, related_name='children')
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
@property
def child_count(self):
"""For v1 compat."""
return self.children.count()
def get_absolute_url(self):
return self.absolute_api_v2_url
## Instruction:
Add Subject.hierarchy to djangosf model
## Code After:
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73
parents = models.ManyToManyField('self', symmetrical=False, related_name='children')
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
@property
def child_count(self):
"""For v1 compat."""
return self.children.count()
def get_absolute_url(self):
return self.absolute_api_v2_url
@property
def hierarchy(self):
if self.parents.exists():
return self.parents.first().hierarchy + [self._id]
return [self._id]
|
...
def get_absolute_url(self):
return self.absolute_api_v2_url
@property
def hierarchy(self):
if self.parents.exists():
return self.parents.first().hierarchy + [self._id]
return [self._id]
...
|
a9711705a8c122bf7e7f1edbf9b640c3be5f8510
|
integration-test/552-water-boundary-sort-key.py
|
integration-test/552-water-boundary-sort-key.py
|
assert_has_feature(
19, 83900, 202617, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
|
assert_has_feature(
16, 10487, 25327, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
|
Update water boundary sort key test zooms
|
Update water boundary sort key test zooms
|
Python
|
mit
|
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
|
python
|
## Code Before:
assert_has_feature(
19, 83900, 202617, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
## Instruction:
Update water boundary sort key test zooms
## Code After:
assert_has_feature(
16, 10487, 25327, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
|
...
assert_has_feature(
16, 10487, 25327, "water",
{"kind": "ocean", "boundary": True, "sort_rank": 205})
...
|
2a322d26d4ed299d21a1b931e03311ff02a23e0f
|
app/status/views/healthcheck.py
|
app/status/views/healthcheck.py
|
from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client, version
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(status="ok", api=api_status, git_commit=version.__git_commit__, build_time=version.__time__), 200
|
from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(
status="ok",
api=api_status), 200
|
Remove git commit/version from status endpoint
|
Remove git commit/version from status endpoint
This is temporary for the purpose of getting running in
Docker with minimal build steps.
|
Python
|
mit
|
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
|
python
|
## Code Before:
from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client, version
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(status="ok", api=api_status, git_commit=version.__git_commit__, build_time=version.__time__), 200
## Instruction:
Remove git commit/version from status endpoint
This is temporary for the purpose of getting running in
Docker with minimal build steps.
## Code After:
from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(
status="ok",
api=api_status), 200
|
...
from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client
from app.status import status
...
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(
status="ok",
api=api_status), 200
...
|
d4a07988c8ba6b214e8d93c3a4048357484ba771
|
test/Analysis/stack-addr-ps.c
|
test/Analysis/stack-addr-ps.c
|
// RUN: clang -checker-simple -verify %s
int* f1() {
int x = 0;
return &x; // expected-warning{{Address of stack memory associated with local variable 'x' returned.}} expected-warning{{address of stack memory associated with local variable 'x' returned}}
}
int* f2(int y) {
return &y; // expected-warning{{Address of stack memory associated with local variable 'y' returned.}} expected-warning{{address of stack memory associated with local variable 'y' returned}}
}
int* f3(int x, int *y) {
int w = 0;
if (x)
y = &w;
return y; // expected-warning{{Address of stack memory associated with local variable 'w' returned.}}
}
unsigned short* compound_literal() {
return &(unsigned short){((unsigned short)0x22EF)}; // expected-warning{{Address of stack memory}} expected-warning{{braces around scalar initializer}}
}
|
// RUN: clang -checker-simple -verify %s
int* f1() {
int x = 0;
return &x; // expected-warning{{Address of stack memory associated with local variable 'x' returned.}} expected-warning{{address of stack memory associated with local variable 'x' returned}}
}
int* f2(int y) {
return &y; // expected-warning{{Address of stack memory associated with local variable 'y' returned.}} expected-warning{{address of stack memory associated with local variable 'y' returned}}
}
int* f3(int x, int *y) {
int w = 0;
if (x)
y = &w;
return y; // expected-warning{{Address of stack memory associated with local variable 'w' returned.}}
}
void* compound_literal(int x) {
if (x)
return &(unsigned short){((unsigned short)0x22EF)}; // expected-warning{{Address of stack memory}} expected-warning{{braces around scalar initializer}}
struct s { int z; double y; int w; };
return &((struct s){ 2, 0.4, 5 * 8 });
}
|
Improve compound literal test case.
|
Improve compound literal test case.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@58447 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang
|
c
|
## Code Before:
// RUN: clang -checker-simple -verify %s
int* f1() {
int x = 0;
return &x; // expected-warning{{Address of stack memory associated with local variable 'x' returned.}} expected-warning{{address of stack memory associated with local variable 'x' returned}}
}
int* f2(int y) {
return &y; // expected-warning{{Address of stack memory associated with local variable 'y' returned.}} expected-warning{{address of stack memory associated with local variable 'y' returned}}
}
int* f3(int x, int *y) {
int w = 0;
if (x)
y = &w;
return y; // expected-warning{{Address of stack memory associated with local variable 'w' returned.}}
}
unsigned short* compound_literal() {
return &(unsigned short){((unsigned short)0x22EF)}; // expected-warning{{Address of stack memory}} expected-warning{{braces around scalar initializer}}
}
## Instruction:
Improve compound literal test case.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@58447 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: clang -checker-simple -verify %s
int* f1() {
int x = 0;
return &x; // expected-warning{{Address of stack memory associated with local variable 'x' returned.}} expected-warning{{address of stack memory associated with local variable 'x' returned}}
}
int* f2(int y) {
return &y; // expected-warning{{Address of stack memory associated with local variable 'y' returned.}} expected-warning{{address of stack memory associated with local variable 'y' returned}}
}
int* f3(int x, int *y) {
int w = 0;
if (x)
y = &w;
return y; // expected-warning{{Address of stack memory associated with local variable 'w' returned.}}
}
void* compound_literal(int x) {
if (x)
return &(unsigned short){((unsigned short)0x22EF)}; // expected-warning{{Address of stack memory}} expected-warning{{braces around scalar initializer}}
struct s { int z; double y; int w; };
return &((struct s){ 2, 0.4, 5 * 8 });
}
|
...
return y; // expected-warning{{Address of stack memory associated with local variable 'w' returned.}}
}
void* compound_literal(int x) {
if (x)
return &(unsigned short){((unsigned short)0x22EF)}; // expected-warning{{Address of stack memory}} expected-warning{{braces around scalar initializer}}
struct s { int z; double y; int w; };
return &((struct s){ 2, 0.4, 5 * 8 });
}
...
|
2cf8d03324af2fadf905da811cfab4a29a6bc93a
|
pony_barn/settings/django_settings.py
|
pony_barn/settings/django_settings.py
|
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db'
}
}
|
import os
pid = os.getpid()
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db_%s' % pid,
}
}
|
Append PID to Django database to avoid conflicts.
|
Append PID to Django database to avoid conflicts.
|
Python
|
mit
|
ericholscher/pony_barn,ericholscher/pony_barn
|
python
|
## Code Before:
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db'
}
}
## Instruction:
Append PID to Django database to avoid conflicts.
## Code After:
import os
pid = os.getpid()
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db_%s' % pid,
}
}
|
...
import os
pid = os.getpid()
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
...
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db_%s' % pid,
}
}
...
|
809c60bbcec764ce8068515dac7d853d1d2771a6
|
pgf+/include/gf/IOException.h
|
pgf+/include/gf/IOException.h
|
//
// IOException.h
// pgf+
//
// Created by Emil Djupfeldt on 2012-06-22.
// Copyright (c) 2012 Chalmers University of Technology. All rights reserved.
//
#ifndef pgf__IOException_h
#define pgf__IOException_h
#include <gf/Exception.h>
namespace gf {
class IOException : public Exception {
private:
public:
IOException();
IOException(const std::string& message);
virtual ~IOException();
};
}
#endif
|
//
// IOException.h
// pgf+
//
// Created by Emil Djupfeldt on 2012-06-22.
// Copyright (c) 2012 Chalmers University of Technology. All rights reserved.
//
#ifndef pgf__IOException_h
#define pgf__IOException_h
#include <gf/Exception.h>
namespace gf {
class IOException : public Exception {
private:
public:
IOException();
IOException(const std::string& message);
IOException(int err);
virtual ~IOException();
};
}
#endif
|
Add a constructor taking an c error number.
|
Add a constructor taking an c error number.
|
C
|
bsd-2-clause
|
egladil/mscthesis,egladil/mscthesis,egladil/mscthesis
|
c
|
## Code Before:
//
// IOException.h
// pgf+
//
// Created by Emil Djupfeldt on 2012-06-22.
// Copyright (c) 2012 Chalmers University of Technology. All rights reserved.
//
#ifndef pgf__IOException_h
#define pgf__IOException_h
#include <gf/Exception.h>
namespace gf {
class IOException : public Exception {
private:
public:
IOException();
IOException(const std::string& message);
virtual ~IOException();
};
}
#endif
## Instruction:
Add a constructor taking an c error number.
## Code After:
//
// IOException.h
// pgf+
//
// Created by Emil Djupfeldt on 2012-06-22.
// Copyright (c) 2012 Chalmers University of Technology. All rights reserved.
//
#ifndef pgf__IOException_h
#define pgf__IOException_h
#include <gf/Exception.h>
namespace gf {
class IOException : public Exception {
private:
public:
IOException();
IOException(const std::string& message);
IOException(int err);
virtual ~IOException();
};
}
#endif
|
...
public:
IOException();
IOException(const std::string& message);
IOException(int err);
virtual ~IOException();
};
...
|
fdae0200e90f6ca93fda8f992002b03629f75d15
|
net/server/http_server_response_info.h
|
net/server/http_server_response_info.h
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#define NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#include <string>
#include <utility>
#include <vector>
#include "net/http/http_status_code.h"
namespace net {
class HttpServerResponseInfo {
public:
// Creates a 200 OK HttpServerResponseInfo.
HttpServerResponseInfo();
explicit HttpServerResponseInfo(HttpStatusCode status_code);
~HttpServerResponseInfo();
static HttpServerResponseInfo CreateFor404();
static HttpServerResponseInfo CreateFor500(const std::string& body);
void AddHeader(const std::string& name, const std::string& value);
// This also adds an appropriate Content-Length header.
void SetBody(const std::string& body, const std::string& content_type);
// Sets content-length and content-type. Body should be sent separately.
void SetContentHeaders(size_t content_length,
const std::string& content_type);
std::string Serialize() const;
HttpStatusCode status_code() const;
const std::string& body() const;
private:
typedef std::vector<std::pair<std::string, std::string> > Headers;
HttpStatusCode status_code_;
Headers headers_;
std::string body_;
};
} // namespace net
#endif // NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#define NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#include <string>
#include <utility>
#include "base/strings/string_split.h"
#include "net/http/http_status_code.h"
namespace net {
class HttpServerResponseInfo {
public:
// Creates a 200 OK HttpServerResponseInfo.
HttpServerResponseInfo();
explicit HttpServerResponseInfo(HttpStatusCode status_code);
~HttpServerResponseInfo();
static HttpServerResponseInfo CreateFor404();
static HttpServerResponseInfo CreateFor500(const std::string& body);
void AddHeader(const std::string& name, const std::string& value);
// This also adds an appropriate Content-Length header.
void SetBody(const std::string& body, const std::string& content_type);
// Sets content-length and content-type. Body should be sent separately.
void SetContentHeaders(size_t content_length,
const std::string& content_type);
std::string Serialize() const;
HttpStatusCode status_code() const;
const std::string& body() const;
private:
using Headers = base::StringPairs;
HttpStatusCode status_code_;
Headers headers_;
std::string body_;
};
} // namespace net
#endif // NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
|
Use of base::StringPairs appropriately in server
|
Use of base::StringPairs appropriately in server
Bescause base/strings/string_split.h defines:
typedef std::vector<std::pair<std::string, std::string> > StringPairs;
BUG=412250
Review URL: https://codereview.chromium.org/1093823005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#327241}
|
C
|
bsd-3-clause
|
Chilledheart/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk
|
c
|
## Code Before:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#define NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#include <string>
#include <utility>
#include <vector>
#include "net/http/http_status_code.h"
namespace net {
class HttpServerResponseInfo {
public:
// Creates a 200 OK HttpServerResponseInfo.
HttpServerResponseInfo();
explicit HttpServerResponseInfo(HttpStatusCode status_code);
~HttpServerResponseInfo();
static HttpServerResponseInfo CreateFor404();
static HttpServerResponseInfo CreateFor500(const std::string& body);
void AddHeader(const std::string& name, const std::string& value);
// This also adds an appropriate Content-Length header.
void SetBody(const std::string& body, const std::string& content_type);
// Sets content-length and content-type. Body should be sent separately.
void SetContentHeaders(size_t content_length,
const std::string& content_type);
std::string Serialize() const;
HttpStatusCode status_code() const;
const std::string& body() const;
private:
typedef std::vector<std::pair<std::string, std::string> > Headers;
HttpStatusCode status_code_;
Headers headers_;
std::string body_;
};
} // namespace net
#endif // NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
## Instruction:
Use of base::StringPairs appropriately in server
Bescause base/strings/string_split.h defines:
typedef std::vector<std::pair<std::string, std::string> > StringPairs;
BUG=412250
Review URL: https://codereview.chromium.org/1093823005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#327241}
## Code After:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#define NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
#include <string>
#include <utility>
#include "base/strings/string_split.h"
#include "net/http/http_status_code.h"
namespace net {
class HttpServerResponseInfo {
public:
// Creates a 200 OK HttpServerResponseInfo.
HttpServerResponseInfo();
explicit HttpServerResponseInfo(HttpStatusCode status_code);
~HttpServerResponseInfo();
static HttpServerResponseInfo CreateFor404();
static HttpServerResponseInfo CreateFor500(const std::string& body);
void AddHeader(const std::string& name, const std::string& value);
// This also adds an appropriate Content-Length header.
void SetBody(const std::string& body, const std::string& content_type);
// Sets content-length and content-type. Body should be sent separately.
void SetContentHeaders(size_t content_length,
const std::string& content_type);
std::string Serialize() const;
HttpStatusCode status_code() const;
const std::string& body() const;
private:
using Headers = base::StringPairs;
HttpStatusCode status_code_;
Headers headers_;
std::string body_;
};
} // namespace net
#endif // NET_SERVER_HTTP_SERVER_RESPONSE_INFO_H_
|
...
#include <string>
#include <utility>
#include "base/strings/string_split.h"
#include "net/http/http_status_code.h"
namespace net {
...
const std::string& body() const;
private:
using Headers = base::StringPairs;
HttpStatusCode status_code_;
Headers headers_;
...
|
8bcc4fe29468868190dcfcbea5438dc0aa638387
|
sweetercat/test_utils.py
|
sweetercat/test_utils.py
|
from __future__ import division
from utils import absolute_magnitude, plDensity, hz
def test_absolute_magnitude():
m = 10
assert isinstance(absolute_magnitude(1, 1), float)
assert absolute_magnitude(1, m) > m
assert absolute_magnitude(1, m) == 15
assert absolute_magnitude(0.1, m) == m
assert absolute_magnitude(0.01, m) < m
assert absolute_magnitude(1/10, m) == m
def test_plDensity():
m, r = 1, 1
assert isinstance(plDensity(m, r), float)
assert round(plDensity(m, r), 2) == 1.33
assert plDensity(0, r) == 0
def test_hz():
teff = 5777
lum = 1
for model in range(1, 6):
assert isinstance(hz(teff, lum, model), float)
results = [0.75, 0.98, 0.99, 1.71, 1.77]
for model, result in enumerate(results, start=1):
assert round(hz(teff, lum, model), 2) == result
|
from __future__ import division
import pytest
import pandas as pd
from utils import absolute_magnitude, plDensity, hz, readSC
def test_absolute_magnitude():
m = 10
assert isinstance(absolute_magnitude(1, 1), float)
assert absolute_magnitude(1, m) > m
assert absolute_magnitude(1, m) == 15
assert absolute_magnitude(0.1, m) == m
assert absolute_magnitude(0.01, m) < m
assert absolute_magnitude(1/10, m) == m
with pytest.raises(ZeroDivisionError):
absolute_magnitude(0, m)
def test_plDensity():
m, r = 1, 1
assert isinstance(plDensity(m, r), float)
assert round(plDensity(m, r), 2) == 1.33
assert plDensity(0, r) == 0
def test_hz():
teff = 5777
lum = 1
for model in range(1, 6):
assert isinstance(hz(teff, lum, model), float)
results = [0.75, 0.98, 0.99, 1.71, 1.77]
for model, result in enumerate(results, start=1):
assert round(hz(teff, lum, model), 2) == result
assert hz(teff, lum, 2) < hz(teff, lum, 4) # hz1 < hz2
def test_readSC():
df, plot_names = readSC()
assert isinstance(df, pd.DataFrame) #
assert isinstance(plot_names, list)
for name in plot_names:
assert isinstance(name, str)
|
Add couple more utils tests.
|
Add couple more utils tests.
|
Python
|
mit
|
DanielAndreasen/SWEETer-Cat,DanielAndreasen/SWEETer-Cat
|
python
|
## Code Before:
from __future__ import division
from utils import absolute_magnitude, plDensity, hz
def test_absolute_magnitude():
m = 10
assert isinstance(absolute_magnitude(1, 1), float)
assert absolute_magnitude(1, m) > m
assert absolute_magnitude(1, m) == 15
assert absolute_magnitude(0.1, m) == m
assert absolute_magnitude(0.01, m) < m
assert absolute_magnitude(1/10, m) == m
def test_plDensity():
m, r = 1, 1
assert isinstance(plDensity(m, r), float)
assert round(plDensity(m, r), 2) == 1.33
assert plDensity(0, r) == 0
def test_hz():
teff = 5777
lum = 1
for model in range(1, 6):
assert isinstance(hz(teff, lum, model), float)
results = [0.75, 0.98, 0.99, 1.71, 1.77]
for model, result in enumerate(results, start=1):
assert round(hz(teff, lum, model), 2) == result
## Instruction:
Add couple more utils tests.
## Code After:
from __future__ import division
import pytest
import pandas as pd
from utils import absolute_magnitude, plDensity, hz, readSC
def test_absolute_magnitude():
m = 10
assert isinstance(absolute_magnitude(1, 1), float)
assert absolute_magnitude(1, m) > m
assert absolute_magnitude(1, m) == 15
assert absolute_magnitude(0.1, m) == m
assert absolute_magnitude(0.01, m) < m
assert absolute_magnitude(1/10, m) == m
with pytest.raises(ZeroDivisionError):
absolute_magnitude(0, m)
def test_plDensity():
m, r = 1, 1
assert isinstance(plDensity(m, r), float)
assert round(plDensity(m, r), 2) == 1.33
assert plDensity(0, r) == 0
def test_hz():
teff = 5777
lum = 1
for model in range(1, 6):
assert isinstance(hz(teff, lum, model), float)
results = [0.75, 0.98, 0.99, 1.71, 1.77]
for model, result in enumerate(results, start=1):
assert round(hz(teff, lum, model), 2) == result
assert hz(teff, lum, 2) < hz(teff, lum, 4) # hz1 < hz2
def test_readSC():
df, plot_names = readSC()
assert isinstance(df, pd.DataFrame) #
assert isinstance(plot_names, list)
for name in plot_names:
assert isinstance(name, str)
|
# ... existing code ...
from __future__ import division
import pytest
import pandas as pd
from utils import absolute_magnitude, plDensity, hz, readSC
def test_absolute_magnitude():
# ... modified code ...
assert absolute_magnitude(0.1, m) == m
assert absolute_magnitude(0.01, m) < m
assert absolute_magnitude(1/10, m) == m
with pytest.raises(ZeroDivisionError):
absolute_magnitude(0, m)
def test_plDensity():
...
results = [0.75, 0.98, 0.99, 1.71, 1.77]
for model, result in enumerate(results, start=1):
assert round(hz(teff, lum, model), 2) == result
assert hz(teff, lum, 2) < hz(teff, lum, 4) # hz1 < hz2
def test_readSC():
df, plot_names = readSC()
assert isinstance(df, pd.DataFrame) #
assert isinstance(plot_names, list)
for name in plot_names:
assert isinstance(name, str)
# ... rest of the code ...
|
d8b477083866a105947281ca34cb6e215417f44d
|
packs/salt/actions/lib/utils.py
|
packs/salt/actions/lib/utils.py
|
import yaml
action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
def generate_action(module_type, action):
manifest = action_meta
manifest['name'] = "{0}_{1}".format(module_type, action)
manifest['parameters']['action']['default'] = action
fh = open('{0}_{1}.yaml'.format(module_type, action), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
def sanitize_payload(keys_to_sanitize, payload):
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
|
import yaml
from .meta import actions
runner_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
local_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"args": {
"type": "array",
"required": False
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Execution modules through Salt API",
"enabled": True,
"entry_point": "local.py"}
def generate_actions():
def create_file(mt, m, a):
manifest = local_action_meta
manifest['name'] = "{0}_{1}.{2}".format(mt, m, a)
manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a)
fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
for key in actions:
map(lambda l: create_file('local', key, l), actions[key])
def sanitize_payload(keys_to_sanitize, payload):
'''
Removes sensitive data from payloads before
publishing to the logs
'''
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
|
Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging.
|
Make distinction between local and runner action payload templates.
Added small description for sanitizing the NetAPI payload for logging.
|
Python
|
apache-2.0
|
pidah/st2contrib,StackStorm/st2contrib,psychopenguin/st2contrib,lmEshoo/st2contrib,armab/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,psychopenguin/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,pidah/st2contrib
|
python
|
## Code Before:
import yaml
action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
def generate_action(module_type, action):
manifest = action_meta
manifest['name'] = "{0}_{1}".format(module_type, action)
manifest['parameters']['action']['default'] = action
fh = open('{0}_{1}.yaml'.format(module_type, action), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
def sanitize_payload(keys_to_sanitize, payload):
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
## Instruction:
Make distinction between local and runner action payload templates.
Added small description for sanitizing the NetAPI payload for logging.
## Code After:
import yaml
from .meta import actions
runner_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
local_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"args": {
"type": "array",
"required": False
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Execution modules through Salt API",
"enabled": True,
"entry_point": "local.py"}
def generate_actions():
def create_file(mt, m, a):
manifest = local_action_meta
manifest['name'] = "{0}_{1}.{2}".format(mt, m, a)
manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a)
fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
for key in actions:
map(lambda l: create_file('local', key, l), actions[key])
def sanitize_payload(keys_to_sanitize, payload):
'''
Removes sensitive data from payloads before
publishing to the logs
'''
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
|
# ... existing code ...
import yaml
from .meta import actions
runner_action_meta = {
"name": "",
"parameters": {
"action": {
# ... modified code ...
"enabled": True,
"entry_point": "runner.py"}
local_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"args": {
"type": "array",
"required": False
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Execution modules through Salt API",
"enabled": True,
"entry_point": "local.py"}
def generate_actions():
def create_file(mt, m, a):
manifest = local_action_meta
manifest['name'] = "{0}_{1}.{2}".format(mt, m, a)
manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a)
fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
for key in actions:
map(lambda l: create_file('local', key, l), actions[key])
def sanitize_payload(keys_to_sanitize, payload):
'''
Removes sensitive data from payloads before
publishing to the logs
'''
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
# ... rest of the code ...
|
a8e42b122916696dbe63ddae3190502b296b47ec
|
label_response/__init__.py
|
label_response/__init__.py
|
import json
def check_labels(api):
with open('config.json', 'r') as fd:
config = json.load(fd)
if not config['active']:
return
labels = config['labels']
for label, comment in labels.items():
if api.payload['label']['name'].lower() == label:
api.post_comment(comment)
method = check_labels
|
import json
def check_labels(api, config):
if not config.get('active'):
return
labels = config.get('labels', [])
for label, comment in labels.items():
if api.payload['label']['name'].lower() == label:
api.post_comment(comment)
methods = [check_labels]
|
Support for multiple methods, and leave the config file to hooker
|
Support for multiple methods, and leave the config file to hooker
|
Python
|
mpl-2.0
|
servo-automation/highfive,servo-automation/highfive,servo-highfive/highfive
|
python
|
## Code Before:
import json
def check_labels(api):
with open('config.json', 'r') as fd:
config = json.load(fd)
if not config['active']:
return
labels = config['labels']
for label, comment in labels.items():
if api.payload['label']['name'].lower() == label:
api.post_comment(comment)
method = check_labels
## Instruction:
Support for multiple methods, and leave the config file to hooker
## Code After:
import json
def check_labels(api, config):
if not config.get('active'):
return
labels = config.get('labels', [])
for label, comment in labels.items():
if api.payload['label']['name'].lower() == label:
api.post_comment(comment)
methods = [check_labels]
|
...
import json
def check_labels(api, config):
if not config.get('active'):
return
labels = config.get('labels', [])
for label, comment in labels.items():
if api.payload['label']['name'].lower() == label:
api.post_comment(comment)
methods = [check_labels]
...
|
8d0b9da511d55191609ffbd88a8b11afd6ff0367
|
remedy/radremedy.py
|
remedy/radremedy.py
|
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from rad.models import db, Resource
def create_app(config, models=()):
from remedyblueprint import remedy, url_for_other_page
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(remedy)
# searching configurations
app.jinja_env.trim_blocks = True
# Register the paging helper method with Jinja2
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
db.init_app(app)
Migrate(app, db, directory=app.config['MIGRATIONS_DIR'])
manager = Manager(app)
manager.add_command('db', MigrateCommand)
# turning API off for now
# from api_manager import init_api_manager
# api_manager = init_api_manager(app, db)
# map(lambda m: api_manager.create_api(m), models)
return app, manager
if __name__ == '__main__':
app, manager = create_app('config.BaseConfig', (Resource, ))
with app.app_context():
manager.run()
|
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import current_user
from rad.models import db, Resource
def create_app(config, models=()):
app = Flask(__name__)
app.config.from_object(config)
from remedyblueprint import remedy, url_for_other_page
app.register_blueprint(remedy)
from auth.user_auth import auth, login_manager
app.register_blueprint(auth)
login_manager.init_app(app)
# searching configurations
app.jinja_env.trim_blocks = True
# Register the paging helper method with Jinja2
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous()
db.init_app(app)
Migrate(app, db, directory=app.config['MIGRATIONS_DIR'])
manager = Manager(app)
manager.add_command('db', MigrateCommand)
# turning API off for now
# from api_manager import init_api_manager
# api_manager = init_api_manager(app, db)
# map(lambda m: api_manager.create_api(m), models)
return app, manager
if __name__ == '__main__':
application, manager = create_app('config.BaseConfig', (Resource, ))
with application.app_context():
manager.run()
|
Move around imports and not shadow app
|
Move around imports and not shadow app
|
Python
|
mpl-2.0
|
radioprotector/radremedy,radioprotector/radremedy,radioprotector/radremedy,AllieDeford/radremedy,AllieDeford/radremedy,radremedy/radremedy,radremedy/radremedy,radremedy/radremedy,AllieDeford/radremedy,radioprotector/radremedy,radremedy/radremedy
|
python
|
## Code Before:
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from rad.models import db, Resource
def create_app(config, models=()):
from remedyblueprint import remedy, url_for_other_page
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(remedy)
# searching configurations
app.jinja_env.trim_blocks = True
# Register the paging helper method with Jinja2
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
db.init_app(app)
Migrate(app, db, directory=app.config['MIGRATIONS_DIR'])
manager = Manager(app)
manager.add_command('db', MigrateCommand)
# turning API off for now
# from api_manager import init_api_manager
# api_manager = init_api_manager(app, db)
# map(lambda m: api_manager.create_api(m), models)
return app, manager
if __name__ == '__main__':
app, manager = create_app('config.BaseConfig', (Resource, ))
with app.app_context():
manager.run()
## Instruction:
Move around imports and not shadow app
## Code After:
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import current_user
from rad.models import db, Resource
def create_app(config, models=()):
app = Flask(__name__)
app.config.from_object(config)
from remedyblueprint import remedy, url_for_other_page
app.register_blueprint(remedy)
from auth.user_auth import auth, login_manager
app.register_blueprint(auth)
login_manager.init_app(app)
# searching configurations
app.jinja_env.trim_blocks = True
# Register the paging helper method with Jinja2
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous()
db.init_app(app)
Migrate(app, db, directory=app.config['MIGRATIONS_DIR'])
manager = Manager(app)
manager.add_command('db', MigrateCommand)
# turning API off for now
# from api_manager import init_api_manager
# api_manager = init_api_manager(app, db)
# map(lambda m: api_manager.create_api(m), models)
return app, manager
if __name__ == '__main__':
application, manager = create_app('config.BaseConfig', (Resource, ))
with application.app_context():
manager.run()
|
// ... existing code ...
from flask import Flask, url_for, request, abort
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import current_user
from rad.models import db, Resource
def create_app(config, models=()):
app = Flask(__name__)
app.config.from_object(config)
from remedyblueprint import remedy, url_for_other_page
app.register_blueprint(remedy)
from auth.user_auth import auth, login_manager
app.register_blueprint(auth)
login_manager.init_app(app)
# searching configurations
app.jinja_env.trim_blocks = True
# Register the paging helper method with Jinja2
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous()
db.init_app(app)
// ... modified code ...
return app, manager
if __name__ == '__main__':
application, manager = create_app('config.BaseConfig', (Resource, ))
with application.app_context():
manager.run()
// ... rest of the code ...
|
0b37e71972d067bd06bfab1d7a0c0f47badefb17
|
scout/markers/models.py
|
scout/markers/models.py
|
from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'marker_colour': self.marker_colour
}
|
from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'address': self.address,
'marker_colour': self.marker_colour
}
|
Return the address from the marker.
|
Return the address from the marker.
|
Python
|
mit
|
meizon/scout,meizon/scout,meizon/scout,meizon/scout
|
python
|
## Code Before:
from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'marker_colour': self.marker_colour
}
## Instruction:
Return the address from the marker.
## Code After:
from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'address': self.address,
'marker_colour': self.marker_colour
}
|
...
'name': self.name,
'lat': self.lat,
'long': self.long,
'address': self.address,
'marker_colour': self.marker_colour
}
...
|
91bf68e26c0fdf7de4209622192f9d57be2d60f8
|
feincms/views/cbv/views.py
|
feincms/views/cbv/views.py
|
from __future__ import absolute_import, unicode_literals
from django.http import Http404
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = 'page.Page'
context_object_name = 'feincms_page'
@property
def page_model(self):
if not hasattr(self, '_page_model'):
self._page_model = get_model(*self.page_model_path.split('.'))
if self._page_model is None:
raise ImportError(
"Can't import model \"%s\"" % self.page_model_path)
return self._page_model
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
|
from __future__ import absolute_import, unicode_literals
from django.http import Http404
from django.utils.functional import cached_property
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = None
context_object_name = 'feincms_page'
@cached_property
def page_model(self):
model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL
return get_model(*model.split('.'))
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
|
Stop invoking get_model for each request
|
Stop invoking get_model for each request
|
Python
|
bsd-3-clause
|
joshuajonah/feincms,mjl/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/django-content-editor,nickburlett/feincms,feincms/feincms,michaelkuty/feincms,mjl/feincms,mjl/feincms,joshuajonah/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/django-content-editor,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,nickburlett/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/feincms2-content,feincms/feincms
|
python
|
## Code Before:
from __future__ import absolute_import, unicode_literals
from django.http import Http404
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = 'page.Page'
context_object_name = 'feincms_page'
@property
def page_model(self):
if not hasattr(self, '_page_model'):
self._page_model = get_model(*self.page_model_path.split('.'))
if self._page_model is None:
raise ImportError(
"Can't import model \"%s\"" % self.page_model_path)
return self._page_model
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
## Instruction:
Stop invoking get_model for each request
## Code After:
from __future__ import absolute_import, unicode_literals
from django.http import Http404
from django.utils.functional import cached_property
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = None
context_object_name = 'feincms_page'
@cached_property
def page_model(self):
model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL
return get_model(*model.split('.'))
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
|
# ... existing code ...
from __future__ import absolute_import, unicode_literals
from django.http import Http404
from django.utils.functional import cached_property
from feincms import settings
from feincms._internal import get_model
# ... modified code ...
class Handler(ContentView):
page_model_path = None
context_object_name = 'feincms_page'
@cached_property
def page_model(self):
model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL
return get_model(*model.split('.'))
def get_object(self):
path = None
# ... rest of the code ...
|
fea168823acd6c1c50d3d366798a4314c79e6dc9
|
src/backend/port/dynloader/osf.c
|
src/backend/port/dynloader/osf.c
|
/* Dummy file used for nothing at this point
*
* see alpha.h
* $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.2 2006/03/11 04:38:31 momjian Exp $
*/
|
/*
* $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.3 2009/04/21 21:05:25 tgl Exp $
*
* Dummy file used for nothing at this point
*
* see osf.h
*/
|
Fix obsolete cross-reference (this file isn't called alpha.c anymore)
|
Fix obsolete cross-reference (this file isn't called alpha.c anymore)
|
C
|
mpl-2.0
|
Postgres-XL/Postgres-XL,tpostgres-projects/tPostgres,greenplum-db/gpdb,edespino/gpdb,pavanvd/postgres-xl,tpostgres-projects/tPostgres,edespino/gpdb,ashwinstar/gpdb,oberstet/postgres-xl,jmcatamney/gpdb,arcivanov/postgres-xl,ovr/postgres-xl,yuanzhao/gpdb,50wu/gpdb,adam8157/gpdb,yuanzhao/gpdb,zeroae/postgres-xl,techdragon/Postgres-XL,arcivanov/postgres-xl,yazun/postgres-xl,jmcatamney/gpdb,jmcatamney/gpdb,Chibin/gpdb,ashwinstar/gpdb,greenplum-db/gpdb,snaga/postgres-xl,zeroae/postgres-xl,yazun/postgres-xl,yuanzhao/gpdb,jmcatamney/gpdb,pavanvd/postgres-xl,oberstet/postgres-xl,lisakowen/gpdb,yuanzhao/gpdb,yazun/postgres-xl,arcivanov/postgres-xl,yuanzhao/gpdb,ashwinstar/gpdb,edespino/gpdb,tpostgres-projects/tPostgres,lisakowen/gpdb,ovr/postgres-xl,ashwinstar/gpdb,adam8157/gpdb,50wu/gpdb,50wu/gpdb,Postgres-XL/Postgres-XL,Chibin/gpdb,lisakowen/gpdb,ashwinstar/gpdb,snaga/postgres-xl,snaga/postgres-xl,techdragon/Postgres-XL,postmind-net/postgres-xl,yazun/postgres-xl,xinzweb/gpdb,edespino/gpdb,techdragon/Postgres-XL,pavanvd/postgres-xl,postmind-net/postgres-xl,yuanzhao/gpdb,50wu/gpdb,edespino/gpdb,greenplum-db/gpdb,jmcatamney/gpdb,adam8157/gpdb,jmcatamney/gpdb,Chibin/gpdb,oberstet/postgres-xl,postmind-net/postgres-xl,ashwinstar/gpdb,greenplum-db/gpdb,ashwinstar/gpdb,zeroae/postgres-xl,greenplum-db/gpdb,Chibin/gpdb,yuanzhao/gpdb,pavanvd/postgres-xl,lisakowen/gpdb,oberstet/postgres-xl,xinzweb/gpdb,oberstet/postgres-xl,edespino/gpdb,yuanzhao/gpdb,edespino/gpdb,Chibin/gpdb,pavanvd/postgres-xl,postmind-net/postgres-xl,tpostgres-projects/tPostgres,ovr/postgres-xl,Chibin/gpdb,adam8157/gpdb,jmcatamney/gpdb,lisakowen/gpdb,xinzweb/gpdb,edespino/gpdb,techdragon/Postgres-XL,lisakowen/gpdb,xinzweb/gpdb,50wu/gpdb,lisakowen/gpdb,arcivanov/postgres-xl,greenplum-db/gpdb,xinzweb/gpdb,yazun/postgres-xl,Chibin/gpdb,snaga/postgres-xl,Postgres-XL/Postgres-XL,greenplum-db/gpdb,ovr/postgres-xl,yuanzhao/gpdb,adam8157/gpdb,adam8157/gpdb,yuanzhao/gpdb,postmind-net/postgres-xl,kmjungersen/PostgresXL,techdragon/Postgres-XL,adam8157/gpdb,ashwinstar/gpdb,xinzweb/gpdb,edespino/gpdb,Chibin/gpdb,Chibin/gpdb,arcivanov/postgres-xl,Postgres-XL/Postgres-XL,Postgres-XL/Postgres-XL,arcivanov/postgres-xl,tpostgres-projects/tPostgres,jmcatamney/gpdb,snaga/postgres-xl,50wu/gpdb,zeroae/postgres-xl,ovr/postgres-xl,edespino/gpdb,kmjungersen/PostgresXL,Chibin/gpdb,kmjungersen/PostgresXL,greenplum-db/gpdb,50wu/gpdb,kmjungersen/PostgresXL,50wu/gpdb,zeroae/postgres-xl,xinzweb/gpdb,xinzweb/gpdb,lisakowen/gpdb,adam8157/gpdb,kmjungersen/PostgresXL
|
c
|
## Code Before:
/* Dummy file used for nothing at this point
*
* see alpha.h
* $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.2 2006/03/11 04:38:31 momjian Exp $
*/
## Instruction:
Fix obsolete cross-reference (this file isn't called alpha.c anymore)
## Code After:
/*
* $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.3 2009/04/21 21:05:25 tgl Exp $
*
* Dummy file used for nothing at this point
*
* see osf.h
*/
|
...
/*
* $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.3 2009/04/21 21:05:25 tgl Exp $
*
* Dummy file used for nothing at this point
*
* see osf.h
*/
...
|
abba08a6a535c202af9c8e2a5e79680b8789b34e
|
CECProject/src/tests/AllTests.java
|
CECProject/src/tests/AllTests.java
|
package tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
EmailBuilderTests.class,
EmailTests.class })
public class AllTests {
}
|
package tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
EmailBuilderTests.class,
EmailTests.class,
EmailSortingTests.class })
public class AllTests {
}
|
Add the sorting test class to the test suite.
|
Add the sorting test class to the test suite.
|
Java
|
mit
|
amishwins/project-cec-2013,amishwins/project-cec-2013
|
java
|
## Code Before:
package tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
EmailBuilderTests.class,
EmailTests.class })
public class AllTests {
}
## Instruction:
Add the sorting test class to the test suite.
## Code After:
package tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
EmailBuilderTests.class,
EmailTests.class,
EmailSortingTests.class })
public class AllTests {
}
|
...
@RunWith(Suite.class)
@SuiteClasses({
EmailBuilderTests.class,
EmailTests.class,
EmailSortingTests.class })
public class AllTests {
}
...
|
2cb73ac018287ab77b380c31166ec4fc6fd99f5e
|
performanceplatform/collector/gcloud/__init__.py
|
performanceplatform/collector/gcloud/__init__.py
|
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
push_aggregates(data_set)
|
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
|
Make the G-Cloud collector empty the data set
|
Make the G-Cloud collector empty the data set
https://www.pivotaltracker.com/story/show/72073020
[Delivers #72073020]
|
Python
|
mit
|
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector
|
python
|
## Code Before:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
push_aggregates(data_set)
## Instruction:
Make the G-Cloud collector empty the data set
https://www.pivotaltracker.com/story/show/72073020
[Delivers #72073020]
## Code After:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
|
...
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
...
|
f88c2135ddc197283bbfb8b481774deb613571cf
|
python/raindrops/raindrops.py
|
python/raindrops/raindrops.py
|
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
|
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
|
Handle 5 as a factor
|
Handle 5 as a factor
|
Python
|
mit
|
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
|
python
|
## Code Before:
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
## Instruction:
Handle 5 as a factor
## Code After:
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
|
# ... existing code ...
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
# ... rest of the code ...
|
bd1a244aa3d9126a12365611372e6449e47e5693
|
pelicanconf.py
|
pelicanconf.py
|
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
|
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
|
Add links to Android/iOS apps
|
Add links to Android/iOS apps
|
Python
|
mit
|
paulgreg/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source
|
python
|
## Code Before:
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
## Instruction:
Add links to Android/iOS apps
## Code After:
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
|
// ... existing code ...
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
// ... rest of the code ...
|
8e980445723f3f185eb88022adbd75f1a01aaef4
|
fabfile/ubuntu.py
|
fabfile/ubuntu.py
|
from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('apt-get -y upgrade')
|
from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.operations import reboot
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o \
Dpkg::Options::="--force-confold" upgrade')
reboot()
|
Add apt-get upgrade without grub-install
|
Add apt-get upgrade without grub-install
|
Python
|
mit
|
maruina/kanedias,maruina/kanedias,maruina/kanedias,maruina/kanedias
|
python
|
## Code Before:
from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('apt-get -y upgrade')
## Instruction:
Add apt-get upgrade without grub-install
## Code After:
from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.operations import reboot
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
@task
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o \
Dpkg::Options::="--force-confold" upgrade')
reboot()
|
# ... existing code ...
from StringIO import StringIO
from fabric.api import local, task, run, env, sudo, get
from fabric.operations import reboot
from fabric.tasks import execute
from fabric.context_managers import lcd, hide
# ... modified code ...
def apt_update():
with hide('stdout'):
sudo('apt-get update')
sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o \
Dpkg::Options::="--force-confold" upgrade')
reboot()
# ... rest of the code ...
|
72ee5d6949f25158b6cbd1deead45ee1e939be5b
|
sympy/series/__init__.py
|
sympy/series/__init__.py
|
from order import Order
from limits import limit, Limit
from gruntz import gruntz
from series import series
O = Order
__all__ = [gruntz, limit, series, O, Order, Limit]
|
from order import Order
from limits import limit, Limit
from gruntz import gruntz
from series import series
O = Order
__all__ = ['gruntz', 'limit', 'series', 'O', 'Order', 'Limit']
|
Fix __all__ usage for sympy/series
|
Fix __all__ usage for sympy/series
|
Python
|
bsd-3-clause
|
hargup/sympy,Arafatk/sympy,chaffra/sympy,kaushik94/sympy,atreyv/sympy,jbbskinny/sympy,aktech/sympy,AunShiLord/sympy,AkademieOlympia/sympy,beni55/sympy,jerli/sympy,vipulroxx/sympy,Titan-C/sympy,yukoba/sympy,minrk/sympy,Shaswat27/sympy,abloomston/sympy,yashsharan/sympy,shipci/sympy,drufat/sympy,jerli/sympy,toolforger/sympy,Gadal/sympy,cswiercz/sympy,cswiercz/sympy,atsao72/sympy,MridulS/sympy,emon10005/sympy,shikil/sympy,aktech/sympy,iamutkarshtiwari/sympy,moble/sympy,Arafatk/sympy,VaibhavAgarwalVA/sympy,wanglongqi/sympy,kaichogami/sympy,Gadal/sympy,postvakje/sympy,ahhda/sympy,yukoba/sympy,sahmed95/sympy,hrashk/sympy,oliverlee/sympy,garvitr/sympy,farhaanbukhsh/sympy,jaimahajan1997/sympy,wanglongqi/sympy,kaushik94/sympy,shikil/sympy,grevutiu-gabriel/sympy,maniteja123/sympy,VaibhavAgarwalVA/sympy,drufat/sympy,abloomston/sympy,atsao72/sympy,Davidjohnwilson/sympy,jaimahajan1997/sympy,sahilshekhawat/sympy,moble/sympy,Davidjohnwilson/sympy,diofant/diofant,Sumith1896/sympy,meghana1995/sympy,AunShiLord/sympy,Vishluck/sympy,kmacinnis/sympy,toolforger/sympy,Davidjohnwilson/sympy,Curious72/sympy,grevutiu-gabriel/sympy,madan96/sympy,kumarkrishna/sympy,chaffra/sympy,souravsingh/sympy,MechCoder/sympy,jamesblunt/sympy,ga7g08/sympy,postvakje/sympy,jbbskinny/sympy,mcdaniel67/sympy,farhaanbukhsh/sympy,rahuldan/sympy,sunny94/temp,Gadal/sympy,hargup/sympy,garvitr/sympy,atreyv/sympy,lidavidm/sympy,abhiii5459/sympy,MechCoder/sympy,saurabhjn76/sympy,shipci/sympy,mcdaniel67/sympy,hrashk/sympy,yashsharan/sympy,bukzor/sympy,Shaswat27/sympy,sahmed95/sympy,Sumith1896/sympy,rahuldan/sympy,shipci/sympy,yukoba/sympy,cccfran/sympy,liangjiaxing/sympy,kaichogami/sympy,skidzo/sympy,bukzor/sympy,kaushik94/sympy,jerli/sympy,Designist/sympy,kmacinnis/sympy,asm666/sympy,Arafatk/sympy,yashsharan/sympy,sahilshekhawat/sympy,pandeyadarsh/sympy,Mitchkoens/sympy,jamesblunt/sympy,saurabhjn76/sympy,hargup/sympy,maniteja123/sympy,debugger22/sympy,saurabhjn76/sympy,wyom/sympy,kmacinnis/sympy,MridulS/sympy,cswiercz/sympy,debugger22/sympy,cccfran/sympy,cccfran/sympy,iamutkarshtiwari/sympy,oliverlee/sympy,maniteja123/sympy,MechCoder/sympy,skirpichev/omg,lindsayad/sympy,VaibhavAgarwalVA/sympy,rahuldan/sympy,madan96/sympy,iamutkarshtiwari/sympy,asm666/sympy,asm666/sympy,pernici/sympy,Designist/sympy,Mitchkoens/sympy,grevutiu-gabriel/sympy,AkademieOlympia/sympy,garvitr/sympy,sampadsaha5/sympy,lindsayad/sympy,atsao72/sympy,drufat/sympy,ga7g08/sympy,Vishluck/sympy,hrashk/sympy,bukzor/sympy,pandeyadarsh/sympy,flacjacket/sympy,sahmed95/sympy,skidzo/sympy,beni55/sympy,emon10005/sympy,emon10005/sympy,pbrady/sympy,jamesblunt/sympy,Designist/sympy,chaffra/sympy,kumarkrishna/sympy,madan96/sympy,moble/sympy,beni55/sympy,Sumith1896/sympy,dqnykamp/sympy,mafiya69/sympy,pbrady/sympy,ChristinaZografou/sympy,ChristinaZografou/sympy,kevalds51/sympy,liangjiaxing/sympy,Titan-C/sympy,amitjamadagni/sympy,minrk/sympy,lidavidm/sympy,dqnykamp/sympy,mafiya69/sympy,sampadsaha5/sympy,liangjiaxing/sympy,ahhda/sympy,sampadsaha5/sympy,Curious72/sympy,aktech/sympy,lindsayad/sympy,wyom/sympy,vipulroxx/sympy,atreyv/sympy,jbbskinny/sympy,mafiya69/sympy,sunny94/temp,srjoglekar246/sympy,pbrady/sympy,shikil/sympy,wyom/sympy,debugger22/sympy,Titan-C/sympy,toolforger/sympy,mcdaniel67/sympy,kevalds51/sympy,MridulS/sympy,Vishluck/sympy,sahilshekhawat/sympy,lidavidm/sympy,sunny94/temp,Shaswat27/sympy,oliverlee/sympy,abhiii5459/sympy,ChristinaZografou/sympy,abloomston/sympy,AunShiLord/sympy,dqnykamp/sympy,jaimahajan1997/sympy,meghana1995/sympy,postvakje/sympy,souravsingh/sympy,souravsingh/sympy,AkademieOlympia/sympy,skidzo/sympy,wanglongqi/sympy,pandeyadarsh/sympy,kevalds51/sympy,farhaanbukhsh/sympy,kaichogami/sympy,meghana1995/sympy,amitjamadagni/sympy,ahhda/sympy,Curious72/sympy,abhiii5459/sympy,Mitchkoens/sympy,kumarkrishna/sympy,vipulroxx/sympy,ga7g08/sympy
|
python
|
## Code Before:
from order import Order
from limits import limit, Limit
from gruntz import gruntz
from series import series
O = Order
__all__ = [gruntz, limit, series, O, Order, Limit]
## Instruction:
Fix __all__ usage for sympy/series
## Code After:
from order import Order
from limits import limit, Limit
from gruntz import gruntz
from series import series
O = Order
__all__ = ['gruntz', 'limit', 'series', 'O', 'Order', 'Limit']
|
...
O = Order
__all__ = ['gruntz', 'limit', 'series', 'O', 'Order', 'Limit']
...
|
8354cfd953bb09723abcff7fefe620fc4aa6b855
|
tests/test_git_helpers.py
|
tests/test_git_helpers.py
|
from unittest import TestCase, mock
from invoke.runner import Result
from semantic_release.git_helpers import commit_new_version, get_commit_log
class GetCommitLogTest(TestCase):
def test_first_commit_is_not_initial_commit(self):
self.assertNotEqual(next(get_commit_log()), 'Initial commit')
class CommitNewVersionTests(TestCase):
@mock.patch('semantic_release.git_helpers.run',
return_value=Result(stdout='', stderr='', pty='', exited=0))
def test_add_and_commit(self, mock_run):
commit_new_version('1.0.0')
self.assertEqual(
mock_run.call_args_list,
[mock.call('git add semantic_release/__init__.py', hide=True),
mock.call('git commit -m "1.0.0"', hide=True)]
)
|
from unittest import TestCase, mock
from invoke.runner import Result
from semantic_release.git_helpers import (commit_new_version, get_commit_log, push_new_version,
tag_new_version)
class GitHelpersTests(TestCase):
def test_first_commit_is_not_initial_commit(self):
self.assertNotEqual(next(get_commit_log()), 'Initial commit')
@mock.patch('semantic_release.git_helpers.run',
return_value=Result(stdout='', stderr='', pty='', exited=0))
def test_add_and_commit(self, mock_run):
commit_new_version('1.0.0')
self.assertEqual(
mock_run.call_args_list,
[mock.call('git add semantic_release/__init__.py', hide=True),
mock.call('git commit -m "1.0.0"', hide=True)]
)
@mock.patch('semantic_release.git_helpers.run')
def test_tag_new_version(self, mock_run):
tag_new_version('1.0.0')
mock_run.assert_called_with('git tag v1.0.0 HEAD', hide=True)
@mock.patch('semantic_release.git_helpers.run')
def test_push_new_version(self, mock_run):
push_new_version()
mock_run.assert_called_with('git push && git push --tags', hide=True)
|
Add test for git helpers
|
Add test for git helpers
|
Python
|
mit
|
relekang/python-semantic-release,relekang/python-semantic-release,wlonk/python-semantic-release,riddlesio/python-semantic-release,jvrsantacruz/python-semantic-release
|
python
|
## Code Before:
from unittest import TestCase, mock
from invoke.runner import Result
from semantic_release.git_helpers import commit_new_version, get_commit_log
class GetCommitLogTest(TestCase):
def test_first_commit_is_not_initial_commit(self):
self.assertNotEqual(next(get_commit_log()), 'Initial commit')
class CommitNewVersionTests(TestCase):
@mock.patch('semantic_release.git_helpers.run',
return_value=Result(stdout='', stderr='', pty='', exited=0))
def test_add_and_commit(self, mock_run):
commit_new_version('1.0.0')
self.assertEqual(
mock_run.call_args_list,
[mock.call('git add semantic_release/__init__.py', hide=True),
mock.call('git commit -m "1.0.0"', hide=True)]
)
## Instruction:
Add test for git helpers
## Code After:
from unittest import TestCase, mock
from invoke.runner import Result
from semantic_release.git_helpers import (commit_new_version, get_commit_log, push_new_version,
tag_new_version)
class GitHelpersTests(TestCase):
def test_first_commit_is_not_initial_commit(self):
self.assertNotEqual(next(get_commit_log()), 'Initial commit')
@mock.patch('semantic_release.git_helpers.run',
return_value=Result(stdout='', stderr='', pty='', exited=0))
def test_add_and_commit(self, mock_run):
commit_new_version('1.0.0')
self.assertEqual(
mock_run.call_args_list,
[mock.call('git add semantic_release/__init__.py', hide=True),
mock.call('git commit -m "1.0.0"', hide=True)]
)
@mock.patch('semantic_release.git_helpers.run')
def test_tag_new_version(self, mock_run):
tag_new_version('1.0.0')
mock_run.assert_called_with('git tag v1.0.0 HEAD', hide=True)
@mock.patch('semantic_release.git_helpers.run')
def test_push_new_version(self, mock_run):
push_new_version()
mock_run.assert_called_with('git push && git push --tags', hide=True)
|
// ... existing code ...
from invoke.runner import Result
from semantic_release.git_helpers import (commit_new_version, get_commit_log, push_new_version,
tag_new_version)
class GitHelpersTests(TestCase):
def test_first_commit_is_not_initial_commit(self):
self.assertNotEqual(next(get_commit_log()), 'Initial commit')
@mock.patch('semantic_release.git_helpers.run',
return_value=Result(stdout='', stderr='', pty='', exited=0))
def test_add_and_commit(self, mock_run):
// ... modified code ...
[mock.call('git add semantic_release/__init__.py', hide=True),
mock.call('git commit -m "1.0.0"', hide=True)]
)
@mock.patch('semantic_release.git_helpers.run')
def test_tag_new_version(self, mock_run):
tag_new_version('1.0.0')
mock_run.assert_called_with('git tag v1.0.0 HEAD', hide=True)
@mock.patch('semantic_release.git_helpers.run')
def test_push_new_version(self, mock_run):
push_new_version()
mock_run.assert_called_with('git push && git push --tags', hide=True)
// ... rest of the code ...
|
edd2cc66fff3159699c28c8f86c52e6524ce9d86
|
social_auth/fields.py
|
social_auth/fields.py
|
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_db_prep_value(self, value, connection, prepared=False):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
|
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
|
Use get_prep_value instead of the database related one. Closes gh-42
|
Use get_prep_value instead of the database related one. Closes gh-42
|
Python
|
bsd-3-clause
|
vuchau/django-social-auth,getsentry/django-social-auth,1st/django-social-auth,michael-borisov/django-social-auth,michael-borisov/django-social-auth,beswarm/django-social-auth,lovehhf/django-social-auth,omab/django-social-auth,adw0rd/django-social-auth,mayankcu/Django-social,caktus/django-social-auth,antoviaque/django-social-auth-norel,vuchau/django-social-auth,thesealion/django-social-auth,dongguangming/django-social-auth,limdauto/django-social-auth,dongguangming/django-social-auth,vxvinh1511/django-social-auth,omab/django-social-auth,duoduo369/django-social-auth,VishvajitP/django-social-auth,brianmckinneyrocks/django-social-auth,beswarm/django-social-auth,MjAbuz/django-social-auth,brianmckinneyrocks/django-social-auth,czpython/django-social-auth,lovehhf/django-social-auth,MjAbuz/django-social-auth,sk7/django-social-auth,qas612820704/django-social-auth,gustavoam/django-social-auth,caktus/django-social-auth,gustavoam/django-social-auth,vxvinh1511/django-social-auth,krvss/django-social-auth,VishvajitP/django-social-auth,WW-Digital/django-social-auth,qas612820704/django-social-auth,thesealion/django-social-auth,limdauto/django-social-auth
|
python
|
## Code Before:
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_db_prep_value(self, value, connection, prepared=False):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
## Instruction:
Use get_prep_value instead of the database related one. Closes gh-42
## Code After:
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
|
# ... existing code ...
except Exception, e:
raise ValidationError(str(e))
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
# ... rest of the code ...
|
a3975cc9d4a388789fcdaf07ece011b01801f162
|
hilbert/decorators.py
|
hilbert/decorators.py
|
from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
from django.utils.log import getLogger
logger = getLogger('django-hilbert')
def ajax_login_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
response = http.HttpResponse()
response['X-Django-Requires-Auth'] = True
response['X-Django-Login-Url'] = settings.LOGIN_URL
return response
else:
return login_required(view_func)(request, *args, **kwargs)
return _wrapped_view
def ajax_only(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
logger.warning(u'AJAX required: %s' % request.path, extra={'request': request})
return http.HttpResponseBadRequest()
return _wrapped_view
|
from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
def ajax_login_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
response = http.HttpResponse()
response['X-Django-Requires-Auth'] = True
response['X-Django-Login-Url'] = settings.LOGIN_URL
return response
else:
return login_required(view_func)(request, *args, **kwargs)
return _wrapped_view
def ajax_only(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
return http.HttpResponseBadRequest()
return _wrapped_view
|
Remove logging to preserve 1.2 compatability.
|
Remove logging to preserve 1.2 compatability.
|
Python
|
bsd-2-clause
|
mlavin/django-hilbert,mlavin/django-hilbert
|
python
|
## Code Before:
from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
from django.utils.log import getLogger
logger = getLogger('django-hilbert')
def ajax_login_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
response = http.HttpResponse()
response['X-Django-Requires-Auth'] = True
response['X-Django-Login-Url'] = settings.LOGIN_URL
return response
else:
return login_required(view_func)(request, *args, **kwargs)
return _wrapped_view
def ajax_only(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
logger.warning(u'AJAX required: %s' % request.path, extra={'request': request})
return http.HttpResponseBadRequest()
return _wrapped_view
## Instruction:
Remove logging to preserve 1.2 compatability.
## Code After:
from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
def ajax_login_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
response = http.HttpResponse()
response['X-Django-Requires-Auth'] = True
response['X-Django-Login-Url'] = settings.LOGIN_URL
return response
else:
return login_required(view_func)(request, *args, **kwargs)
return _wrapped_view
def ajax_only(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
return http.HttpResponseBadRequest()
return _wrapped_view
|
// ... existing code ...
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
def ajax_login_required(view_func):
// ... modified code ...
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
return http.HttpResponseBadRequest()
return _wrapped_view
// ... rest of the code ...
|
6f80a7e5f8dea031db1c7cc676f8c96faf5fc458
|
test/test_links.py
|
test/test_links.py
|
import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(File, name, linked_to):
assert File(name).exists
assert File(name).is_symlink
assert File(name).linked_to == str(linked_to)
|
import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(host, name, linked_to):
file = host.file(name)
assert file.exists
assert file.is_symlink
assert file.linked_to == str(linked_to)
|
Change test function as existing method deprecated
|
Change test function as existing method deprecated
|
Python
|
mit
|
wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build
|
python
|
## Code Before:
import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(File, name, linked_to):
assert File(name).exists
assert File(name).is_symlink
assert File(name).linked_to == str(linked_to)
## Instruction:
Change test function as existing method deprecated
## Code After:
import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(host, name, linked_to):
file = host.file(name)
assert file.exists
assert file.is_symlink
assert file.linked_to == str(linked_to)
|
...
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(host, name, linked_to):
file = host.file(name)
assert file.exists
assert file.is_symlink
assert file.linked_to == str(linked_to)
...
|
6f24aa5e1e1ff78e95ed17ff75acc2646280bdd8
|
typedmarshal/util.py
|
typedmarshal/util.py
|
def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
elif isinstance(obj, dict):
for k, v in obj:
i_print(f'{k}: {v}')
else:
for k, v in obj.__dict__.items():
if not k.startswith('_'):
if v.__class__.__name__ not in __builtins__:
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent+2)
elif isinstance(v, (list, dict)):
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent)
else:
i_print(f'{k}: {v}')
|
def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
elif isinstance(obj, dict):
for k, v in obj.items():
i_print(f'{k}: {repr(v)}')
else:
for k, v in obj.__dict__.items():
if not k.startswith('_'):
if v is None:
i_print(f'{k}: None')
elif v.__class__.__name__ not in __builtins__:
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent+2)
elif isinstance(v, (list, dict)):
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent)
else:
i_print(f'{k}: {repr(v)}')
|
Add None identifier / repr print
|
Add None identifier / repr print
|
Python
|
bsd-3-clause
|
puhitaku/typedmarshal
|
python
|
## Code Before:
def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
elif isinstance(obj, dict):
for k, v in obj:
i_print(f'{k}: {v}')
else:
for k, v in obj.__dict__.items():
if not k.startswith('_'):
if v.__class__.__name__ not in __builtins__:
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent+2)
elif isinstance(v, (list, dict)):
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent)
else:
i_print(f'{k}: {v}')
## Instruction:
Add None identifier / repr print
## Code After:
def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
elif isinstance(obj, dict):
for k, v in obj.items():
i_print(f'{k}: {repr(v)}')
else:
for k, v in obj.__dict__.items():
if not k.startswith('_'):
if v is None:
i_print(f'{k}: None')
elif v.__class__.__name__ not in __builtins__:
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent+2)
elif isinstance(v, (list, dict)):
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent)
else:
i_print(f'{k}: {repr(v)}')
|
...
for l in obj:
pretty_print_recursive(l, indent=indent+2)
elif isinstance(obj, dict):
for k, v in obj.items():
i_print(f'{k}: {repr(v)}')
else:
for k, v in obj.__dict__.items():
if not k.startswith('_'):
if v is None:
i_print(f'{k}: None')
elif v.__class__.__name__ not in __builtins__:
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent+2)
elif isinstance(v, (list, dict)):
...
i_print(f'{k}:')
pretty_print_recursive(v, indent=indent)
else:
i_print(f'{k}: {repr(v)}')
...
|
2ed55f8d7eef0709bf1c96356d98605dd28ce442
|
machine/include/config.h
|
machine/include/config.h
|
// The trampoline must be mapped at the same vaddr for both the kernel and
// the userspace processes. The page is mapped to the last VPN slot available
// Sv39 has 39bit adresses: 2^39 - PAGESIZE = 0x80'0000'0000 - 0x100 = 0x80'0000'0000
// It will be mapped twice in the kernel address space
#define TRAMPOLINE_VADDR 0x7FFFFFFF00
// The top-most stack address for a user process. As the stack grows downwards, it's best to place it after the trap trampoline to prevent collisions.
// As specified by the RISC-V ELF psABI (https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md),
// we use a descending full stack, i.e. sp points to the last pushed element in the stack
// Thus, USERSPACE_STACK_START shall be positioned one above the actual first stack slot.
#define USERSPACE_STACK_START TRAMPOLINE_VADDR
#endif
|
// The trampoline must be mapped at the same vaddr for both the kernel and
// the userspace processes. The page is mapped to the last VPN slot available
// Sv39 has 39bit adresses: 2^39 - PAGESIZE = 0x80'0000'0000 - 0x100 = 0x7F'FFFF'F000
// According to the Sv39 documentation, the vaddr "must have bits 63–39 all equal to bit 38, or else a page-fault
// exception will occur", thus the actual vaddr is 0xFFFF'FFFF'FFFF'F000
// It will be mapped twice in the kernel address space
#define TRAMPOLINE_VADDR 0xFFFFFFFFFFFFF000
// The top-most stack address for a user process. As the stack grows downwards, it's best to place it after the trap trampoline to prevent collisions.
// As specified by the RISC-V ELF psABI (https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md),
// we use a descending full stack, i.e. sp points to the last pushed element in the stack
// Thus, USERSPACE_STACK_START shall be positioned one above the actual first stack slot.
#define USERSPACE_STACK_START TRAMPOLINE_VADDR
#endif
|
Fix trap trampoline virtual address
|
Fix trap trampoline virtual address [skip ci]
We want to map the trap trampoline to the highest possible virtual
address, i.e. the last PTE possible. However, Sv39 specifies that bits
39-63 must reflect bit 38's state lest the CPU raises a page fault.
|
C
|
bsd-2-clause
|
cksystemsteaching/selfie,ChristianMoesl/selfie,cksystemsteaching/selfie,ChristianMoesl/selfie,cksystemsteaching/selfie
|
c
|
## Code Before:
// The trampoline must be mapped at the same vaddr for both the kernel and
// the userspace processes. The page is mapped to the last VPN slot available
// Sv39 has 39bit adresses: 2^39 - PAGESIZE = 0x80'0000'0000 - 0x100 = 0x80'0000'0000
// It will be mapped twice in the kernel address space
#define TRAMPOLINE_VADDR 0x7FFFFFFF00
// The top-most stack address for a user process. As the stack grows downwards, it's best to place it after the trap trampoline to prevent collisions.
// As specified by the RISC-V ELF psABI (https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md),
// we use a descending full stack, i.e. sp points to the last pushed element in the stack
// Thus, USERSPACE_STACK_START shall be positioned one above the actual first stack slot.
#define USERSPACE_STACK_START TRAMPOLINE_VADDR
#endif
## Instruction:
Fix trap trampoline virtual address [skip ci]
We want to map the trap trampoline to the highest possible virtual
address, i.e. the last PTE possible. However, Sv39 specifies that bits
39-63 must reflect bit 38's state lest the CPU raises a page fault.
## Code After:
// The trampoline must be mapped at the same vaddr for both the kernel and
// the userspace processes. The page is mapped to the last VPN slot available
// Sv39 has 39bit adresses: 2^39 - PAGESIZE = 0x80'0000'0000 - 0x100 = 0x7F'FFFF'F000
// According to the Sv39 documentation, the vaddr "must have bits 63–39 all equal to bit 38, or else a page-fault
// exception will occur", thus the actual vaddr is 0xFFFF'FFFF'FFFF'F000
// It will be mapped twice in the kernel address space
#define TRAMPOLINE_VADDR 0xFFFFFFFFFFFFF000
// The top-most stack address for a user process. As the stack grows downwards, it's best to place it after the trap trampoline to prevent collisions.
// As specified by the RISC-V ELF psABI (https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md),
// we use a descending full stack, i.e. sp points to the last pushed element in the stack
// Thus, USERSPACE_STACK_START shall be positioned one above the actual first stack slot.
#define USERSPACE_STACK_START TRAMPOLINE_VADDR
#endif
|
# ... existing code ...
// The trampoline must be mapped at the same vaddr for both the kernel and
// the userspace processes. The page is mapped to the last VPN slot available
// Sv39 has 39bit adresses: 2^39 - PAGESIZE = 0x80'0000'0000 - 0x100 = 0x7F'FFFF'F000
// According to the Sv39 documentation, the vaddr "must have bits 63–39 all equal to bit 38, or else a page-fault
// exception will occur", thus the actual vaddr is 0xFFFF'FFFF'FFFF'F000
// It will be mapped twice in the kernel address space
#define TRAMPOLINE_VADDR 0xFFFFFFFFFFFFF000
// The top-most stack address for a user process. As the stack grows downwards, it's best to place it after the trap trampoline to prevent collisions.
// As specified by the RISC-V ELF psABI (https://github.com/riscv/riscv-elf-psabi-doc/blob/master/riscv-elf.md),
# ... rest of the code ...
|
b46dc26e5e1b4c0388c330017dc52393417c3323
|
tests/test_init.py
|
tests/test_init.py
|
from disco.test import TestCase, TestJob
class InitJob(TestJob):
sort = False
@staticmethod
def map_reader(stream, size, url, params):
params.x = 10
return (stream, size, url)
@staticmethod
def map_init(iter, params):
assert hasattr(params, 'x')
iter.next()
params['x'] += 100
@staticmethod
def map(e, params):
yield e, int(e) + params['x']
@staticmethod
def reduce_init(iter, params):
params['y'] = 1000
@staticmethod
def reduce(iter, params):
for k, v in iter:
yield k, int(v) + params['y']
class InitTestCase(TestCase):
def serve(self, path):
return 'skipthis\n' + ('%s\n' % path) * 10
def runTest(self):
self.job = InitJob().run(input=self.test_server.urls(range(10)))
results = list(self.results(self.job))
for k, v in results:
self.assertEquals(int(k) + 1110, int(v))
self.assertEquals(len(results), 100)
|
from disco.test import TestCase, TestJob
class InitJob(TestJob):
params = {'x': 10}
sort = False
@staticmethod
def map_init(iter, params):
iter.next()
params['x'] += 100
@staticmethod
def map(e, params):
yield e, int(e) + params['x']
@staticmethod
def reduce_init(iter, params):
params['y'] = 1000
@staticmethod
def reduce(iter, params):
for k, v in iter:
yield k, int(v) + params['y']
class InitTestCase(TestCase):
def serve(self, path):
return 'skipthis\n' + ('%s\n' % path) * 10
def runTest(self):
self.job = InitJob().run(input=self.test_server.urls(range(10)))
results = list(self.results(self.job))
for k, v in results:
self.assertEquals(int(k) + 1110, int(v))
self.assertEquals(len(results), 100)
|
Revert "added a test for the map_reader before map_init -case which fails currently" (deprecate init functions instead)
|
Revert "added a test for the map_reader before map_init -case which fails currently"
(deprecate init functions instead)
This reverts commit 88551bf444b7b358fea8e7eb4475df2c5d87ceeb.
|
Python
|
bsd-3-clause
|
ErikDubbelboer/disco,pombredanne/disco,mwilliams3/disco,simudream/disco,pombredanne/disco,simudream/disco,mozilla/disco,beni55/disco,ErikDubbelboer/disco,pavlobaron/disco_playground,pooya/disco,ktkt2009/disco,scrapinghub/disco,seabirdzh/disco,pombredanne/disco,pooya/disco,pombredanne/disco,mwilliams3/disco,ktkt2009/disco,oldmantaiter/disco,simudream/disco,discoproject/disco,seabirdzh/disco,discoproject/disco,mwilliams3/disco,pavlobaron/disco_playground,oldmantaiter/disco,discoproject/disco,simudream/disco,beni55/disco,mozilla/disco,scrapinghub/disco,oldmantaiter/disco,pombredanne/disco,mwilliams3/disco,beni55/disco,mozilla/disco,scrapinghub/disco,ktkt2009/disco,scrapinghub/disco,seabirdzh/disco,discoproject/disco,seabirdzh/disco,beni55/disco,ErikDubbelboer/disco,mozilla/disco,ErikDubbelboer/disco,mwilliams3/disco,pooya/disco,seabirdzh/disco,pavlobaron/disco_playground,pavlobaron/disco_playground,ktkt2009/disco,ktkt2009/disco,discoproject/disco,simudream/disco,pooya/disco,beni55/disco,oldmantaiter/disco,oldmantaiter/disco,ErikDubbelboer/disco
|
python
|
## Code Before:
from disco.test import TestCase, TestJob
class InitJob(TestJob):
sort = False
@staticmethod
def map_reader(stream, size, url, params):
params.x = 10
return (stream, size, url)
@staticmethod
def map_init(iter, params):
assert hasattr(params, 'x')
iter.next()
params['x'] += 100
@staticmethod
def map(e, params):
yield e, int(e) + params['x']
@staticmethod
def reduce_init(iter, params):
params['y'] = 1000
@staticmethod
def reduce(iter, params):
for k, v in iter:
yield k, int(v) + params['y']
class InitTestCase(TestCase):
def serve(self, path):
return 'skipthis\n' + ('%s\n' % path) * 10
def runTest(self):
self.job = InitJob().run(input=self.test_server.urls(range(10)))
results = list(self.results(self.job))
for k, v in results:
self.assertEquals(int(k) + 1110, int(v))
self.assertEquals(len(results), 100)
## Instruction:
Revert "added a test for the map_reader before map_init -case which fails currently"
(deprecate init functions instead)
This reverts commit 88551bf444b7b358fea8e7eb4475df2c5d87ceeb.
## Code After:
from disco.test import TestCase, TestJob
class InitJob(TestJob):
params = {'x': 10}
sort = False
@staticmethod
def map_init(iter, params):
iter.next()
params['x'] += 100
@staticmethod
def map(e, params):
yield e, int(e) + params['x']
@staticmethod
def reduce_init(iter, params):
params['y'] = 1000
@staticmethod
def reduce(iter, params):
for k, v in iter:
yield k, int(v) + params['y']
class InitTestCase(TestCase):
def serve(self, path):
return 'skipthis\n' + ('%s\n' % path) * 10
def runTest(self):
self.job = InitJob().run(input=self.test_server.urls(range(10)))
results = list(self.results(self.job))
for k, v in results:
self.assertEquals(int(k) + 1110, int(v))
self.assertEquals(len(results), 100)
|
...
from disco.test import TestCase, TestJob
class InitJob(TestJob):
params = {'x': 10}
sort = False
@staticmethod
def map_init(iter, params):
iter.next()
params['x'] += 100
...
|
c535e5450e909e53a6ed7c17e6bea79150b5dddc
|
src/test/java/info/u_team/u_team_test/init/TestBiomes.java
|
src/test/java/info/u_team/u_team_test/init/TestBiomes.java
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.biome.BasicBiome;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestBiomes {
public static final Biome BASIC = new BasicBiome("basic");
@SubscribeEvent
public static void register(Register<Biome> event) {
BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register);
}
}
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.biome.BasicBiome;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
//@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestBiomes {
//public static final Biome BASIC = new BasicBiome("basic");
public static final DeferredRegister<Biome> BLOCKS = DeferredRegister.create(ForgeRegistries.BIOMES, TestMod.MODID);
public static final RegistryObject<BasicBiome> BASIC = BLOCKS.register("basic", () -> new BasicBiome("basic"));
// @SubscribeEvent
// public static void register(Register<Biome> event) {
// BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register);
// }
}
|
Test deferred registry with biomes
|
Test deferred registry with biomes
|
Java
|
apache-2.0
|
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
|
java
|
## Code Before:
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.biome.BasicBiome;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestBiomes {
public static final Biome BASIC = new BasicBiome("basic");
@SubscribeEvent
public static void register(Register<Biome> event) {
BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register);
}
}
## Instruction:
Test deferred registry with biomes
## Code After:
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.biome.BasicBiome;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
//@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestBiomes {
//public static final Biome BASIC = new BasicBiome("basic");
public static final DeferredRegister<Biome> BLOCKS = DeferredRegister.create(ForgeRegistries.BIOMES, TestMod.MODID);
public static final RegistryObject<BasicBiome> BASIC = BLOCKS.register("basic", () -> new BasicBiome("basic"));
// @SubscribeEvent
// public static void register(Register<Biome> event) {
// BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register);
// }
}
|
# ... existing code ...
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
//@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestBiomes {
//public static final Biome BASIC = new BasicBiome("basic");
public static final DeferredRegister<Biome> BLOCKS = DeferredRegister.create(ForgeRegistries.BIOMES, TestMod.MODID);
public static final RegistryObject<BasicBiome> BASIC = BLOCKS.register("basic", () -> new BasicBiome("basic"));
// @SubscribeEvent
// public static void register(Register<Biome> event) {
// BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register);
// }
}
# ... rest of the code ...
|
b1edcbe02e2e1b2c54fd96c994e2c83e27e9b7b9
|
test/client/local_recognizer_test.py
|
test/client/local_recognizer_test.py
|
import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
|
import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerLoop()
self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
|
Fix init of local recognizer
|
Fix init of local recognizer
|
Python
|
apache-2.0
|
MycroftAI/mycroft-core,aatchison/mycroft-core,linuxipho/mycroft-core,forslund/mycroft-core,Dark5ide/mycroft-core,linuxipho/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core,Dark5ide/mycroft-core,aatchison/mycroft-core
|
python
|
## Code Before:
import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
## Instruction:
Fix init of local recognizer
## Code After:
import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerLoop()
self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
|
# ... existing code ...
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerLoop()
self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
16000,
"en-us")
def testRecognizerWrapper(self):
# ... rest of the code ...
|
f00ae3046436f09e62460a8468e031a0c2027e7f
|
scikits/learn/machine/em/__init__.py
|
scikits/learn/machine/em/__init__.py
|
from info import __doc__
from gauss_mix import GmParamError, GM
from gmm_em import GmmParamError, GMM, EM
from online_em import OnGMM as _OnGMM
__all__ = filter(lambda s:not s.startswith('_'), dir())
from numpy.testing import NumpyTest
test = NumpyTest().test
def test_suite(*args):
# XXX: this is to avoid recursive call to itself. This is an horrible hack,
# I have no idea why infinite recursion happens otherwise.
if len(args) > 0:
import unittest
return unittest.TestSuite()
np = NumpyTest()
np.testfile_patterns.append(r'test_examples.py')
return np.test(level = -10, verbosity = 5)
|
from info import __doc__
from gauss_mix import GmParamError, GM
from gmm_em import GmmParamError, GMM, EM
from online_em import OnGMM as _OnGMM
__all__ = filter(lambda s:not s.startswith('_'), dir())
|
Remove deprecated test runned for em machine.
|
Remove deprecated test runned for em machine.
From: cdavid <cdavid@cb17146a-f446-4be1-a4f7-bd7c5bb65646>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@271 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8
|
Python
|
bsd-3-clause
|
xzh86/scikit-learn,Akshay0724/scikit-learn,fyffyt/scikit-learn,jlegendary/scikit-learn,henridwyer/scikit-learn,Djabbz/scikit-learn,shenzebang/scikit-learn,mrshu/scikit-learn,costypetrisor/scikit-learn,jlegendary/scikit-learn,manhhomienbienthuy/scikit-learn,thientu/scikit-learn,marcocaccin/scikit-learn,xavierwu/scikit-learn,krez13/scikit-learn,fabianp/scikit-learn,kmike/scikit-learn,arabenjamin/scikit-learn,NunoEdgarGub1/scikit-learn,frank-tancf/scikit-learn,carrillo/scikit-learn,quheng/scikit-learn,wlamond/scikit-learn,wlamond/scikit-learn,hrjn/scikit-learn,Akshay0724/scikit-learn,phdowling/scikit-learn,466152112/scikit-learn,jakobworldpeace/scikit-learn,billy-inn/scikit-learn,devanshdalal/scikit-learn,vybstat/scikit-learn,terkkila/scikit-learn,hsuantien/scikit-learn,equialgo/scikit-learn,etkirsch/scikit-learn,pnedunuri/scikit-learn,hainm/scikit-learn,qifeigit/scikit-learn,mwv/scikit-learn,rexshihaoren/scikit-learn,zorroblue/scikit-learn,manhhomienbienthuy/scikit-learn,ky822/scikit-learn,deepesch/scikit-learn,bnaul/scikit-learn,ashhher3/scikit-learn,hitszxp/scikit-learn,thilbern/scikit-learn,xubenben/scikit-learn,terkkila/scikit-learn,ivannz/scikit-learn,justincassidy/scikit-learn,meduz/scikit-learn,Aasmi/scikit-learn,robbymeals/scikit-learn,IndraVikas/scikit-learn,simon-pepin/scikit-learn,aabadie/scikit-learn,liyu1990/sklearn,arjoly/scikit-learn,beepee14/scikit-learn,bikong2/scikit-learn,sarahgrogan/scikit-learn,dhruv13J/scikit-learn,ankurankan/scikit-learn,xwolf12/scikit-learn,beepee14/scikit-learn,shangwuhencc/scikit-learn,lin-credible/scikit-learn,jorik041/scikit-learn,fabioticconi/scikit-learn,r-mart/scikit-learn,nmayorov/scikit-learn,hitszxp/scikit-learn,ChanderG/scikit-learn,mattilyra/scikit-learn,mjudsp/Tsallis,potash/scikit-learn,jmschrei/scikit-learn,samzhang111/scikit-learn,appapantula/scikit-learn,cainiaocome/scikit-learn,mxjl620/scikit-learn,herilalaina/scikit-learn,vivekmishra1991/scikit-learn,sumspr/scikit-learn,jm-begon/scikit-learn,ogrisel/scikit-learn,YinongLong/scikit-learn,icdishb/scikit-learn,kjung/scikit-learn,ankurankan/scikit-learn,Vimos/scikit-learn,ningchi/scikit-learn,henrykironde/scikit-learn,0asa/scikit-learn,cauchycui/scikit-learn,NelisVerhoef/scikit-learn,aetilley/scikit-learn,MohammedWasim/scikit-learn,giorgiop/scikit-learn,samuel1208/scikit-learn,voxlol/scikit-learn,Achuth17/scikit-learn,Myasuka/scikit-learn,ndingwall/scikit-learn,qifeigit/scikit-learn,anurag313/scikit-learn,henridwyer/scikit-learn,PrashntS/scikit-learn,evgchz/scikit-learn,bikong2/scikit-learn,Barmaley-exe/scikit-learn,florian-f/sklearn,glemaitre/scikit-learn,roxyboy/scikit-learn,jm-begon/scikit-learn,shikhardb/scikit-learn,kashif/scikit-learn,thientu/scikit-learn,arjoly/scikit-learn,fzalkow/scikit-learn,mehdidc/scikit-learn,imaculate/scikit-learn,mhue/scikit-learn,MohammedWasim/scikit-learn,huobaowangxi/scikit-learn,wlamond/scikit-learn,mwv/scikit-learn,jjx02230808/project0223,shyamalschandra/scikit-learn,equialgo/scikit-learn,mikebenfield/scikit-learn,jereze/scikit-learn,PrashntS/scikit-learn,Garrett-R/scikit-learn,IshankGulati/scikit-learn,AlexandreAbraham/scikit-learn,beepee14/scikit-learn,mojoboss/scikit-learn,sumspr/scikit-learn,akionakamura/scikit-learn,sergeyf/scikit-learn,3manuek/scikit-learn,mjudsp/Tsallis,dsullivan7/scikit-learn,LohithBlaze/scikit-learn,thilbern/scikit-learn,Garrett-R/scikit-learn,JosmanPS/scikit-learn,bhargav/scikit-learn,ngoix/OCRF,hitszxp/scikit-learn,chrsrds/scikit-learn,phdowling/scikit-learn,bthirion/scikit-learn,olologin/scikit-learn,procoder317/scikit-learn,Garrett-R/scikit-learn,RPGOne/scikit-learn,evgchz/scikit-learn,shangwuhencc/scikit-learn,moutai/scikit-learn,hainm/scikit-learn,MatthieuBizien/scikit-learn,cainiaocome/scikit-learn,zorroblue/scikit-learn,jakobworldpeace/scikit-learn,MatthieuBizien/scikit-learn,anurag313/scikit-learn,marcocaccin/scikit-learn,DonBeo/scikit-learn,petosegan/scikit-learn,florian-f/sklearn,pythonvietnam/scikit-learn,ominux/scikit-learn,YinongLong/scikit-learn,ycaihua/scikit-learn,ilyes14/scikit-learn,rsivapr/scikit-learn,lucidfrontier45/scikit-learn,JeanKossaifi/scikit-learn,nesterione/scikit-learn,lin-credible/scikit-learn,yonglehou/scikit-learn,appapantula/scikit-learn,hdmetor/scikit-learn,jorik041/scikit-learn,NunoEdgarGub1/scikit-learn,vibhorag/scikit-learn,espg/scikit-learn,belltailjp/scikit-learn,liyu1990/sklearn,jpautom/scikit-learn,etkirsch/scikit-learn,ltiao/scikit-learn,belltailjp/scikit-learn,BiaDarkia/scikit-learn,AnasGhrab/scikit-learn,zihua/scikit-learn,ssaeger/scikit-learn,Obus/scikit-learn,ltiao/scikit-learn,aminert/scikit-learn,sonnyhu/scikit-learn,yonglehou/scikit-learn,jseabold/scikit-learn,mayblue9/scikit-learn,cybernet14/scikit-learn,BiaDarkia/scikit-learn,hsiaoyi0504/scikit-learn,amueller/scikit-learn,h2educ/scikit-learn,chrisburr/scikit-learn,ky822/scikit-learn,florian-f/sklearn,cybernet14/scikit-learn,vibhorag/scikit-learn,victorbergelin/scikit-learn,mxjl620/scikit-learn,rahul-c1/scikit-learn,simon-pepin/scikit-learn,xyguo/scikit-learn,ephes/scikit-learn,shusenl/scikit-learn,spallavolu/scikit-learn,MartinSavc/scikit-learn,rrohan/scikit-learn,AlexandreAbraham/scikit-learn,B3AU/waveTree,ChanderG/scikit-learn,samuel1208/scikit-learn,cwu2011/scikit-learn,ChanderG/scikit-learn,JPFrancoia/scikit-learn,samzhang111/scikit-learn,heli522/scikit-learn,moutai/scikit-learn,ZENGXH/scikit-learn,ilo10/scikit-learn,NelisVerhoef/scikit-learn,jseabold/scikit-learn,pompiduskus/scikit-learn,ivannz/scikit-learn,shangwuhencc/scikit-learn,jblackburne/scikit-learn,tomlof/scikit-learn,roxyboy/scikit-learn,fzalkow/scikit-learn,q1ang/scikit-learn,madjelan/scikit-learn,macks22/scikit-learn,abimannans/scikit-learn,massmutual/scikit-learn,mattilyra/scikit-learn,AIML/scikit-learn,pnedunuri/scikit-learn,ominux/scikit-learn,nrhine1/scikit-learn,Srisai85/scikit-learn,xavierwu/scikit-learn,massmutual/scikit-learn,LohithBlaze/scikit-learn,ndingwall/scikit-learn,liangz0707/scikit-learn,clemkoa/scikit-learn,jaidevd/scikit-learn,nrhine1/scikit-learn,eg-zhang/scikit-learn,DSLituiev/scikit-learn,scikit-learn/scikit-learn,nikitasingh981/scikit-learn,mjudsp/Tsallis,nesterione/scikit-learn,zorojean/scikit-learn,huobaowangxi/scikit-learn,huobaowangxi/scikit-learn,ningchi/scikit-learn,murali-munna/scikit-learn,rsivapr/scikit-learn,aetilley/scikit-learn,vinayak-mehta/scikit-learn,plissonf/scikit-learn,jm-begon/scikit-learn,stylianos-kampakis/scikit-learn,tdhopper/scikit-learn,xuewei4d/scikit-learn,hainm/scikit-learn,liangz0707/scikit-learn,0x0all/scikit-learn,robbymeals/scikit-learn,0x0all/scikit-learn,dhruv13J/scikit-learn,zorojean/scikit-learn,rajat1994/scikit-learn,ahoyosid/scikit-learn,jlegendary/scikit-learn,meduz/scikit-learn,joshloyal/scikit-learn,bigdataelephants/scikit-learn,dingocuster/scikit-learn,yonglehou/scikit-learn,jkarnows/scikit-learn,amueller/scikit-learn,rrohan/scikit-learn,jaidevd/scikit-learn,zhenv5/scikit-learn,liyu1990/sklearn,elkingtonmcb/scikit-learn,lenovor/scikit-learn,IshankGulati/scikit-learn,kaichogami/scikit-learn,cdegroc/scikit-learn,zaxtax/scikit-learn,3manuek/scikit-learn,CVML/scikit-learn,abhishekgahlot/scikit-learn,mugizico/scikit-learn,yanlend/scikit-learn,mwv/scikit-learn,ngoix/OCRF,nvoron23/scikit-learn,glennq/scikit-learn,h2educ/scikit-learn,Vimos/scikit-learn,zhenv5/scikit-learn,krez13/scikit-learn,mjgrav2001/scikit-learn,nvoron23/scikit-learn,wazeerzulfikar/scikit-learn,Clyde-fare/scikit-learn,khkaminska/scikit-learn,ningchi/scikit-learn,larsmans/scikit-learn,hdmetor/scikit-learn,voxlol/scikit-learn,mayblue9/scikit-learn,kjung/scikit-learn,mojoboss/scikit-learn,hsuantien/scikit-learn,tomlof/scikit-learn,kagayakidan/scikit-learn,mojoboss/scikit-learn,fabioticconi/scikit-learn,ssaeger/scikit-learn,shikhardb/scikit-learn,massmutual/scikit-learn,Djabbz/scikit-learn,AlexRobson/scikit-learn,huzq/scikit-learn,trankmichael/scikit-learn,JsNoNo/scikit-learn,ky822/scikit-learn,gclenaghan/scikit-learn,Aasmi/scikit-learn,RomainBrault/scikit-learn,aabadie/scikit-learn,wzbozon/scikit-learn,lenovor/scikit-learn,jereze/scikit-learn,Garrett-R/scikit-learn,treycausey/scikit-learn,qifeigit/scikit-learn,466152112/scikit-learn,belltailjp/scikit-learn,LiaoPan/scikit-learn,sanketloke/scikit-learn,yanlend/scikit-learn,manashmndl/scikit-learn,Sentient07/scikit-learn,andrewnc/scikit-learn,jakobworldpeace/scikit-learn,nvoron23/scikit-learn,alexeyum/scikit-learn,tawsifkhan/scikit-learn,betatim/scikit-learn,pv/scikit-learn,mattgiguere/scikit-learn,0asa/scikit-learn,cl4rke/scikit-learn,luo66/scikit-learn,Nyker510/scikit-learn,michigraber/scikit-learn,depet/scikit-learn,phdowling/scikit-learn,AlexanderFabisch/scikit-learn,victorbergelin/scikit-learn,yunfeilu/scikit-learn,Nyker510/scikit-learn,ngoix/OCRF,espg/scikit-learn,appapantula/scikit-learn,chrsrds/scikit-learn,vigilv/scikit-learn,RachitKansal/scikit-learn,Adai0808/scikit-learn,siutanwong/scikit-learn,idlead/scikit-learn,ldirer/scikit-learn,bnaul/scikit-learn,pompiduskus/scikit-learn,tdhopper/scikit-learn,wzbozon/scikit-learn,cwu2011/scikit-learn,r-mart/scikit-learn,yyjiang/scikit-learn,wazeerzulfikar/scikit-learn,sgenoud/scikit-learn,etkirsch/scikit-learn,vivekmishra1991/scikit-learn,schets/scikit-learn,devanshdalal/scikit-learn,JPFrancoia/scikit-learn,loli/sklearn-ensembletrees,Adai0808/scikit-learn,davidgbe/scikit-learn,larsmans/scikit-learn,f3r/scikit-learn,shusenl/scikit-learn,jmetzen/scikit-learn,nrhine1/scikit-learn,petosegan/scikit-learn,pnedunuri/scikit-learn,Jimmy-Morzaria/scikit-learn,voxlol/scikit-learn,untom/scikit-learn,joshloyal/scikit-learn,pv/scikit-learn,ngoix/OCRF,shahankhatch/scikit-learn,phdowling/scikit-learn,hdmetor/scikit-learn,rishikksh20/scikit-learn,glemaitre/scikit-learn,IshankGulati/scikit-learn,Windy-Ground/scikit-learn,rahul-c1/scikit-learn,jorge2703/scikit-learn,siutanwong/scikit-learn,hitszxp/scikit-learn,DonBeo/scikit-learn,florian-f/sklearn,jayflo/scikit-learn,MohammedWasim/scikit-learn,sumspr/scikit-learn,devanshdalal/scikit-learn,ClimbsRocks/scikit-learn,alexsavio/scikit-learn,aflaxman/scikit-learn,cdegroc/scikit-learn,q1ang/scikit-learn,xubenben/scikit-learn,PatrickOReilly/scikit-learn,hugobowne/scikit-learn,jjx02230808/project0223,qifeigit/scikit-learn,q1ang/scikit-learn,dsquareindia/scikit-learn,henrykironde/scikit-learn,lbishal/scikit-learn,nikitasingh981/scikit-learn,kevin-intel/scikit-learn,fyffyt/scikit-learn,thilbern/scikit-learn,h2educ/scikit-learn,kagayakidan/scikit-learn,krez13/scikit-learn,cwu2011/scikit-learn,iismd17/scikit-learn,vinayak-mehta/scikit-learn,sonnyhu/scikit-learn,samzhang111/scikit-learn,PatrickOReilly/scikit-learn,ankurankan/scikit-learn,themrmax/scikit-learn,tosolveit/scikit-learn,RomainBrault/scikit-learn,vigilv/scikit-learn,gclenaghan/scikit-learn,CforED/Machine-Learning,mlyundin/scikit-learn,xyguo/scikit-learn,Clyde-fare/scikit-learn,equialgo/scikit-learn,andrewnc/scikit-learn,HolgerPeters/scikit-learn,luo66/scikit-learn,raghavrv/scikit-learn,aflaxman/scikit-learn,glemaitre/scikit-learn,zorroblue/scikit-learn,lucidfrontier45/scikit-learn,Srisai85/scikit-learn,vortex-ape/scikit-learn,djgagne/scikit-learn,kevin-intel/scikit-learn,Nyker510/scikit-learn,PatrickChrist/scikit-learn,dhruv13J/scikit-learn,MatthieuBizien/scikit-learn,waterponey/scikit-learn,ahoyosid/scikit-learn,IndraVikas/scikit-learn,spallavolu/scikit-learn,kylerbrown/scikit-learn,voxlol/scikit-learn,zuku1985/scikit-learn,mhdella/scikit-learn,tomlof/scikit-learn,mattgiguere/scikit-learn,bnaul/scikit-learn,fredhusser/scikit-learn,HolgerPeters/scikit-learn,wanggang3333/scikit-learn,alexeyum/scikit-learn,wlamond/scikit-learn,toastedcornflakes/scikit-learn,pkruskal/scikit-learn,maheshakya/scikit-learn,shangwuhencc/scikit-learn,mlyundin/scikit-learn,Lawrence-Liu/scikit-learn,rvraghav93/scikit-learn,Barmaley-exe/scikit-learn,vybstat/scikit-learn,Fireblend/scikit-learn,shahankhatch/scikit-learn,justincassidy/scikit-learn,pythonvietnam/scikit-learn,fredhusser/scikit-learn,bthirion/scikit-learn,depet/scikit-learn,AlexanderFabisch/scikit-learn,ndingwall/scikit-learn,vigilv/scikit-learn,B3AU/waveTree,xuewei4d/scikit-learn,pypot/scikit-learn,lbishal/scikit-learn,jakirkham/scikit-learn,Achuth17/scikit-learn,nmayorov/scikit-learn,vortex-ape/scikit-learn,vinayak-mehta/scikit-learn,dingocuster/scikit-learn,tawsifkhan/scikit-learn,mehdidc/scikit-learn,bikong2/scikit-learn,mojoboss/scikit-learn,PatrickOReilly/scikit-learn,Aasmi/scikit-learn,vermouthmjl/scikit-learn,robin-lai/scikit-learn,shenzebang/scikit-learn,Titan-C/scikit-learn,rishikksh20/scikit-learn,raghavrv/scikit-learn,robin-lai/scikit-learn,meduz/scikit-learn,akionakamura/scikit-learn,btabibian/scikit-learn,ZENGXH/scikit-learn,heli522/scikit-learn,hsiaoyi0504/scikit-learn,alvarofierroclavero/scikit-learn,mlyundin/scikit-learn,hugobowne/scikit-learn,loli/semisupervisedforests,Windy-Ground/scikit-learn,shahankhatch/scikit-learn,lucidfrontier45/scikit-learn,wanggang3333/scikit-learn,ahoyosid/scikit-learn,madjelan/scikit-learn,quheng/scikit-learn,altairpearl/scikit-learn,hsuantien/scikit-learn,gotomypc/scikit-learn,MartinDelzant/scikit-learn,fzalkow/scikit-learn,poryfly/scikit-learn,nrhine1/scikit-learn,RachitKansal/scikit-learn,davidgbe/scikit-learn,xwolf12/scikit-learn,MartinSavc/scikit-learn,evgchz/scikit-learn,anntzer/scikit-learn,aetilley/scikit-learn,tosolveit/scikit-learn,AlexandreAbraham/scikit-learn,rishikksh20/scikit-learn,trungnt13/scikit-learn,LiaoPan/scikit-learn,Achuth17/scikit-learn,f3r/scikit-learn,justincassidy/scikit-learn,manashmndl/scikit-learn,zaxtax/scikit-learn,saiwing-yeung/scikit-learn,wzbozon/scikit-learn,giorgiop/scikit-learn,sgenoud/scikit-learn,ilo10/scikit-learn,stylianos-kampakis/scikit-learn,OshynSong/scikit-learn,LohithBlaze/scikit-learn,siutanwong/scikit-learn,kagayakidan/scikit-learn,jm-begon/scikit-learn,pompiduskus/scikit-learn,Srisai85/scikit-learn,JPFrancoia/scikit-learn,Sentient07/scikit-learn,IssamLaradji/scikit-learn,abimannans/scikit-learn,MechCoder/scikit-learn,smartscheduling/scikit-learn-categorical-tree,rvraghav93/scikit-learn,dsullivan7/scikit-learn,nelson-liu/scikit-learn,TomDLT/scikit-learn,IssamLaradji/scikit-learn,mblondel/scikit-learn,ashhher3/scikit-learn,andaag/scikit-learn,petosegan/scikit-learn,ZenDevelopmentSystems/scikit-learn,nikitasingh981/scikit-learn,samuel1208/scikit-learn,massmutual/scikit-learn,hdmetor/scikit-learn,theoryno3/scikit-learn,JPFrancoia/scikit-learn,glennq/scikit-learn,frank-tancf/scikit-learn,anirudhjayaraman/scikit-learn,anirudhjayaraman/scikit-learn,ssaeger/scikit-learn,beepee14/scikit-learn,cl4rke/scikit-learn,xavierwu/scikit-learn,theoryno3/scikit-learn,glouppe/scikit-learn,mattilyra/scikit-learn,imaculate/scikit-learn,luo66/scikit-learn,Akshay0724/scikit-learn,ephes/scikit-learn,harshaneelhg/scikit-learn,mayblue9/scikit-learn,Srisai85/scikit-learn,jakirkham/scikit-learn,0x0all/scikit-learn,ZenDevelopmentSystems/scikit-learn,yanlend/scikit-learn,cdegroc/scikit-learn,amueller/scikit-learn,pythonvietnam/scikit-learn,jayflo/scikit-learn,untom/scikit-learn,plissonf/scikit-learn,trankmichael/scikit-learn,elkingtonmcb/scikit-learn,B3AU/waveTree,amueller/scikit-learn,alvarofierroclavero/scikit-learn,nomadcube/scikit-learn,vibhorag/scikit-learn,mfjb/scikit-learn,aetilley/scikit-learn,icdishb/scikit-learn,ankurankan/scikit-learn,jakobworldpeace/scikit-learn,billy-inn/scikit-learn,hlin117/scikit-learn,terkkila/scikit-learn,clemkoa/scikit-learn,walterreade/scikit-learn,arahuja/scikit-learn,kevin-intel/scikit-learn,maheshakya/scikit-learn,spallavolu/scikit-learn,heli522/scikit-learn,Akshay0724/scikit-learn,xzh86/scikit-learn,anirudhjayaraman/scikit-learn,wazeerzulfikar/scikit-learn,fbagirov/scikit-learn,cl4rke/scikit-learn,mblondel/scikit-learn,roxyboy/scikit-learn,eickenberg/scikit-learn,altairpearl/scikit-learn,pratapvardhan/scikit-learn,jayflo/scikit-learn,fbagirov/scikit-learn,ilyes14/scikit-learn,idlead/scikit-learn,devanshdalal/scikit-learn,zuku1985/scikit-learn,MechCoder/scikit-learn,theoryno3/scikit-learn,schets/scikit-learn,3manuek/scikit-learn,wzbozon/scikit-learn,adamgreenhall/scikit-learn,petosegan/scikit-learn,rohanp/scikit-learn,jmetzen/scikit-learn,manhhomienbienthuy/scikit-learn,ogrisel/scikit-learn,pkruskal/scikit-learn,RachitKansal/scikit-learn,idlead/scikit-learn,billy-inn/scikit-learn,herilalaina/scikit-learn,vshtanko/scikit-learn,ngoix/OCRF,bthirion/scikit-learn,herilalaina/scikit-learn,ominux/scikit-learn,fbagirov/scikit-learn,YinongLong/scikit-learn,trankmichael/scikit-learn,glouppe/scikit-learn,rajat1994/scikit-learn,thientu/scikit-learn,maheshakya/scikit-learn,shenzebang/scikit-learn,pianomania/scikit-learn,Obus/scikit-learn,vibhorag/scikit-learn,pratapvardhan/scikit-learn,btabibian/scikit-learn,arjoly/scikit-learn,Barmaley-exe/scikit-learn,costypetrisor/scikit-learn,elkingtonmcb/scikit-learn,aminert/scikit-learn,andrewnc/scikit-learn,walterreade/scikit-learn,akionakamura/scikit-learn,f3r/scikit-learn,smartscheduling/scikit-learn-categorical-tree,heli522/scikit-learn,ElDeveloper/scikit-learn,mikebenfield/scikit-learn,nomadcube/scikit-learn,depet/scikit-learn,shusenl/scikit-learn,iismd17/scikit-learn,michigraber/scikit-learn,tmhm/scikit-learn,JosmanPS/scikit-learn,macks22/scikit-learn,Titan-C/scikit-learn,ycaihua/scikit-learn,bikong2/scikit-learn,pv/scikit-learn,Fireblend/scikit-learn,mehdidc/scikit-learn,mhdella/scikit-learn,plissonf/scikit-learn,clemkoa/scikit-learn,jlegendary/scikit-learn,AlexRobson/scikit-learn,ycaihua/scikit-learn,dsquareindia/scikit-learn,manashmndl/scikit-learn,stylianos-kampakis/scikit-learn,aewhatley/scikit-learn,larsmans/scikit-learn,tmhm/scikit-learn,rajat1994/scikit-learn,aabadie/scikit-learn,nomadcube/scikit-learn,vortex-ape/scikit-learn,liyu1990/sklearn,smartscheduling/scikit-learn-categorical-tree,smartscheduling/scikit-learn-categorical-tree,henridwyer/scikit-learn,IssamLaradji/scikit-learn,cybernet14/scikit-learn,mrshu/scikit-learn,JosmanPS/scikit-learn,treycausey/scikit-learn,simon-pepin/scikit-learn,poryfly/scikit-learn,hitszxp/scikit-learn,jaidevd/scikit-learn,djgagne/scikit-learn,yask123/scikit-learn,sinhrks/scikit-learn,MatthieuBizien/scikit-learn,pnedunuri/scikit-learn,ZENGXH/scikit-learn,procoder317/scikit-learn,costypetrisor/scikit-learn,vshtanko/scikit-learn,jmetzen/scikit-learn,evgchz/scikit-learn,jkarnows/scikit-learn,ogrisel/scikit-learn,equialgo/scikit-learn,jorge2703/scikit-learn,glouppe/scikit-learn,trungnt13/scikit-learn,PatrickChrist/scikit-learn,ishanic/scikit-learn,glouppe/scikit-learn,abhishekkrthakur/scikit-learn,davidgbe/scikit-learn,jpautom/scikit-learn,liberatorqjw/scikit-learn,fengzhyuan/scikit-learn,huobaowangxi/scikit-learn,B3AU/waveTree,Jimmy-Morzaria/scikit-learn,vshtanko/scikit-learn,mfjb/scikit-learn,NunoEdgarGub1/scikit-learn,untom/scikit-learn,fabioticconi/scikit-learn,walterreade/scikit-learn,ldirer/scikit-learn,themrmax/scikit-learn,arabenjamin/scikit-learn,mhdella/scikit-learn,aabadie/scikit-learn,rsivapr/scikit-learn,zuku1985/scikit-learn,yunfeilu/scikit-learn,etkirsch/scikit-learn,btabibian/scikit-learn,chrisburr/scikit-learn,michigraber/scikit-learn,fredhusser/scikit-learn,waterponey/scikit-learn,NunoEdgarGub1/scikit-learn,mrshu/scikit-learn,AIML/scikit-learn,madjelan/scikit-learn,robbymeals/scikit-learn,sinhrks/scikit-learn,Sentient07/scikit-learn,ephes/scikit-learn,alexeyum/scikit-learn,fyffyt/scikit-learn,AnasGhrab/scikit-learn,murali-munna/scikit-learn,sarahgrogan/scikit-learn,rsivapr/scikit-learn,andaag/scikit-learn,ishanic/scikit-learn,lenovor/scikit-learn,raghavrv/scikit-learn,jseabold/scikit-learn,scikit-learn/scikit-learn,anurag313/scikit-learn,shusenl/scikit-learn,chrisburr/scikit-learn,RPGOne/scikit-learn,procoder317/scikit-learn,arjoly/scikit-learn,lin-credible/scikit-learn,AIML/scikit-learn,alvarofierroclavero/scikit-learn,yyjiang/scikit-learn,tawsifkhan/scikit-learn,russel1237/scikit-learn,jjx02230808/project0223,Barmaley-exe/scikit-learn,mrshu/scikit-learn,mfjb/scikit-learn,icdishb/scikit-learn,waterponey/scikit-learn,saiwing-yeung/scikit-learn,jzt5132/scikit-learn,joshloyal/scikit-learn,depet/scikit-learn,rexshihaoren/scikit-learn,xiaoxiamii/scikit-learn,RayMick/scikit-learn,sarahgrogan/scikit-learn,anntzer/scikit-learn,ky822/scikit-learn,russel1237/scikit-learn,pypot/scikit-learn,RPGOne/scikit-learn,vivekmishra1991/scikit-learn,rahuldhote/scikit-learn,loli/sklearn-ensembletrees,yonglehou/scikit-learn,ZENGXH/scikit-learn,AlexanderFabisch/scikit-learn,mjudsp/Tsallis,mattilyra/scikit-learn,rexshihaoren/scikit-learn,rahuldhote/scikit-learn,zuku1985/scikit-learn,CforED/Machine-Learning,RayMick/scikit-learn,wanggang3333/scikit-learn,eg-zhang/scikit-learn,lesteve/scikit-learn,kaichogami/scikit-learn,ClimbsRocks/scikit-learn,AlexanderFabisch/scikit-learn,AnasGhrab/scikit-learn,quheng/scikit-learn,joernhees/scikit-learn,mhue/scikit-learn,zihua/scikit-learn,dingocuster/scikit-learn,dsullivan7/scikit-learn,pypot/scikit-learn,yask123/scikit-learn,mattilyra/scikit-learn,Windy-Ground/scikit-learn,bhargav/scikit-learn,nmayorov/scikit-learn,jblackburne/scikit-learn,sgenoud/scikit-learn,mblondel/scikit-learn,themrmax/scikit-learn,vermouthmjl/scikit-learn,Myasuka/scikit-learn,treycausey/scikit-learn,schets/scikit-learn,cauchycui/scikit-learn,lazywei/scikit-learn,hlin117/scikit-learn,RomainBrault/scikit-learn,huzq/scikit-learn,cainiaocome/scikit-learn,eg-zhang/scikit-learn,olologin/scikit-learn,sarahgrogan/scikit-learn,evgchz/scikit-learn,alexsavio/scikit-learn,IndraVikas/scikit-learn,jseabold/scikit-learn,sinhrks/scikit-learn,RPGOne/scikit-learn,chrisburr/scikit-learn,mjgrav2001/scikit-learn,CforED/Machine-Learning,rohanp/scikit-learn,carrillo/scikit-learn,Garrett-R/scikit-learn,henrykironde/scikit-learn,betatim/scikit-learn,loli/sklearn-ensembletrees,tdhopper/scikit-learn,IndraVikas/scikit-learn,belltailjp/scikit-learn,jereze/scikit-learn,rohanp/scikit-learn,nmayorov/scikit-learn,rahuldhote/scikit-learn,Obus/scikit-learn,liberatorqjw/scikit-learn,sergeyf/scikit-learn,Fireblend/scikit-learn,xubenben/scikit-learn,UNR-AERIAL/scikit-learn,jjx02230808/project0223,untom/scikit-learn,nhejazi/scikit-learn,davidgbe/scikit-learn,Djabbz/scikit-learn,CVML/scikit-learn,fabianp/scikit-learn,mwv/scikit-learn,glemaitre/scikit-learn,jorik041/scikit-learn,xiaoxiamii/scikit-learn,loli/semisupervisedforests,Myasuka/scikit-learn,hainm/scikit-learn,ominux/scikit-learn,ssaeger/scikit-learn,AlexandreAbraham/scikit-learn,adamgreenhall/scikit-learn,ElDeveloper/scikit-learn,potash/scikit-learn,macks22/scikit-learn,TomDLT/scikit-learn,xavierwu/scikit-learn,dsquareindia/scikit-learn,466152112/scikit-learn,khkaminska/scikit-learn,carrillo/scikit-learn,LiaoPan/scikit-learn,bnaul/scikit-learn,russel1237/scikit-learn,imaculate/scikit-learn,xubenben/scikit-learn,jorge2703/scikit-learn,alexsavio/scikit-learn,manhhomienbienthuy/scikit-learn,giorgiop/scikit-learn,idlead/scikit-learn,lenovor/scikit-learn,altairpearl/scikit-learn,zorojean/scikit-learn,JsNoNo/scikit-learn,UNR-AERIAL/scikit-learn,HolgerPeters/scikit-learn,arahuja/scikit-learn,zhenv5/scikit-learn,cl4rke/scikit-learn,nvoron23/scikit-learn,iismd17/scikit-learn,rvraghav93/scikit-learn,mjgrav2001/scikit-learn,loli/semisupervisedforests,tosolveit/scikit-learn,djgagne/scikit-learn,ashhher3/scikit-learn,lesteve/scikit-learn,466152112/scikit-learn,mxjl620/scikit-learn,procoder317/scikit-learn,luo66/scikit-learn,hrjn/scikit-learn,NelisVerhoef/scikit-learn,saiwing-yeung/scikit-learn,pv/scikit-learn,DSLituiev/scikit-learn,robin-lai/scikit-learn,ClimbsRocks/scikit-learn,wanggang3333/scikit-learn,kashif/scikit-learn,deepesch/scikit-learn,olologin/scikit-learn,trankmichael/scikit-learn,russel1237/scikit-learn,trungnt13/scikit-learn,kagayakidan/scikit-learn,TomDLT/scikit-learn,olologin/scikit-learn,huzq/scikit-learn,shyamalschandra/scikit-learn,ChanChiChoi/scikit-learn,CforED/Machine-Learning,ycaihua/scikit-learn,HolgerPeters/scikit-learn,fyffyt/scikit-learn,mhdella/scikit-learn,imaculate/scikit-learn,bhargav/scikit-learn,sinhrks/scikit-learn,nelson-liu/scikit-learn,MartinSavc/scikit-learn,rahul-c1/scikit-learn,r-mart/scikit-learn,frank-tancf/scikit-learn,Nyker510/scikit-learn,ChanderG/scikit-learn,hlin117/scikit-learn,jblackburne/scikit-learn,zorojean/scikit-learn,iismd17/scikit-learn,0asa/scikit-learn,mjgrav2001/scikit-learn,pratapvardhan/scikit-learn,schets/scikit-learn,MechCoder/scikit-learn,RomainBrault/scikit-learn,florian-f/sklearn,pianomania/scikit-learn,abhishekgahlot/scikit-learn,zaxtax/scikit-learn,trungnt13/scikit-learn,altairpearl/scikit-learn,TomDLT/scikit-learn,ilyes14/scikit-learn,shyamalschandra/scikit-learn,Lawrence-Liu/scikit-learn,elkingtonmcb/scikit-learn,hrjn/scikit-learn,abimannans/scikit-learn,chrsrds/scikit-learn,mhue/scikit-learn,vermouthmjl/scikit-learn,mugizico/scikit-learn,rahuldhote/scikit-learn,ElDeveloper/scikit-learn,jorik041/scikit-learn,vinayak-mehta/scikit-learn,jkarnows/scikit-learn,LohithBlaze/scikit-learn,shyamalschandra/scikit-learn,joshloyal/scikit-learn,kmike/scikit-learn,rrohan/scikit-learn,ltiao/scikit-learn,f3r/scikit-learn,joernhees/scikit-learn,ankurankan/scikit-learn,Titan-C/scikit-learn,andaag/scikit-learn,yyjiang/scikit-learn,poryfly/scikit-learn,jayflo/scikit-learn,fzalkow/scikit-learn,lazywei/scikit-learn,spallavolu/scikit-learn,IshankGulati/scikit-learn,ogrisel/scikit-learn,saiwing-yeung/scikit-learn,ZenDevelopmentSystems/scikit-learn,jaidevd/scikit-learn,joernhees/scikit-learn,vshtanko/scikit-learn,Obus/scikit-learn,anurag313/scikit-learn,Djabbz/scikit-learn,kashif/scikit-learn,aewhatley/scikit-learn,terkkila/scikit-learn,Clyde-fare/scikit-learn,gotomypc/scikit-learn,bhargav/scikit-learn,ChanChiChoi/scikit-learn,eickenberg/scikit-learn,maheshakya/scikit-learn,glennq/scikit-learn,liangz0707/scikit-learn,walterreade/scikit-learn,marcocaccin/scikit-learn,liberatorqjw/scikit-learn,marcocaccin/scikit-learn,rrohan/scikit-learn,mugizico/scikit-learn,tomlof/scikit-learn,jmetzen/scikit-learn,gotomypc/scikit-learn,waterponey/scikit-learn,vybstat/scikit-learn,0x0all/scikit-learn,AIML/scikit-learn,stylianos-kampakis/scikit-learn,frank-tancf/scikit-learn,robbymeals/scikit-learn,harshaneelhg/scikit-learn,RayMick/scikit-learn,aflaxman/scikit-learn,xuewei4d/scikit-learn,hugobowne/scikit-learn,murali-munna/scikit-learn,Lawrence-Liu/scikit-learn,Sentient07/scikit-learn,kevin-intel/scikit-learn,YinongLong/scikit-learn,espg/scikit-learn,0asa/scikit-learn,mrshu/scikit-learn,IssamLaradji/scikit-learn,JsNoNo/scikit-learn,aewhatley/scikit-learn,rahul-c1/scikit-learn,arahuja/scikit-learn,alvarofierroclavero/scikit-learn,aflaxman/scikit-learn,lucidfrontier45/scikit-learn,yyjiang/scikit-learn,clemkoa/scikit-learn,plissonf/scikit-learn,zaxtax/scikit-learn,yask123/scikit-learn,bigdataelephants/scikit-learn,kjung/scikit-learn,gotomypc/scikit-learn,ChanChiChoi/scikit-learn,h2educ/scikit-learn,ningchi/scikit-learn,Aasmi/scikit-learn,fengzhyuan/scikit-learn,larsmans/scikit-learn,pkruskal/scikit-learn,BiaDarkia/scikit-learn,vigilv/scikit-learn,harshaneelhg/scikit-learn,ilo10/scikit-learn,OshynSong/scikit-learn,RayMick/scikit-learn,quheng/scikit-learn,anntzer/scikit-learn,liangz0707/scikit-learn,UNR-AERIAL/scikit-learn,liberatorqjw/scikit-learn,lbishal/scikit-learn,kylerbrown/scikit-learn,justincassidy/scikit-learn,macks22/scikit-learn,djgagne/scikit-learn,khkaminska/scikit-learn,hugobowne/scikit-learn,ishanic/scikit-learn,JeanKossaifi/scikit-learn,Lawrence-Liu/scikit-learn,eickenberg/scikit-learn,ltiao/scikit-learn,kjung/scikit-learn,mattgiguere/scikit-learn,tosolveit/scikit-learn,hlin117/scikit-learn,victorbergelin/scikit-learn,eickenberg/scikit-learn,OshynSong/scikit-learn,carrillo/scikit-learn,toastedcornflakes/scikit-learn,tmhm/scikit-learn,arabenjamin/scikit-learn,jpautom/scikit-learn,aminert/scikit-learn,nhejazi/scikit-learn,nesterione/scikit-learn,adamgreenhall/scikit-learn,sonnyhu/scikit-learn,deepesch/scikit-learn,abhishekkrthakur/scikit-learn,bthirion/scikit-learn,Jimmy-Morzaria/scikit-learn,mblondel/scikit-learn,sergeyf/scikit-learn,MartinSavc/scikit-learn,mlyundin/scikit-learn,rishikksh20/scikit-learn,Jimmy-Morzaria/scikit-learn,Titan-C/scikit-learn,kashif/scikit-learn,kaichogami/scikit-learn,ishanic/scikit-learn,JosmanPS/scikit-learn,JeanKossaifi/scikit-learn,anirudhjayaraman/scikit-learn,vortex-ape/scikit-learn,herilalaina/scikit-learn,sonnyhu/scikit-learn,kmike/scikit-learn,icdishb/scikit-learn,AlexRobson/scikit-learn,raghavrv/scikit-learn,jmschrei/scikit-learn,cainiaocome/scikit-learn,thilbern/scikit-learn,betatim/scikit-learn,AlexRobson/scikit-learn,zihua/scikit-learn,nomadcube/scikit-learn,q1ang/scikit-learn,fbagirov/scikit-learn,DonBeo/scikit-learn,Vimos/scikit-learn,chrsrds/scikit-learn,DonBeo/scikit-learn,alexeyum/scikit-learn,cybernet14/scikit-learn,fabioticconi/scikit-learn,rsivapr/scikit-learn,anntzer/scikit-learn,abhishekkrthakur/scikit-learn,LiaoPan/scikit-learn,mikebenfield/scikit-learn,jmschrei/scikit-learn,CVML/scikit-learn,rajat1994/scikit-learn,fabianp/scikit-learn,zihua/scikit-learn,xyguo/scikit-learn,sgenoud/scikit-learn,pypot/scikit-learn,btabibian/scikit-learn,xiaoxiamii/scikit-learn,sanketloke/scikit-learn,hsiaoyi0504/scikit-learn,abhishekgahlot/scikit-learn,madjelan/scikit-learn,arahuja/scikit-learn,ashhher3/scikit-learn,yunfeilu/scikit-learn,bigdataelephants/scikit-learn,hrjn/scikit-learn,krez13/scikit-learn,jblackburne/scikit-learn,pkruskal/scikit-learn,sumspr/scikit-learn,mxjl620/scikit-learn,depet/scikit-learn,lbishal/scikit-learn,pythonvietnam/scikit-learn,Adai0808/scikit-learn,yunfeilu/scikit-learn,roxyboy/scikit-learn,MechCoder/scikit-learn,jmschrei/scikit-learn,samuel1208/scikit-learn,sgenoud/scikit-learn,nikitasingh981/scikit-learn,glennq/scikit-learn,abimannans/scikit-learn,shahankhatch/scikit-learn,kylerbrown/scikit-learn,cauchycui/scikit-learn,JeanKossaifi/scikit-learn,loli/sklearn-ensembletrees,ElDeveloper/scikit-learn,loli/semisupervisedforests,shikhardb/scikit-learn,mhue/scikit-learn,xyguo/scikit-learn,xwolf12/scikit-learn,abhishekgahlot/scikit-learn,lesteve/scikit-learn,fabianp/scikit-learn,costypetrisor/scikit-learn,lazywei/scikit-learn,jakirkham/scikit-learn,samzhang111/scikit-learn,DSLituiev/scikit-learn,vermouthmjl/scikit-learn,lazywei/scikit-learn,MohammedWasim/scikit-learn,wazeerzulfikar/scikit-learn,hsiaoyi0504/scikit-learn,kylerbrown/scikit-learn,nhejazi/scikit-learn,simon-pepin/scikit-learn,mikebenfield/scikit-learn,scikit-learn/scikit-learn,loli/sklearn-ensembletrees,Vimos/scikit-learn,abhishekgahlot/scikit-learn,zhenv5/scikit-learn,pianomania/scikit-learn,shenzebang/scikit-learn,jzt5132/scikit-learn,andrewnc/scikit-learn,OshynSong/scikit-learn,xiaoxiamii/scikit-learn,treycausey/scikit-learn,nelson-liu/scikit-learn,DSLituiev/scikit-learn,manashmndl/scikit-learn,kmike/scikit-learn,tdhopper/scikit-learn,Clyde-fare/scikit-learn,sanketloke/scikit-learn,murali-munna/scikit-learn,mjudsp/Tsallis,jakirkham/scikit-learn,dingocuster/scikit-learn,ivannz/scikit-learn,fredhusser/scikit-learn,ycaihua/scikit-learn,siutanwong/scikit-learn,pratapvardhan/scikit-learn,vivekmishra1991/scikit-learn,kmike/scikit-learn,dsquareindia/scikit-learn,adamgreenhall/scikit-learn,larsmans/scikit-learn,xzh86/scikit-learn,akionakamura/scikit-learn,aminert/scikit-learn,3manuek/scikit-learn,MartinDelzant/scikit-learn,nhejazi/scikit-learn,xzh86/scikit-learn,henridwyer/scikit-learn,RachitKansal/scikit-learn,mattgiguere/scikit-learn,potash/scikit-learn,AnasGhrab/scikit-learn,cwu2011/scikit-learn,treycausey/scikit-learn,aewhatley/scikit-learn,cauchycui/scikit-learn,betatim/scikit-learn,PatrickChrist/scikit-learn,andaag/scikit-learn,BiaDarkia/scikit-learn,eickenberg/scikit-learn,sergeyf/scikit-learn,bigdataelephants/scikit-learn,theoryno3/scikit-learn,nesterione/scikit-learn,appapantula/scikit-learn,mehdidc/scikit-learn,Achuth17/scikit-learn,ZenDevelopmentSystems/scikit-learn,r-mart/scikit-learn,giorgiop/scikit-learn,victorbergelin/scikit-learn,lucidfrontier45/scikit-learn,thientu/scikit-learn,yanlend/scikit-learn,michigraber/scikit-learn,jorge2703/scikit-learn,scikit-learn/scikit-learn,maheshakya/scikit-learn,dhruv13J/scikit-learn,moutai/scikit-learn,meduz/scikit-learn,lesteve/scikit-learn,espg/scikit-learn,eg-zhang/scikit-learn,mugizico/scikit-learn,jereze/scikit-learn,PatrickChrist/scikit-learn,mfjb/scikit-learn,nelson-liu/scikit-learn,CVML/scikit-learn,JsNoNo/scikit-learn,arabenjamin/scikit-learn,abhishekkrthakur/scikit-learn,MartinDelzant/scikit-learn,shikhardb/scikit-learn,harshaneelhg/scikit-learn,hsuantien/scikit-learn,ldirer/scikit-learn,ndingwall/scikit-learn,Myasuka/scikit-learn,Adai0808/scikit-learn,themrmax/scikit-learn,jkarnows/scikit-learn,ivannz/scikit-learn,ilyes14/scikit-learn,fengzhyuan/scikit-learn,huzq/scikit-learn,rohanp/scikit-learn,pianomania/scikit-learn,toastedcornflakes/scikit-learn,xwolf12/scikit-learn,moutai/scikit-learn,billy-inn/scikit-learn,potash/scikit-learn,ldirer/scikit-learn,ahoyosid/scikit-learn,PatrickOReilly/scikit-learn,xuewei4d/scikit-learn,robin-lai/scikit-learn,alexsavio/scikit-learn,fengzhyuan/scikit-learn,PrashntS/scikit-learn,ephes/scikit-learn,henrykironde/scikit-learn,zorroblue/scikit-learn,dsullivan7/scikit-learn,gclenaghan/scikit-learn,toastedcornflakes/scikit-learn,rexshihaoren/scikit-learn,gclenaghan/scikit-learn,NelisVerhoef/scikit-learn,kaichogami/scikit-learn,sanketloke/scikit-learn,khkaminska/scikit-learn,ChanChiChoi/scikit-learn,jpautom/scikit-learn,pompiduskus/scikit-learn,jzt5132/scikit-learn,mayblue9/scikit-learn,deepesch/scikit-learn,0x0all/scikit-learn,tmhm/scikit-learn,tawsifkhan/scikit-learn,Fireblend/scikit-learn,0asa/scikit-learn,PrashntS/scikit-learn,poryfly/scikit-learn,Windy-Ground/scikit-learn,MartinDelzant/scikit-learn,ngoix/OCRF,jzt5132/scikit-learn,vybstat/scikit-learn,rvraghav93/scikit-learn,yask123/scikit-learn,cdegroc/scikit-learn,UNR-AERIAL/scikit-learn,ClimbsRocks/scikit-learn,joernhees/scikit-learn,lin-credible/scikit-learn,ilo10/scikit-learn,B3AU/waveTree
|
python
|
## Code Before:
from info import __doc__
from gauss_mix import GmParamError, GM
from gmm_em import GmmParamError, GMM, EM
from online_em import OnGMM as _OnGMM
__all__ = filter(lambda s:not s.startswith('_'), dir())
from numpy.testing import NumpyTest
test = NumpyTest().test
def test_suite(*args):
# XXX: this is to avoid recursive call to itself. This is an horrible hack,
# I have no idea why infinite recursion happens otherwise.
if len(args) > 0:
import unittest
return unittest.TestSuite()
np = NumpyTest()
np.testfile_patterns.append(r'test_examples.py')
return np.test(level = -10, verbosity = 5)
## Instruction:
Remove deprecated test runned for em machine.
From: cdavid <cdavid@cb17146a-f446-4be1-a4f7-bd7c5bb65646>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@271 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8
## Code After:
from info import __doc__
from gauss_mix import GmParamError, GM
from gmm_em import GmmParamError, GMM, EM
from online_em import OnGMM as _OnGMM
__all__ = filter(lambda s:not s.startswith('_'), dir())
|
...
from online_em import OnGMM as _OnGMM
__all__ = filter(lambda s:not s.startswith('_'), dir())
...
|
70c98a42326471d3ed615def61954905673c5972
|
typhon/nonlte/__init__.py
|
typhon/nonlte/__init__.py
|
from .version import __version__
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
|
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
|
Remove import of removed version module.
|
Remove import of removed version module.
|
Python
|
mit
|
atmtools/typhon,atmtools/typhon
|
python
|
## Code Before:
from .version import __version__
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
## Instruction:
Remove import of removed version module.
## Code After:
try:
__ATRASU_SETUP__
except:
__ATRASU_SETUP__ = False
if not __ATRASU_SETUP__:
from . import spectra
from . import setup_atmosphere
from . import const
from . import nonltecalc
from . import mathmatics
from . import rtc
|
# ... existing code ...
try:
__ATRASU_SETUP__
# ... rest of the code ...
|
74a3fe9d83c3ccf2f6972277df3a34c47bc06c26
|
slave/skia_slave_scripts/run_gyp.py
|
slave/skia_slave_scripts/run_gyp.py
|
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def _Run(self):
self._flavor_utils.RunGYP()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(RunGYP))
|
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def __init__(self, timeout=15000, no_output_timeout=10000,
**kwargs):
super(RunGYP, self).__init__(timeout=timeout,
no_output_timeout=no_output_timeout,
**kwargs)
def _Run(self):
self._flavor_utils.RunGYP()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(RunGYP))
|
Increase timeout for RunGYP step BUG=skia:1631 (SkipBuildbotRuns)
|
Increase timeout for RunGYP step
BUG=skia:1631
(SkipBuildbotRuns)
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11229 2bbb7eff-a529-9590-31e7-b0007b416f81
|
Python
|
bsd-3-clause
|
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot
|
python
|
## Code Before:
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def _Run(self):
self._flavor_utils.RunGYP()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(RunGYP))
## Instruction:
Increase timeout for RunGYP step
BUG=skia:1631
(SkipBuildbotRuns)
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11229 2bbb7eff-a529-9590-31e7-b0007b416f81
## Code After:
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def __init__(self, timeout=15000, no_output_timeout=10000,
**kwargs):
super(RunGYP, self).__init__(timeout=timeout,
no_output_timeout=no_output_timeout,
**kwargs)
def _Run(self):
self._flavor_utils.RunGYP()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(RunGYP))
|
# ... existing code ...
class RunGYP(BuildStep):
def __init__(self, timeout=15000, no_output_timeout=10000,
**kwargs):
super(RunGYP, self).__init__(timeout=timeout,
no_output_timeout=no_output_timeout,
**kwargs)
def _Run(self):
self._flavor_utils.RunGYP()
# ... rest of the code ...
|
ecce58e936dcac7c92d79c76ecc9729b9475bb0e
|
src/main/java/name/snavrotskiy/ant/listener/NotificationParams.java
|
src/main/java/name/snavrotskiy/ant/listener/NotificationParams.java
|
package name.snavrotskiy.ant.listener;
import com.google.common.base.Preconditions;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
* <p>
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
Preconditions.checkNotNull(trayIcon);
Preconditions.checkNotNull(notificationTitle);
Preconditions.checkNotNull(notificationMessage);
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
@Override
public String toString() {
return "NotificationParams{"
+ "icon=" + icon
+ ", title='" + title + '\''
+ ", message='" + message + '\''
+ '}';
}
}
|
package name.snavrotskiy.ant.listener;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
* <p>
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
}
|
Remove null checks for notification params
|
Remove null checks for notification params
|
Java
|
apache-2.0
|
snavrotskii/ant-native-notifier
|
java
|
## Code Before:
package name.snavrotskiy.ant.listener;
import com.google.common.base.Preconditions;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
* <p>
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
Preconditions.checkNotNull(trayIcon);
Preconditions.checkNotNull(notificationTitle);
Preconditions.checkNotNull(notificationMessage);
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
@Override
public String toString() {
return "NotificationParams{"
+ "icon=" + icon
+ ", title='" + title + '\''
+ ", message='" + message + '\''
+ '}';
}
}
## Instruction:
Remove null checks for notification params
## Code After:
package name.snavrotskiy.ant.listener;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
* <p>
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
}
|
...
package name.snavrotskiy.ant.listener;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
...
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
...
String getMessage() {
return message;
}
}
...
|
43b46f1e3ded3972dede7226cf0255b904d028bd
|
django/notejam/pads/tests.py
|
django/notejam/pads/tests.py
|
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
|
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
class PadTest(TestCase):
def setUp(self):
user_data = {
'email': '[email protected]',
'password': 'secure_password'
}
user = User.objects.create(username=user_data['email'], **user_data)
user.set_password(user_data['password'])
user.save()
self.client.login(**user_data)
def _get_pad_data(self):
pass
def test_create_pad_success(self):
pass
|
Test improvementes. Empty Pad test class added.
|
Django: Test improvementes. Empty Pad test class added.
|
Python
|
mit
|
hstaugaard/notejam,nadavge/notejam,lefloh/notejam,lefloh/notejam,williamn/notejam,hstaugaard/notejam,nadavge/notejam,williamn/notejam,hstaugaard/notejam,hstaugaard/notejam,lefloh/notejam,lefloh/notejam,williamn/notejam,nadavge/notejam,lefloh/notejam,hstaugaard/notejam,williamn/notejam,shikhardb/notejam,williamn/notejam,williamn/notejam,hstaugaard/notejam,shikhardb/notejam,lefloh/notejam,hstaugaard/notejam,lefloh/notejam,williamn/notejam,shikhardb/notejam,shikhardb/notejam,nadavge/notejam,hstaugaard/notejam,nadavge/notejam,shikhardb/notejam
|
python
|
## Code Before:
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
## Instruction:
Django: Test improvementes. Empty Pad test class added.
## Code After:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
class PadTest(TestCase):
def setUp(self):
user_data = {
'email': '[email protected]',
'password': 'secure_password'
}
user = User.objects.create(username=user_data['email'], **user_data)
user.set_password(user_data['password'])
user.save()
self.client.login(**user_data)
def _get_pad_data(self):
pass
def test_create_pad_success(self):
pass
|
# ... existing code ...
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
class PadTest(TestCase):
def setUp(self):
user_data = {
'email': '[email protected]',
'password': 'secure_password'
}
user = User.objects.create(username=user_data['email'], **user_data)
user.set_password(user_data['password'])
user.save()
self.client.login(**user_data)
def _get_pad_data(self):
pass
def test_create_pad_success(self):
pass
# ... rest of the code ...
|
e6af345239f2778a2245d9f8be54bf754224aafd
|
tests/helper.py
|
tests/helper.py
|
def mock_api(path, file_path):
from httmock import urlmatch, response
@urlmatch(scheme = 'https', netloc = 'api.webpay.jp', path = '/v1' + path)
def webpay_api_mock(url, request):
from os import path
import codecs
dump = path.dirname(path.abspath(__file__)) + '/mock/' + file_path
file = codecs.open(dump, 'r', 'utf-8')
lines = file.readlines()
file.close
status = 0
headers = {}
body = ''
body_started = False
for i in range(len(lines)):
line = lines[i]
if i == 0:
status = int(line.split(' ')[1])
elif body_started:
body += line
elif (line.strip() == ''):
body_started = True
else:
key, value = line.split(':', 1)
headers[key] = value.strip()
return response(status, content = body.encode('utf-8'), headers = headers, request = request)
return webpay_api_mock
|
def mock_api(path, file_path, query = None, data = None):
from httmock import urlmatch, response
import json
@urlmatch(scheme = 'https', netloc = 'api.webpay.jp', path = '/v1' + path)
def webpay_api_mock(url, request):
assert query is None or url.query == query
assert data is None or json.loads(request.body) == data
from os import path
import codecs
dump = path.dirname(path.abspath(__file__)) + '/mock/' + file_path
file = codecs.open(dump, 'r', 'utf-8')
lines = file.readlines()
file.close
status = 0
headers = {}
body = ''
body_started = False
for i in range(len(lines)):
line = lines[i]
if i == 0:
status = int(line.split(' ')[1])
elif body_started:
body += line
elif (line.strip() == ''):
body_started = True
else:
key, value = line.split(':', 1)
headers[key] = value.strip()
return response(status, content = body.encode('utf-8'), headers = headers, request = request)
return webpay_api_mock
|
Add assertion for query and data of request
|
Add assertion for query and data of request
|
Python
|
mit
|
yamaneko1212/webpay-python
|
python
|
## Code Before:
def mock_api(path, file_path):
from httmock import urlmatch, response
@urlmatch(scheme = 'https', netloc = 'api.webpay.jp', path = '/v1' + path)
def webpay_api_mock(url, request):
from os import path
import codecs
dump = path.dirname(path.abspath(__file__)) + '/mock/' + file_path
file = codecs.open(dump, 'r', 'utf-8')
lines = file.readlines()
file.close
status = 0
headers = {}
body = ''
body_started = False
for i in range(len(lines)):
line = lines[i]
if i == 0:
status = int(line.split(' ')[1])
elif body_started:
body += line
elif (line.strip() == ''):
body_started = True
else:
key, value = line.split(':', 1)
headers[key] = value.strip()
return response(status, content = body.encode('utf-8'), headers = headers, request = request)
return webpay_api_mock
## Instruction:
Add assertion for query and data of request
## Code After:
def mock_api(path, file_path, query = None, data = None):
from httmock import urlmatch, response
import json
@urlmatch(scheme = 'https', netloc = 'api.webpay.jp', path = '/v1' + path)
def webpay_api_mock(url, request):
assert query is None or url.query == query
assert data is None or json.loads(request.body) == data
from os import path
import codecs
dump = path.dirname(path.abspath(__file__)) + '/mock/' + file_path
file = codecs.open(dump, 'r', 'utf-8')
lines = file.readlines()
file.close
status = 0
headers = {}
body = ''
body_started = False
for i in range(len(lines)):
line = lines[i]
if i == 0:
status = int(line.split(' ')[1])
elif body_started:
body += line
elif (line.strip() == ''):
body_started = True
else:
key, value = line.split(':', 1)
headers[key] = value.strip()
return response(status, content = body.encode('utf-8'), headers = headers, request = request)
return webpay_api_mock
|
# ... existing code ...
def mock_api(path, file_path, query = None, data = None):
from httmock import urlmatch, response
import json
@urlmatch(scheme = 'https', netloc = 'api.webpay.jp', path = '/v1' + path)
def webpay_api_mock(url, request):
assert query is None or url.query == query
assert data is None or json.loads(request.body) == data
from os import path
import codecs
dump = path.dirname(path.abspath(__file__)) + '/mock/' + file_path
# ... rest of the code ...
|
2ca316e90993e830fcc7cd1337b86766371bfb4c
|
Client/Client-UI/src/main/java/net/sourceforge/javydreamercsw/client/ui/nodes/actions/CreateTestAction.java
|
Client/Client-UI/src/main/java/net/sourceforge/javydreamercsw/client/ui/nodes/actions/CreateTestAction.java
|
package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
|
package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.db.TestPlan;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import org.openide.util.Utilities;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setTestPlan(Utilities.actionsGlobalContext().lookup(TestPlan.class));
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
|
Fix NPE while creating tests.
|
Fix NPE while creating tests.
|
Java
|
apache-2.0
|
javydreamercsw/validation-manager
|
java
|
## Code Before:
package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
## Instruction:
Fix NPE while creating tests.
## Code After:
package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.db.TestPlan;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import org.openide.util.Utilities;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class CreateTestAction extends AbstractAction {
public CreateTestAction() {
super("Create Test",
new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setTestPlan(Utilities.actionsGlobalContext().lookup(TestPlan.class));
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
});
}
}
|
// ... existing code ...
package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.db.TestPlan;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import org.openide.util.Utilities;
/**
*
// ... modified code ...
public void run() {
final CreateTestDialog dialog =
new CreateTestDialog(new javax.swing.JFrame(), true);
dialog.setTestPlan(Utilities.actionsGlobalContext().lookup(TestPlan.class));
dialog.setLocationRelativeTo(null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
// ... rest of the code ...
|
9cb05046c66f39575e1d38542a5dcf656209840a
|
src/main/java/org/hummingbirdlang/types/concrete/IntegerType.java
|
src/main/java/org/hummingbirdlang/types/concrete/IntegerType.java
|
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
}
|
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
@Override
public String toString() {
return "$Integer";
}
}
|
Add debug string representation of integer concrete type
|
Add debug string representation of integer concrete type
|
Java
|
bsd-3-clause
|
dirk/hummingbird2,dirk/hummingbird2,dirk/hummingbird2
|
java
|
## Code Before:
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
}
## Instruction:
Add debug string representation of integer concrete type
## Code After:
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
@Override
public String toString() {
return "$Integer";
}
}
|
...
throw new PropertyNotFoundException(this, name);
}
}
@Override
public String toString() {
return "$Integer";
}
}
...
|
5638aca636be4449ee3f7f358c334058e7837cd7
|
OpERP/src/main/java/devopsdistilled/operp/server/data/service/account/impl/TransactionServiceImpl.java
|
OpERP/src/main/java/devopsdistilled/operp/server/data/service/account/impl/TransactionServiceImpl.java
|
package devopsdistilled.operp.server.data.service.account.impl;
import org.springframework.data.jpa.repository.JpaRepository;
import devopsdistilled.operp.server.data.entity.account.Transaction;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
public abstract class TransactionServiceImpl<T extends Transaction<?>, TR extends JpaRepository<T, Long>>
extends AbstractEntityService<T, Long, TR> {
private static final long serialVersionUID = -4898201898165854461L;
@Override
protected T findByEntityName(String entityName) {
return null;
}
}
|
package devopsdistilled.operp.server.data.service.account.impl;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
import devopsdistilled.operp.server.data.entity.account.Transaction;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
public abstract class TransactionServiceImpl<T extends Transaction<?>, TR extends JpaRepository<T, Long>>
extends AbstractEntityService<T, Long, TR> {
private static final long serialVersionUID = -4898201898165854461L;
@Override
protected T findByEntityName(String entityName) {
return null;
}
@Override
public <S extends T> S save(S transaction) {
transaction.setTransactionDate(new Date());
return super.save(transaction);
}
}
|
Set Date when persisting Transaction
|
Set Date when persisting Transaction
|
Java
|
mit
|
DevOpsDistilled/OpERP,njmube/OpERP
|
java
|
## Code Before:
package devopsdistilled.operp.server.data.service.account.impl;
import org.springframework.data.jpa.repository.JpaRepository;
import devopsdistilled.operp.server.data.entity.account.Transaction;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
public abstract class TransactionServiceImpl<T extends Transaction<?>, TR extends JpaRepository<T, Long>>
extends AbstractEntityService<T, Long, TR> {
private static final long serialVersionUID = -4898201898165854461L;
@Override
protected T findByEntityName(String entityName) {
return null;
}
}
## Instruction:
Set Date when persisting Transaction
## Code After:
package devopsdistilled.operp.server.data.service.account.impl;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
import devopsdistilled.operp.server.data.entity.account.Transaction;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
public abstract class TransactionServiceImpl<T extends Transaction<?>, TR extends JpaRepository<T, Long>>
extends AbstractEntityService<T, Long, TR> {
private static final long serialVersionUID = -4898201898165854461L;
@Override
protected T findByEntityName(String entityName) {
return null;
}
@Override
public <S extends T> S save(S transaction) {
transaction.setTransactionDate(new Date());
return super.save(transaction);
}
}
|
// ... existing code ...
package devopsdistilled.operp.server.data.service.account.impl;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
// ... modified code ...
return null;
}
@Override
public <S extends T> S save(S transaction) {
transaction.setTransactionDate(new Date());
return super.save(transaction);
}
}
// ... rest of the code ...
|
89d6c81529d1f0f467a098934a670c57e463188f
|
cmcb/reddit.py
|
cmcb/reddit.py
|
import asyncio
import functools
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password, loop=None):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
async def get_top_level_comments(self, submission_id):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(
None, functools.partioal(submission.comments.replace_more, limit=None))
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(submission.edit, updated_text)
|
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
async def get_top_level_comments(self, submission_id):
submission = self._reddit.submission(id=submission_id)
submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = self._reddit.submission(id=submission_id)
submission.edit(updated_text)
|
Revert Reddit api to its synchonous state
|
Revert Reddit api to its synchonous state
|
Python
|
mit
|
festinuz/cmcb,festinuz/cmcb
|
python
|
## Code Before:
import asyncio
import functools
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password, loop=None):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
async def get_top_level_comments(self, submission_id):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(
None, functools.partioal(submission.comments.replace_more, limit=None))
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(submission.edit, updated_text)
## Instruction:
Revert Reddit api to its synchonous state
## Code After:
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
async def get_top_level_comments(self, submission_id):
submission = self._reddit.submission(id=submission_id)
submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = self._reddit.submission(id=submission_id)
submission.edit(updated_text)
|
// ... existing code ...
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
async def get_top_level_comments(self, submission_id):
submission = self._reddit.submission(id=submission_id)
submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = self._reddit.submission(id=submission_id)
submission.edit(updated_text)
// ... rest of the code ...
|
048f2d9469b3f9eb266a343602ddf608e3bd6d86
|
highton/models/email_address.py
|
highton/models/email_address.py
|
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION)
self.address = fields.StringField(name=HightonConstants.ADDRESS)
super().__init__(**kwargs)
|
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
|
Set EmailAddress Things to required
|
Set EmailAddress Things to required
|
Python
|
apache-2.0
|
seibert-media/Highton,seibert-media/Highton
|
python
|
## Code Before:
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION)
self.address = fields.StringField(name=HightonConstants.ADDRESS)
super().__init__(**kwargs)
## Instruction:
Set EmailAddress Things to required
## Code After:
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
|
...
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
...
|
e48efcf64c3568be32d96c1dc2a139b56206e9a5
|
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/KtFiles.kt
|
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/KtFiles.kt
|
package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile
/**
* @author Artur Bosch
*/
fun KtFile.unnormalizedContent(): String {
val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
return this.text.replace("\n", lineSeparator!!)
}
val KtFile.relativePath: String?
get() = this.getUserData(KtCompiler.RELATIVE_PATH)
|
package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile
/**
* @author Artur Bosch
*/
fun KtFile.unnormalizedContent(): String {
val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
return StringUtilRt.convertLineSeparators("\n", lineSeparator!!)
}
val KtFile.relativePath: String?
get() = this.getUserData(KtCompiler.RELATIVE_PATH)
|
Use idea intern line separator replacement
|
Use idea intern line separator replacement
|
Kotlin
|
apache-2.0
|
arturbosch/detekt,arturbosch/detekt,Mauin/detekt,rock3r/detekt,Mauin/detekt,arturbosch/detekt,MyDogTom/detekt,rock3r/detekt,Mauin/detekt,Mauin/detekt,rock3r/detekt
|
kotlin
|
## Code Before:
package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile
/**
* @author Artur Bosch
*/
fun KtFile.unnormalizedContent(): String {
val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
return this.text.replace("\n", lineSeparator!!)
}
val KtFile.relativePath: String?
get() = this.getUserData(KtCompiler.RELATIVE_PATH)
## Instruction:
Use idea intern line separator replacement
## Code After:
package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile
/**
* @author Artur Bosch
*/
fun KtFile.unnormalizedContent(): String {
val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
return StringUtilRt.convertLineSeparators("\n", lineSeparator!!)
}
val KtFile.relativePath: String?
get() = this.getUserData(KtCompiler.RELATIVE_PATH)
|
# ... existing code ...
package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile
# ... modified code ...
fun KtFile.unnormalizedContent(): String {
val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
return StringUtilRt.convertLineSeparators("\n", lineSeparator!!)
}
val KtFile.relativePath: String?
# ... rest of the code ...
|
ec6fee9230040d515fd0ee8224023d5a2e7e6bb5
|
src/main/java/techreborn/compat/opencomputers/CompatOpenComputers.java
|
src/main/java/techreborn/compat/opencomputers/CompatOpenComputers.java
|
package techreborn.compat.opencomputers;
import li.cil.oc.api.Driver;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import techreborn.compat.ICompatModule;
public class CompatOpenComputers implements ICompatModule {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
}
@Override
public void postInit(FMLPostInitializationEvent event) {
Driver.add(new DriverMachine());
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
}
}
|
package techreborn.compat.opencomputers;
import li.cil.oc.api.Driver;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import techreborn.compat.ICompatModule;
public class CompatOpenComputers implements ICompatModule {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
Driver.add(new DriverMachine());
}
@Override
public void postInit(FMLPostInitializationEvent event) {
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
}
}
|
Fix crash with OC compat
|
Fix crash with OC compat
|
Java
|
mit
|
Dimmerworld/TechReborn,drcrazy/TechReborn,TechReborn/TechReborn
|
java
|
## Code Before:
package techreborn.compat.opencomputers;
import li.cil.oc.api.Driver;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import techreborn.compat.ICompatModule;
public class CompatOpenComputers implements ICompatModule {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
}
@Override
public void postInit(FMLPostInitializationEvent event) {
Driver.add(new DriverMachine());
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
}
}
## Instruction:
Fix crash with OC compat
## Code After:
package techreborn.compat.opencomputers;
import li.cil.oc.api.Driver;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import techreborn.compat.ICompatModule;
public class CompatOpenComputers implements ICompatModule {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
Driver.add(new DriverMachine());
}
@Override
public void postInit(FMLPostInitializationEvent event) {
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
}
}
|
# ... existing code ...
@Override
public void init(FMLInitializationEvent event) {
Driver.add(new DriverMachine());
}
@Override
public void postInit(FMLPostInitializationEvent event) {
}
@Override
# ... rest of the code ...
|
fe5ddba257885aa166bd71696a6eeefad153e66a
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "[email protected]",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: MIT Licence",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
)
|
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "[email protected]",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
)
|
Switch to OSI license for Pypi
|
Switch to OSI license for Pypi
|
Python
|
mit
|
Deisss/python-sockjsroom,Deisss/python-sockjsroom,Deisss/python-sockjsroom
|
python
|
## Code Before:
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "[email protected]",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: MIT Licence",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
)
## Instruction:
Switch to OSI license for Pypi
## Code After:
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "[email protected]",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
)
|
...
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
...
|
4e5fa71790f7a69bf6bb472ee7ce48f4a801953c
|
test/util.py
|
test/util.py
|
from functools import wraps
from mongoalchemy.session import Session
DB_NAME = 'mongoalchemy-unit-test'
def known_failure(fun):
"""
Wraps a test known to fail without causing an actual test failure.
"""
@wraps(fun)
def wrapper(*args, **kwds):
try:
fun(*args, **kwds)
raise Exception('Known failure passed! %s' % fun.__name__)
except:
pass
return wrapper
def get_session():
"""
Returns the :class:`Session` used for testing.
"""
return Session.connect(DB_NAME)
|
from functools import wraps
from mongoalchemy.session import Session
DB_NAME = 'mongoalchemy-unit-test'
""" Name of the database to use for testing. """
def known_failure(fun):
"""
Wraps a test known to fail without causing an actual test failure.
"""
@wraps(fun)
def wrapper(*args, **kwds):
try:
fun(*args, **kwds)
raise Exception('Known failure passed! %s' % fun.__name__)
except:
pass
return wrapper
def get_session(*args, **kwargs):
"""
Returns the :class:`Session` used for testing.
"""
return Session.connect(DB_NAME, *args, **kwargs)
|
Allow get_session to pass through arguments, like `safe`.
|
Allow get_session to pass through arguments, like `safe`.
|
Python
|
mit
|
shakefu/MongoAlchemy,shakefu/MongoAlchemy,shakefu/MongoAlchemy
|
python
|
## Code Before:
from functools import wraps
from mongoalchemy.session import Session
DB_NAME = 'mongoalchemy-unit-test'
def known_failure(fun):
"""
Wraps a test known to fail without causing an actual test failure.
"""
@wraps(fun)
def wrapper(*args, **kwds):
try:
fun(*args, **kwds)
raise Exception('Known failure passed! %s' % fun.__name__)
except:
pass
return wrapper
def get_session():
"""
Returns the :class:`Session` used for testing.
"""
return Session.connect(DB_NAME)
## Instruction:
Allow get_session to pass through arguments, like `safe`.
## Code After:
from functools import wraps
from mongoalchemy.session import Session
DB_NAME = 'mongoalchemy-unit-test'
""" Name of the database to use for testing. """
def known_failure(fun):
"""
Wraps a test known to fail without causing an actual test failure.
"""
@wraps(fun)
def wrapper(*args, **kwds):
try:
fun(*args, **kwds)
raise Exception('Known failure passed! %s' % fun.__name__)
except:
pass
return wrapper
def get_session(*args, **kwargs):
"""
Returns the :class:`Session` used for testing.
"""
return Session.connect(DB_NAME, *args, **kwargs)
|
# ... existing code ...
DB_NAME = 'mongoalchemy-unit-test'
""" Name of the database to use for testing. """
def known_failure(fun):
# ... modified code ...
return wrapper
def get_session(*args, **kwargs):
"""
Returns the :class:`Session` used for testing.
"""
return Session.connect(DB_NAME, *args, **kwargs)
# ... rest of the code ...
|
b91b0d667f64960fd1f07b7dc42290f287ab4c5b
|
scripts/endpoints_json.py
|
scripts/endpoints_json.py
|
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
def __init__(self):
pass
def find(self):
page = requests.get(self._page)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
from pprint import pprint
pprint(sections)
return sections
if __name__ == "__main__":
json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True)
|
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
def __init__(self):
pass
def find(self):
page = requests.get(self._page, headers=self._headers)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
return sections
if __name__ == "__main__":
print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
|
Add default headers, fix output
|
Add default headers, fix output
|
Python
|
mit
|
thatJavaNerd/JRAW,ccrama/JRAW,fbis251/JRAW,fbis251/JRAW,fbis251/JRAW,thatJavaNerd/JRAW,Saketme/JRAW,hzsweers/JRAW,hzsweers/JRAW,ccrama/JRAW,thatJavaNerd/JRAW,ccrama/JRAW,Saketme/JRAW,hzsweers/JRAW,Saketme/JRAW
|
python
|
## Code Before:
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
def __init__(self):
pass
def find(self):
page = requests.get(self._page)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
from pprint import pprint
pprint(sections)
return sections
if __name__ == "__main__":
json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True)
## Instruction:
Add default headers, fix output
## Code After:
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import json
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
def __init__(self):
pass
def find(self):
page = requests.get(self._page, headers=self._headers)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
exit(1)
tree = lxml.html.fromstring(page.text)
sel = CSSSelector('div[class="toc"] > ul > li > ul > li')
results = sel(tree)
sections = {}
for result in results:
scope = result.find('a').text_content()
if not scope:
scope = self._no_scope
endpointlist = []
endpoints = result.cssselect('li > a')
for endpoint in endpoints[1:]:
descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/')
endpointlist.append(descriptor)
sections[scope] = endpointlist
return sections
if __name__ == "__main__":
print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
|
// ... existing code ...
class EndpointIdentifier:
_page = 'https://www.reddit.com/dev/api/oauth'
_no_scope = '(any scope)'
_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
def __init__(self):
pass
def find(self):
page = requests.get(self._page, headers=self._headers)
if page.status_code != 200:
print("Bad status code:", page.status_code)
from sys import exit
// ... modified code ...
endpointlist.append(descriptor)
sections[scope] = endpointlist
return sections
if __name__ == "__main__":
print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.