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
2281aaa8403743578678dcb313cc05c438e692f5
src/graphics/EvolutionSelector.java
src/graphics/EvolutionSelector.java
package graphics; import javax.swing.*; import java.awt.*; public class EvolutionSelector extends JPanel { private static JFrame frame; //Used to allow JLabel to word-wrap private static final String HTML_Formatting = "<html><body style='width: 100px'>"; public static JCheckBox xEquation = new JCheckBox("x"); public static JCheckBox yEquation = new JCheckBox("y"); public static JCheckBox zEquation = new JCheckBox("z"); public static JCheckBox colorEquation = new JCheckBox("color"); private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:"); public EvolutionSelector(int x, int y) { frame = new JFrame("Evolution Selector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(x, y); frame.setSize(150, 300); frame.setResizable(false); frame.setVisible(true); //Don't let this window take focus away from the GraphicalInterface window frame.setFocusableWindowState(false); frame.getContentPane().setLayout(new GridLayout(5, 2)); //Add the title text to the windows frame.getContentPane().add(title); //Add the evolution selectors frame.getContentPane().add(xEquation); frame.getContentPane().add(yEquation); frame.getContentPane().add(zEquation); frame.getContentPane().add(colorEquation); } }
package graphics; import javax.swing.*; import java.awt.*; public class EvolutionSelector extends JPanel { private static JFrame frame; //Used to allow JLabel to word-wrap private static final String HTML_Formatting = "<html><body style='width: 100px'>"; public static JCheckBox xEquation = new JCheckBox("x"); public static JCheckBox yEquation = new JCheckBox("y"); public static JCheckBox zEquation = new JCheckBox("z"); public static JCheckBox colorEquation = new JCheckBox("color"); private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:"); public EvolutionSelector(int x, int y) { xEquation.setSelected(true); yEquation.setSelected(true); zEquation.setSelected(true); frame = new JFrame("Evolution Selector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(x, y); frame.setSize(150, 300); frame.setResizable(false); frame.setVisible(true); //Don't let this window take focus away from the GraphicalInterface window frame.setFocusableWindowState(false); frame.getContentPane().setLayout(new GridLayout(5, 2)); //Add the title text to the windows frame.getContentPane().add(title); //Add the evolution selectors frame.getContentPane().add(xEquation); frame.getContentPane().add(yEquation); frame.getContentPane().add(zEquation); frame.getContentPane().add(colorEquation); } }
Make the X Y and Z checkboxes automatically selected on program start
Make the X Y and Z checkboxes automatically selected on program start
Java
mit
Tyler-Yates/AestheticFractals
java
## Code Before: package graphics; import javax.swing.*; import java.awt.*; public class EvolutionSelector extends JPanel { private static JFrame frame; //Used to allow JLabel to word-wrap private static final String HTML_Formatting = "<html><body style='width: 100px'>"; public static JCheckBox xEquation = new JCheckBox("x"); public static JCheckBox yEquation = new JCheckBox("y"); public static JCheckBox zEquation = new JCheckBox("z"); public static JCheckBox colorEquation = new JCheckBox("color"); private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:"); public EvolutionSelector(int x, int y) { frame = new JFrame("Evolution Selector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(x, y); frame.setSize(150, 300); frame.setResizable(false); frame.setVisible(true); //Don't let this window take focus away from the GraphicalInterface window frame.setFocusableWindowState(false); frame.getContentPane().setLayout(new GridLayout(5, 2)); //Add the title text to the windows frame.getContentPane().add(title); //Add the evolution selectors frame.getContentPane().add(xEquation); frame.getContentPane().add(yEquation); frame.getContentPane().add(zEquation); frame.getContentPane().add(colorEquation); } } ## Instruction: Make the X Y and Z checkboxes automatically selected on program start ## Code After: package graphics; import javax.swing.*; import java.awt.*; public class EvolutionSelector extends JPanel { private static JFrame frame; //Used to allow JLabel to word-wrap private static final String HTML_Formatting = "<html><body style='width: 100px'>"; public static JCheckBox xEquation = new JCheckBox("x"); public static JCheckBox yEquation = new JCheckBox("y"); public static JCheckBox zEquation = new JCheckBox("z"); public static JCheckBox colorEquation = new JCheckBox("color"); private static JLabel title = new JLabel(HTML_Formatting + "Select Equations to Evolve:"); public EvolutionSelector(int x, int y) { xEquation.setSelected(true); yEquation.setSelected(true); zEquation.setSelected(true); frame = new JFrame("Evolution Selector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(x, y); frame.setSize(150, 300); frame.setResizable(false); frame.setVisible(true); //Don't let this window take focus away from the GraphicalInterface window frame.setFocusableWindowState(false); frame.getContentPane().setLayout(new GridLayout(5, 2)); //Add the title text to the windows frame.getContentPane().add(title); //Add the evolution selectors frame.getContentPane().add(xEquation); frame.getContentPane().add(yEquation); frame.getContentPane().add(zEquation); frame.getContentPane().add(colorEquation); } }
... public EvolutionSelector(int x, int y) { xEquation.setSelected(true); yEquation.setSelected(true); zEquation.setSelected(true); frame = new JFrame("Evolution Selector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(x, y); ...
351bc14c66962e5ef386b6d41073697993c95236
greengraph/test/test_map.py
greengraph/test/test_map.py
from greengraph.map import Map import numpy as np from nose.tools import assert_equal import yaml def test_green(): size = (10,10) zoom = 10 lat = 50 lon = 50 satellite = True testMap = Map(lat,lon,satellite,zoom,size) threshold = 1 trueArray = np.ones(size,dtype=bool) falseArray = np.zeros(size,dtype=bool) def assert_images_equal(r,g,b,checkArray): testPixels = np.dstack((r,g,blue)) testMap.pixels = testPixels np.testing.assert_array_equal(testMap.green(threshold),checkArray) green = np.ones(size) red = np.ones(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) blue = np.zeros(size) assert_images_equal(red,green,blue,falseArray) red = np.zeros(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) blue = np.zeros(size) assert_images_equal(red,green,blue,trueArray)
from greengraph.map import Map import numpy as np from nose.tools import assert_equal from mock import patch import os @patch('requests.get') @patch('matplotlib.image.imread') @patch('StringIO.StringIO') def test_green(mock_get,mock_imread,mock_StringIO): def assert_images_equal(r,g,b,checkArray): testMap.pixels = np.dstack((r,g,b)) np.testing.assert_array_equal(testMap.green(threshold),checkArray) lat = 50 lon = 50 testMap = Map(lat,lon) size = (400,400) trueArray = np.ones(size,dtype=bool) falseArray = np.zeros(size,dtype=bool) threshold = 1 #Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels green = np.ones(size) red = np.ones(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels blue = np.zeros(size) assert_images_equal(red,green,blue,falseArray) #As above but with red and blue pixels switched red = np.zeros(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels blue = np.zeros(size) assert_images_equal(red,green,blue,trueArray)
Add patch decorator to test_green() function
Add patch decorator to test_green() function
Python
mit
MikeVasmer/GreenGraphCoursework
python
## Code Before: from greengraph.map import Map import numpy as np from nose.tools import assert_equal import yaml def test_green(): size = (10,10) zoom = 10 lat = 50 lon = 50 satellite = True testMap = Map(lat,lon,satellite,zoom,size) threshold = 1 trueArray = np.ones(size,dtype=bool) falseArray = np.zeros(size,dtype=bool) def assert_images_equal(r,g,b,checkArray): testPixels = np.dstack((r,g,blue)) testMap.pixels = testPixels np.testing.assert_array_equal(testMap.green(threshold),checkArray) green = np.ones(size) red = np.ones(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) blue = np.zeros(size) assert_images_equal(red,green,blue,falseArray) red = np.zeros(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) blue = np.zeros(size) assert_images_equal(red,green,blue,trueArray) ## Instruction: Add patch decorator to test_green() function ## Code After: from greengraph.map import Map import numpy as np from nose.tools import assert_equal from mock import patch import os @patch('requests.get') @patch('matplotlib.image.imread') @patch('StringIO.StringIO') def test_green(mock_get,mock_imread,mock_StringIO): def assert_images_equal(r,g,b,checkArray): testMap.pixels = np.dstack((r,g,b)) np.testing.assert_array_equal(testMap.green(threshold),checkArray) lat = 50 lon = 50 testMap = Map(lat,lon) size = (400,400) trueArray = np.ones(size,dtype=bool) falseArray = np.zeros(size,dtype=bool) threshold = 1 #Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels green = np.ones(size) red = np.ones(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels blue = np.zeros(size) assert_images_equal(red,green,blue,falseArray) #As above but with red and blue pixels switched red = np.zeros(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels blue = np.zeros(size) assert_images_equal(red,green,blue,trueArray)
# ... existing code ... from greengraph.map import Map import numpy as np from nose.tools import assert_equal from mock import patch import os @patch('requests.get') @patch('matplotlib.image.imread') @patch('StringIO.StringIO') def test_green(mock_get,mock_imread,mock_StringIO): def assert_images_equal(r,g,b,checkArray): testMap.pixels = np.dstack((r,g,b)) np.testing.assert_array_equal(testMap.green(threshold),checkArray) lat = 50 lon = 50 testMap = Map(lat,lon) size = (400,400) trueArray = np.ones(size,dtype=bool) falseArray = np.zeros(size,dtype=bool) threshold = 1 #Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels green = np.ones(size) red = np.ones(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels blue = np.zeros(size) assert_images_equal(red,green,blue,falseArray) #As above but with red and blue pixels switched red = np.zeros(size) blue = np.ones(size) assert_images_equal(red,green,blue,falseArray) #Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels blue = np.zeros(size) assert_images_equal(red,green,blue,trueArray) # ... rest of the code ...
051e0d0b7e6c5cff85c2992a0a73955d89a2d392
statefulj-framework/statefulj-framework-core/src/main/java/org/statefulj/framework/core/model/impl/FactoryImpl.java
statefulj-framework/statefulj-framework-core/src/main/java/org/statefulj/framework/core/model/impl/FactoryImpl.java
/*** * * Copyright 2014 Andrew Hall * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.statefulj.framework.core.model.impl; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { T newInstance = null; try { newInstance = clazz.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } return newInstance; } }
/*** * * Copyright 2014 Andrew Hall * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.statefulj.framework.core.model.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { try { Constructor<T> ctr = clazz.getDeclaredConstructor(); ctr.setAccessible(true); return ctr.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor"); } } }
Add in ability to instantiate non public default constructors
Add in ability to instantiate non public default constructors
Java
apache-2.0
statefulj/statefulj
java
## Code Before: /*** * * Copyright 2014 Andrew Hall * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.statefulj.framework.core.model.impl; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { T newInstance = null; try { newInstance = clazz.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } return newInstance; } } ## Instruction: Add in ability to instantiate non public default constructors ## Code After: /*** * * Copyright 2014 Andrew Hall * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.statefulj.framework.core.model.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { try { Constructor<T> ctr = clazz.getDeclaredConstructor(); ctr.setAccessible(true); return ctr.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor"); } } }
// ... existing code ... */ package org.statefulj.framework.core.model.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { // ... modified code ... @Override public T create(Class<T> clazz, String event, CT context) { try { Constructor<T> ctr = clazz.getDeclaredConstructor(); ctr.setAccessible(true); return ctr.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor"); } } } // ... rest of the code ...
edd21fc76068894de1001a163885291c3b2cfadb
tests/factories.py
tests/factories.py
from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select id, username from auth_user"
from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select app, name from django_migrations"
Make default QueryFactory return data (fixes test)
Make default QueryFactory return data (fixes test)
Python
mit
sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz
python
## Code Before: from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select id, username from auth_user" ## Instruction: Make default QueryFactory return data (fixes test) ## Code After: from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select app, name from django_migrations"
# ... existing code ... db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select app, name from django_migrations" # ... rest of the code ...
39045363291cde02ce60284cf092e6061eaecd0e
src/main/java/uk/ac/ebi/biosamples/model/util/ExecutionInfo.java
src/main/java/uk/ac/ebi/biosamples/model/util/ExecutionInfo.java
package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private AtomicInteger submitted; private AtomicInteger completed; private AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { int oldValue = submitted.get(); submitted.set(oldValue + value); } public void incrementCompleted(int value) { int oldValue = completed.get(); completed.set(oldValue + value); } public void incrementError(int value) { int oldValue = error.get(); error.set(oldValue + value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } }
package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private final AtomicInteger submitted; private final AtomicInteger completed; private final AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { submitted.getAndAdd(value); } public void incrementCompleted(int value) { completed.getAndAdd(value); } public void incrementError(int value) { error.getAndAdd(value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } }
Use atomic operation to increment the execution stats values
Use atomic operation to increment the execution stats values
Java
apache-2.0
EBIBioSamples/EbiGeneralSearch,EBIBioSamples/EbiGeneralSearch
java
## Code Before: package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private AtomicInteger submitted; private AtomicInteger completed; private AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { int oldValue = submitted.get(); submitted.set(oldValue + value); } public void incrementCompleted(int value) { int oldValue = completed.get(); completed.set(oldValue + value); } public void incrementError(int value) { int oldValue = error.get(); error.set(oldValue + value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } } ## Instruction: Use atomic operation to increment the execution stats values ## Code After: package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private final AtomicInteger submitted; private final AtomicInteger completed; private final AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { submitted.getAndAdd(value); } public void incrementCompleted(int value) { completed.getAndAdd(value); } public void incrementError(int value) { error.getAndAdd(value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } }
// ... existing code ... import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private final AtomicInteger submitted; private final AtomicInteger completed; private final AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); // ... modified code ... public void incrementSubmitted(int value) { submitted.getAndAdd(value); } public void incrementCompleted(int value) { completed.getAndAdd(value); } public void incrementError(int value) { error.getAndAdd(value); } public int getCompleted() { // ... rest of the code ...
f0567acb9b6aa5f5abf4c424f9b900ce63638cb0
Client/MySQL-Driver/src/main/java/net/sourceforge/javydreamercsw/mysql/driver/Installer.java
Client/MySQL-Driver/src/main/java/net/sourceforge/javydreamercsw/mysql/driver/Installer.java
package net.sourceforge.javydreamercsw.mysql.driver; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import org.netbeans.api.db.explorer.DatabaseException; import org.netbeans.api.db.explorer.JDBCDriver; import org.netbeans.api.db.explorer.JDBCDriverManager; import org.openide.modules.ModuleInstall; import org.openide.util.Exceptions; import org.openide.windows.WindowManager; public class Installer extends ModuleInstall { public static final String mysqlDriverClass = "com.mysql.jdbc.Driver"; private static final Logger LOG = Logger.getLogger(Installer.class.getCanonicalName()); @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { //Check drivers if (JDBCDriverManager.getDefault().getDrivers(mysqlDriverClass).length == 0) { try { LOG.fine("Registering MySQL driver!"); JDBCDriverManager.getDefault().addDriver( JDBCDriver.create("mysql", "MySQL", mysqlDriverClass, new URL[]{new URL( "nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar")})); } catch (DatabaseException ex) { Exceptions.printStackTrace(ex); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } } } }); } }
package net.sourceforge.javydreamercsw.mysql.driver; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import org.netbeans.api.db.explorer.DatabaseException; import org.netbeans.api.db.explorer.JDBCDriver; import org.netbeans.api.db.explorer.JDBCDriverManager; import org.openide.modules.ModuleInstall; import org.openide.util.Exceptions; import org.openide.windows.WindowManager; public class Installer extends ModuleInstall { public static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final Logger LOG = Logger.getLogger(Installer.class.getCanonicalName()); @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady(() -> { //Check drivers if (JDBCDriverManager.getDefault().getDrivers(DRIVER).length == 0) { try { LOG.fine("Registering MySQL driver!"); JDBCDriverManager.getDefault().addDriver( JDBCDriver.create("mysql", "MySQL", DRIVER, new URL[]{new URL( "nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar")})); } catch (DatabaseException | MalformedURLException ex) { Exceptions.printStackTrace(ex); } } }); } }
Use correct driver class as the old one is being deprecated.
Use correct driver class as the old one is being deprecated.
Java
apache-2.0
javydreamercsw/validation-manager
java
## Code Before: package net.sourceforge.javydreamercsw.mysql.driver; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import org.netbeans.api.db.explorer.DatabaseException; import org.netbeans.api.db.explorer.JDBCDriver; import org.netbeans.api.db.explorer.JDBCDriverManager; import org.openide.modules.ModuleInstall; import org.openide.util.Exceptions; import org.openide.windows.WindowManager; public class Installer extends ModuleInstall { public static final String mysqlDriverClass = "com.mysql.jdbc.Driver"; private static final Logger LOG = Logger.getLogger(Installer.class.getCanonicalName()); @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { //Check drivers if (JDBCDriverManager.getDefault().getDrivers(mysqlDriverClass).length == 0) { try { LOG.fine("Registering MySQL driver!"); JDBCDriverManager.getDefault().addDriver( JDBCDriver.create("mysql", "MySQL", mysqlDriverClass, new URL[]{new URL( "nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar")})); } catch (DatabaseException ex) { Exceptions.printStackTrace(ex); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } } } }); } } ## Instruction: Use correct driver class as the old one is being deprecated. ## Code After: package net.sourceforge.javydreamercsw.mysql.driver; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import org.netbeans.api.db.explorer.DatabaseException; import org.netbeans.api.db.explorer.JDBCDriver; import org.netbeans.api.db.explorer.JDBCDriverManager; import org.openide.modules.ModuleInstall; import org.openide.util.Exceptions; import org.openide.windows.WindowManager; public class Installer extends ModuleInstall { public static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final Logger LOG = Logger.getLogger(Installer.class.getCanonicalName()); @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady(() -> { //Check drivers if (JDBCDriverManager.getDefault().getDrivers(DRIVER).length == 0) { try { LOG.fine("Registering MySQL driver!"); JDBCDriverManager.getDefault().addDriver( JDBCDriver.create("mysql", "MySQL", DRIVER, new URL[]{new URL( "nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar")})); } catch (DatabaseException | MalformedURLException ex) { Exceptions.printStackTrace(ex); } } }); } }
# ... existing code ... public class Installer extends ModuleInstall { public static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final Logger LOG = Logger.getLogger(Installer.class.getCanonicalName()); @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady(() -> { //Check drivers if (JDBCDriverManager.getDefault().getDrivers(DRIVER).length == 0) { try { LOG.fine("Registering MySQL driver!"); JDBCDriverManager.getDefault().addDriver( JDBCDriver.create("mysql", "MySQL", DRIVER, new URL[]{new URL( "nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar")})); } catch (DatabaseException | MalformedURLException ex) { Exceptions.printStackTrace(ex); } } }); # ... rest of the code ...
a9bdf9ec691f0e688af41be1216977b9ce9c8976
helpers.py
helpers.py
## Import python libraries we need up here. ############################################### ### Problem One! ### ############################################### def get_city_coordinates(): """Find the GPS coordinates for Charlottesville, and fill in the information below """ lattitude = ??? longitude = ??? return lattitude, longitude ############################################### ### Problem Two! ### ############################################### def get_icon_size(): """ Modify this function to return a number of instagram photos you want to appear on the site at a time! Because of how the instagram API works, it won't return more than 20 photos at once. """ size = ??? return size ############################################### ### Problem Three! ### ############################################### def choose_number_of_tweets(): """ Modify this function to return the max number of tweets you want to appear on the site at a time! """ return number ############################################### ### Problem Four! ### ############################################### def choose_hashtag(): """ Modify this function to use return the hashtah #sparkhackathon """ return hashtag
## Import python libraries we need up here. ############################################### ### Problem One! ### ############################################### def get_city_coordinates(): """Find the GPS coordinates for Charlottesville, and fill in the information below """ lattitude = ??? longitude = ??? return lattitude, longitude ############################################### ### Problem Two! ### ############################################### def get_icon_size(): """ Modify this function to return a number of instagram photos you want to appear on the site at a time! Because of how the instagram API works, it won't return more than 20 photos at once. """ size = ??? return size ############################################### ### Problem Three! ### ############################################### def choose_number_of_tweets(): """ Modify this function to return the max number of tweets you want to appear on the site at a time! """ number = 30 return number ############################################### ### Problem Four! ### ############################################### def choose_hashtag(): """ Modify this function to use return the hashtah #sparkhackathon """ return hashtag
Set tweet limit to 30 tweets
Set tweet limit to 30 tweets
Python
apache-2.0
samanehsan/spark_github,samanehsan/spark_github,samanehsan/learn-git,samanehsan/learn-git
python
## Code Before: ## Import python libraries we need up here. ############################################### ### Problem One! ### ############################################### def get_city_coordinates(): """Find the GPS coordinates for Charlottesville, and fill in the information below """ lattitude = ??? longitude = ??? return lattitude, longitude ############################################### ### Problem Two! ### ############################################### def get_icon_size(): """ Modify this function to return a number of instagram photos you want to appear on the site at a time! Because of how the instagram API works, it won't return more than 20 photos at once. """ size = ??? return size ############################################### ### Problem Three! ### ############################################### def choose_number_of_tweets(): """ Modify this function to return the max number of tweets you want to appear on the site at a time! """ return number ############################################### ### Problem Four! ### ############################################### def choose_hashtag(): """ Modify this function to use return the hashtah #sparkhackathon """ return hashtag ## Instruction: Set tweet limit to 30 tweets ## Code After: ## Import python libraries we need up here. ############################################### ### Problem One! ### ############################################### def get_city_coordinates(): """Find the GPS coordinates for Charlottesville, and fill in the information below """ lattitude = ??? longitude = ??? return lattitude, longitude ############################################### ### Problem Two! ### ############################################### def get_icon_size(): """ Modify this function to return a number of instagram photos you want to appear on the site at a time! Because of how the instagram API works, it won't return more than 20 photos at once. """ size = ??? return size ############################################### ### Problem Three! ### ############################################### def choose_number_of_tweets(): """ Modify this function to return the max number of tweets you want to appear on the site at a time! """ number = 30 return number ############################################### ### Problem Four! ### ############################################### def choose_hashtag(): """ Modify this function to use return the hashtah #sparkhackathon """ return hashtag
... """ Modify this function to return the max number of tweets you want to appear on the site at a time! """ number = 30 return number ...
925fefdcdaf32123a9ed4ed2b038bcb11269d77d
main/appengine_config.py
main/appengine_config.py
import os import sys sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
Remove duplicate libx path insertion
Remove duplicate libx path insertion
Python
mit
gae-init/gae-init-babel,lipis/life-line,lipis/life-line,mdxs/gae-init-babel,gae-init/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,lipis/life-line
python
## Code Before: import os import sys sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx') ## Instruction: Remove duplicate libx path insertion ## Code After: import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
# ... existing code ... import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') # ... rest of the code ...
bff010be0ee1a8e512486777c47228449a766cd3
webhooks/admin.py
webhooks/admin.py
from django.contrib import admin from .models import Webhook admin.site.register(Webhook)
from django.contrib import admin from .models import Webhook class WebhookAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'event', 'url') list_editable = ('event', 'url') list_filter = ('event',) admin.site.register(Webhook, WebhookAdmin)
Add custom ModelAdmin for easier editing from list view
Add custom ModelAdmin for easier editing from list view
Python
bsd-2-clause
chop-dbhi/django-webhooks,pombredanne/django-webhooks,chop-dbhi/django-webhooks,pombredanne/django-webhooks
python
## Code Before: from django.contrib import admin from .models import Webhook admin.site.register(Webhook) ## Instruction: Add custom ModelAdmin for easier editing from list view ## Code After: from django.contrib import admin from .models import Webhook class WebhookAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'event', 'url') list_editable = ('event', 'url') list_filter = ('event',) admin.site.register(Webhook, WebhookAdmin)
// ... existing code ... from django.contrib import admin from .models import Webhook class WebhookAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'event', 'url') list_editable = ('event', 'url') list_filter = ('event',) admin.site.register(Webhook, WebhookAdmin) // ... rest of the code ...
192e24cdafff2bb780ef9cc87853c48e9e41cb4a
stationspinner/accounting/management/commands/characters.py
stationspinner/accounting/management/commands/characters.py
from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterSheet.objects.filter(enabled=True) for char in characters: self.stdout.write('CharacterID\t\t {0} APIKey\t\t {1}'.format(char.pk, char.owner_key.pk))
from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterSheet.objects.filter(enabled=True) for char in characters: self.stdout.write('{0}\t\tCharacterID\t\t {1} APIKey\t\t {2}'.format(char.name, char.pk, char.owner_key.pk))
Simplify the output for copypaste
Simplify the output for copypaste
Python
agpl-3.0
kriberg/stationspinner,kriberg/stationspinner
python
## Code Before: from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterSheet.objects.filter(enabled=True) for char in characters: self.stdout.write('CharacterID\t\t {0} APIKey\t\t {1}'.format(char.pk, char.owner_key.pk)) ## Instruction: Simplify the output for copypaste ## Code After: from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterSheet.objects.filter(enabled=True) for char in characters: self.stdout.write('{0}\t\tCharacterID\t\t {1} APIKey\t\t {2}'.format(char.name, char.pk, char.owner_key.pk))
... def handle(self, *args, **options): characters = CharacterSheet.objects.filter(enabled=True) for char in characters: self.stdout.write('{0}\t\tCharacterID\t\t {1} APIKey\t\t {2}'.format(char.name, char.pk, char.owner_key.pk)) ...
523e5780fd467222967bce3c03186d5af7f3623f
entrec/char_rnn_test.py
entrec/char_rnn_test.py
import tensorflow as tf from .char_rnn import char_rnn def test_char_rnn(): for i, (sentence_shape, labels_shape) in enumerate([ [[None, 64, 8], [None, 64]], [[None, None, 8], [None, None]], [[None, None, None], [None, None]]]): for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL, tf.contrib.learn.ModeKeys.INFER]: with tf.variable_scope('model_{}_{}'.format(i, mode)): char_rnn(tf.placeholder(tf.int32, sentence_shape), tf.placeholder(tf.int32, labels_shape), mode=mode, num_classes=7, char_space_size=128, char_embedding_size=128, word_embedding_size=128, context_vector_size=128)
import tensorflow as tf from .char_rnn import char_rnn def test_char_rnn(): for i, (sentence_shape, labels_shape) in enumerate([ [[11, 64, 8], [11, 64]], [[None, 64, 8], [None, 64]], [[None, None, 8], [None, None]], [[None, None, None], [None, None]]]): for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL, tf.contrib.learn.ModeKeys.INFER]: with tf.variable_scope('model_{}_{}'.format(i, mode)): char_rnn(tf.placeholder(tf.int32, sentence_shape), tf.placeholder(tf.int32, labels_shape), mode=mode, num_classes=7, char_space_size=128, char_embedding_size=128, word_embedding_size=128, context_vector_size=128)
Test char rnn with static batch size
Test char rnn with static batch size
Python
unlicense
raviqqe/tensorflow-entrec,raviqqe/tensorflow-entrec
python
## Code Before: import tensorflow as tf from .char_rnn import char_rnn def test_char_rnn(): for i, (sentence_shape, labels_shape) in enumerate([ [[None, 64, 8], [None, 64]], [[None, None, 8], [None, None]], [[None, None, None], [None, None]]]): for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL, tf.contrib.learn.ModeKeys.INFER]: with tf.variable_scope('model_{}_{}'.format(i, mode)): char_rnn(tf.placeholder(tf.int32, sentence_shape), tf.placeholder(tf.int32, labels_shape), mode=mode, num_classes=7, char_space_size=128, char_embedding_size=128, word_embedding_size=128, context_vector_size=128) ## Instruction: Test char rnn with static batch size ## Code After: import tensorflow as tf from .char_rnn import char_rnn def test_char_rnn(): for i, (sentence_shape, labels_shape) in enumerate([ [[11, 64, 8], [11, 64]], [[None, 64, 8], [None, 64]], [[None, None, 8], [None, None]], [[None, None, None], [None, None]]]): for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL, tf.contrib.learn.ModeKeys.INFER]: with tf.variable_scope('model_{}_{}'.format(i, mode)): char_rnn(tf.placeholder(tf.int32, sentence_shape), tf.placeholder(tf.int32, labels_shape), mode=mode, num_classes=7, char_space_size=128, char_embedding_size=128, word_embedding_size=128, context_vector_size=128)
// ... existing code ... def test_char_rnn(): for i, (sentence_shape, labels_shape) in enumerate([ [[11, 64, 8], [11, 64]], [[None, 64, 8], [None, 64]], [[None, None, 8], [None, None]], [[None, None, None], [None, None]]]): // ... rest of the code ...
6a58430516878dbd1c5f146bb7eef740d2bb5f42
src/main/kotlin/org/wfanet/measurement/common/CommonServer.kt
src/main/kotlin/org/wfanet/measurement/common/CommonServer.kt
package org.wfanet.measurement.common import io.grpc.BindableService import io.grpc.Server import io.grpc.ServerBuilder import java.io.IOException import java.util.logging.Level import java.util.logging.Logger class CommonServer(private val serversEnum: CommonServerType, vararg services: BindableService) { private var server: Server init { val builder = ServerBuilder.forPort(serversEnum.port) services.forEach { builder.addService(it) } server = builder.build() } @Throws(IOException::class) fun start(): CommonServer { server.start() logger.log(Level.INFO, "${serversEnum.nameForLogging} started, listening on ${serversEnum.port}") Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** ${serversEnum.nameForLogging} shutting down...") [email protected]() System.err.println("*** ${serversEnum.nameForLogging} shut down") } }) return this } private fun stop() { server.shutdown() } @Throws(InterruptedException::class) fun blockUntilShutdown() { server.awaitTermination() } companion object { private val logger = Logger.getLogger(this::class.java.name) } } enum class CommonServerType(val nameForLogging: String, val port: Int) { COMPUTATION_CONTROL("ComputationControlServer", 31124), PUBLISHER_DATA("PublisherDataServer", 31125), REQUISITION("RequisitionServer", 31126) }
package org.wfanet.measurement.common import io.grpc.BindableService import io.grpc.Server import io.grpc.ServerBuilder import java.io.IOException import java.util.logging.Level import java.util.logging.Logger class CommonServer( private val nameForLogging: String, private val port: Int, vararg services: BindableService ) { private var server: Server init { val builder = ServerBuilder.forPort(port) services.forEach { builder.addService(it) } server = builder.build() } @Throws(IOException::class) fun start(): CommonServer { server.start() logger.log( Level.INFO, "$nameForLogging started, listening on $port" ) Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** $nameForLogging shutting down...") [email protected]() System.err.println("*** $nameForLogging shut down") } }) return this } private fun stop() { server.shutdown() } @Throws(InterruptedException::class) fun blockUntilShutdown() { server.awaitTermination() } companion object { private val logger = Logger.getLogger(this::class.java.name) } }
Create Duchy servers for workers and work management.
Create Duchy servers for workers and work management. Change-Id: I8ecd8cdf0c02acda3588f9c539cc7caf3ce7f900
Kotlin
apache-2.0
world-federation-of-advertisers/common-jvm,world-federation-of-advertisers/common-jvm
kotlin
## Code Before: package org.wfanet.measurement.common import io.grpc.BindableService import io.grpc.Server import io.grpc.ServerBuilder import java.io.IOException import java.util.logging.Level import java.util.logging.Logger class CommonServer(private val serversEnum: CommonServerType, vararg services: BindableService) { private var server: Server init { val builder = ServerBuilder.forPort(serversEnum.port) services.forEach { builder.addService(it) } server = builder.build() } @Throws(IOException::class) fun start(): CommonServer { server.start() logger.log(Level.INFO, "${serversEnum.nameForLogging} started, listening on ${serversEnum.port}") Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** ${serversEnum.nameForLogging} shutting down...") [email protected]() System.err.println("*** ${serversEnum.nameForLogging} shut down") } }) return this } private fun stop() { server.shutdown() } @Throws(InterruptedException::class) fun blockUntilShutdown() { server.awaitTermination() } companion object { private val logger = Logger.getLogger(this::class.java.name) } } enum class CommonServerType(val nameForLogging: String, val port: Int) { COMPUTATION_CONTROL("ComputationControlServer", 31124), PUBLISHER_DATA("PublisherDataServer", 31125), REQUISITION("RequisitionServer", 31126) } ## Instruction: Create Duchy servers for workers and work management. Change-Id: I8ecd8cdf0c02acda3588f9c539cc7caf3ce7f900 ## Code After: package org.wfanet.measurement.common import io.grpc.BindableService import io.grpc.Server import io.grpc.ServerBuilder import java.io.IOException import java.util.logging.Level import java.util.logging.Logger class CommonServer( private val nameForLogging: String, private val port: Int, vararg services: BindableService ) { private var server: Server init { val builder = ServerBuilder.forPort(port) services.forEach { builder.addService(it) } server = builder.build() } @Throws(IOException::class) fun start(): CommonServer { server.start() logger.log( Level.INFO, "$nameForLogging started, listening on $port" ) Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** $nameForLogging shutting down...") [email protected]() System.err.println("*** $nameForLogging shut down") } }) return this } private fun stop() { server.shutdown() } @Throws(InterruptedException::class) fun blockUntilShutdown() { server.awaitTermination() } companion object { private val logger = Logger.getLogger(this::class.java.name) } }
// ... existing code ... import java.util.logging.Level import java.util.logging.Logger class CommonServer( private val nameForLogging: String, private val port: Int, vararg services: BindableService ) { private var server: Server init { val builder = ServerBuilder.forPort(port) services.forEach { builder.addService(it) } // ... modified code ... @Throws(IOException::class) fun start(): CommonServer { server.start() logger.log( Level.INFO, "$nameForLogging started, listening on $port" ) Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** $nameForLogging shutting down...") [email protected]() System.err.println("*** $nameForLogging shut down") } }) return this ... private val logger = Logger.getLogger(this::class.java.name) } } // ... rest of the code ...
478afbc2178850d209d5d5d4c0626581b601f208
cutepaste/tests/conftest.py
cutepaste/tests/conftest.py
import os import pytest from pyvirtualdisplay import Display from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options REPORTS_DIR = "reports" @pytest.fixture(scope='function') def webdriver(request): display = Display(visible=0, size=(800, 600), use_xauth=True) display.start() options = Options() options.add_argument("--no-sandbox") driver = Chrome(chrome_options=options) prev_failed_tests = request.session.testsfailed yield driver if prev_failed_tests != request.session.testsfailed: try: os.makedirs(REPORTS_DIR) except os.error: pass test_name = request.function.__module__ + "." + request.function.__name__ driver.save_screenshot(f"reports/{test_name}.png") with open(f"reports/{test_name}.html", "w") as f: f.write(driver.page_source) driver.quit() display.stop()
import os import pytest from pyvirtualdisplay import Display from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options REPORTS_DIR = "reports" @pytest.fixture(scope='function') def webdriver(request): display = Display(visible=0, size=(800, 600), use_xauth=True) display.start() options = Options() options.add_argument("--no-sandbox") driver = Chrome(chrome_options=options) driver.implicitly_wait(1) prev_failed_tests = request.session.testsfailed yield driver if prev_failed_tests != request.session.testsfailed: try: os.makedirs(REPORTS_DIR) except os.error: pass test_name = request.function.__module__ + "." + request.function.__name__ driver.save_screenshot(f"reports/{test_name}.png") with open(f"reports/{test_name}.html", "w") as f: f.write(driver.page_source) driver.quit() display.stop()
Add an implicit wait of 1 second
Add an implicit wait of 1 second
Python
apache-2.0
msurdi/cutepaste,msurdi/cutepaste,msurdi/cutepaste
python
## Code Before: import os import pytest from pyvirtualdisplay import Display from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options REPORTS_DIR = "reports" @pytest.fixture(scope='function') def webdriver(request): display = Display(visible=0, size=(800, 600), use_xauth=True) display.start() options = Options() options.add_argument("--no-sandbox") driver = Chrome(chrome_options=options) prev_failed_tests = request.session.testsfailed yield driver if prev_failed_tests != request.session.testsfailed: try: os.makedirs(REPORTS_DIR) except os.error: pass test_name = request.function.__module__ + "." + request.function.__name__ driver.save_screenshot(f"reports/{test_name}.png") with open(f"reports/{test_name}.html", "w") as f: f.write(driver.page_source) driver.quit() display.stop() ## Instruction: Add an implicit wait of 1 second ## Code After: import os import pytest from pyvirtualdisplay import Display from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options REPORTS_DIR = "reports" @pytest.fixture(scope='function') def webdriver(request): display = Display(visible=0, size=(800, 600), use_xauth=True) display.start() options = Options() options.add_argument("--no-sandbox") driver = Chrome(chrome_options=options) driver.implicitly_wait(1) prev_failed_tests = request.session.testsfailed yield driver if prev_failed_tests != request.session.testsfailed: try: os.makedirs(REPORTS_DIR) except os.error: pass test_name = request.function.__module__ + "." + request.function.__name__ driver.save_screenshot(f"reports/{test_name}.png") with open(f"reports/{test_name}.html", "w") as f: f.write(driver.page_source) driver.quit() display.stop()
# ... existing code ... options = Options() options.add_argument("--no-sandbox") driver = Chrome(chrome_options=options) driver.implicitly_wait(1) prev_failed_tests = request.session.testsfailed yield driver # ... rest of the code ...
a4913289ce0672cfe60bb443db469356f970c353
wakatime/projects/projectmap.py
wakatime/projects/projectmap.py
import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): self.config = self._load_config() if self.config: log.debug(self.config) return True return False def branch(self): return None def name(self): for path in self._path_generator(): if path in self.config: return self.config[path] return None def _load_config(self): map_path = "%s/.waka-projectmap" % os.environ['HOME'] if os.path.isfile(map_path): with open(map_path) as map_file: try: return json.load(map_file) except (IOError, json.JSONDecodeError) as e: log.exception("ProjectMap Exception: ") return False def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): if self.config: return True return False def branch(self): return None def name(self): for path in self._path_generator(): if self.config.has_option('projectmap', path): return self.config.get('projectmap', path) return None def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
Make ProjectMap use config section
Make ProjectMap use config section
Python
bsd-3-clause
wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,queenp/wakatime,gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,Djabbz/wakatime,gandarez/wakatime,wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,wangjun/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wangjun/wakatime,wakatime/wakatime,wakatime/wakatime
python
## Code Before: import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): self.config = self._load_config() if self.config: log.debug(self.config) return True return False def branch(self): return None def name(self): for path in self._path_generator(): if path in self.config: return self.config[path] return None def _load_config(self): map_path = "%s/.waka-projectmap" % os.environ['HOME'] if os.path.isfile(map_path): with open(map_path) as map_file: try: return json.load(map_file) except (IOError, json.JSONDecodeError) as e: log.exception("ProjectMap Exception: ") return False def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path) ## Instruction: Make ProjectMap use config section ## Code After: import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): if self.config: return True return False def branch(self): return None def name(self): for path in self._path_generator(): if self.config.has_option('projectmap', path): return self.config.get('projectmap', path) return None def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
// ... existing code ... class ProjectMap(BaseProject): def process(self): if self.config: return True return False // ... modified code ... def name(self): for path in self._path_generator(): if self.config.has_option('projectmap', path): return self.config.get('projectmap', path) return None def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') // ... rest of the code ...
efd44be24e84a35db353ac79dae7cc7392a18b0c
matador/commands/deploy_ticket.py
matador/commands/deploy_ticket.py
from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') parser.add_argument( '-', '--package', type=bool, default=False, help='Agresso environment name') def _checkout_ticket(self, project, ticket, branch='master'): repo_folder = utils.matador_repository_folder(project) subprocess.run([ 'git', '-C', repo_folder, 'checkout', branch], stderr=subprocess.STDOUT, stdout=open(os.devnull, 'w')) def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project) self._checkout_ticket(project, 'test')
from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') parser.add_argument( '-t', '--ticket', type=str, required=True, help='Ticket name') parser.add_argument( '-b', '--branch', type=str, default='master', help='Branch name') parser.add_argument( '-', '--package', type=bool, default=False, help='Agresso environment name') def _checkout_ticket(self, project, ticket, branch='master'): repo_folder = utils.matador_repository_folder(project) subprocess.run([ 'git', '-C', repo_folder, 'checkout', branch], stderr=subprocess.STDOUT, stdout=open(os.devnull, 'w')) def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project, self.args.branch) self._checkout_ticket(project, self.args.ticket)
Add ticket and branch arguments
Add ticket and branch arguments
Python
mit
Empiria/matador
python
## Code Before: from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') parser.add_argument( '-', '--package', type=bool, default=False, help='Agresso environment name') def _checkout_ticket(self, project, ticket, branch='master'): repo_folder = utils.matador_repository_folder(project) subprocess.run([ 'git', '-C', repo_folder, 'checkout', branch], stderr=subprocess.STDOUT, stdout=open(os.devnull, 'w')) def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project) self._checkout_ticket(project, 'test') ## Instruction: Add ticket and branch arguments ## Code After: from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') parser.add_argument( '-t', '--ticket', type=str, required=True, help='Ticket name') parser.add_argument( '-b', '--branch', type=str, default='master', help='Branch name') parser.add_argument( '-', '--package', type=bool, default=False, help='Agresso environment name') def _checkout_ticket(self, project, ticket, branch='master'): repo_folder = utils.matador_repository_folder(project) subprocess.run([ 'git', '-C', repo_folder, 'checkout', branch], stderr=subprocess.STDOUT, stdout=open(os.devnull, 'w')) def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project, self.args.branch) self._checkout_ticket(project, self.args.ticket)
# ... existing code ... help='Agresso environment name') parser.add_argument( '-t', '--ticket', type=str, required=True, help='Ticket name') parser.add_argument( '-b', '--branch', type=str, default='master', help='Branch name') parser.add_argument( '-', '--package', type=bool, default=False, # ... modified code ... def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project, self.args.branch) self._checkout_ticket(project, self.args.ticket) # ... rest of the code ...
a49a3c133478c01774adfe8853b608e110a5a2e6
examples/test_double_click.py
examples/test_double_click.py
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.switch_to_frame("iframeResult") self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo")
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click_and_switch_to_frame(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame("#iframeResult") self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo") def test_double_click_and_switch_to_frame_of_element(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame_of_element('[ondblclick="myFunction()"]') self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo")
Update a test for entering iframes and double-clicking
Update a test for entering iframes and double-clicking
Python
mit
seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
python
## Code Before: from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.switch_to_frame("iframeResult") self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo") ## Instruction: Update a test for entering iframes and double-clicking ## Code After: from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click_and_switch_to_frame(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame("#iframeResult") self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo") def test_double_click_and_switch_to_frame_of_element(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame_of_element('[ondblclick="myFunction()"]') self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo")
// ... existing code ... class MyTestClass(BaseCase): def test_double_click_and_switch_to_frame(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame("#iframeResult") self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo") def test_double_click_and_switch_to_frame_of_element(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame_of_element('[ondblclick="myFunction()"]') self.double_click('[ondblclick="myFunction()"]') self.assert_text("Hello World", "#demo") // ... rest of the code ...
6fee339bd8ccc195012921cdc9284de41c992571
JASP-Common/options/optionfieldpairs.h
JASP-Common/options/optionfieldpairs.h
typedef std::pair<std::string, std::string> FieldPair; typedef std::vector<FieldPair> FieldPairs; class OptionFieldPairs : public OptionI<std::vector<std::pair<std::string, std::string> > > { public: OptionFieldPairs(std::string name); virtual Json::Value asJSON() const override; virtual void set(Json::Value &value) override; }; #endif // OPTIONFIELDPAIRS_H
typedef std::pair<std::string, std::string> FieldPair; typedef std::vector<FieldPair> FieldPairs; class OptionFieldPairs : public OptionI<std::vector<std::pair<std::string, std::string> > > { public: OptionFieldPairs(std::string name); virtual Json::Value asJSON() const OVERRIDE; virtual void set(Json::Value &value) OVERRIDE; }; #endif // OPTIONFIELDPAIRS_H
Fix for GCC 4.6 compatibility
Fix for GCC 4.6 compatibility
C
agpl-3.0
TimKDJ/jasp-desktop,raviselker/jasp-desktop,AlexanderLyNL/jasp-desktop,dostodabsi/jasp-desktop,AlexanderLyNL/jasp-desktop,aknight1-uva/jasp-desktop,dostodabsi/jasp-desktop,AlexanderLyNL/jasp-desktop,dostodabsi/jasp-desktop,FransMeerhoff/jasp-desktop,Tahiraj/jasp-desktop,cgvarela/jasp-desktop,boutinb/jasp-desktop,vankesteren/jasp-desktop,vankesteren/jasp-desktop,raviselker/jasp-desktop,aknight1-uva/jasp-desktop,dostodabsi/jasp-desktop,fdabl/jasp-desktop,jasp-stats/jasp-desktop,jasp-stats/jasp-desktop,Tahiraj/jasp-desktop,jasp-stats/jasp-desktop,FransMeerhoff/jasp-desktop,tlevine/jasp-desktop,raviselker/jasp-desktop,TimKDJ/jasp-desktop,tlevine/jasp-desktop,cgvarela/jasp-desktop,jasp-stats/jasp-desktop,vankesteren/jasp-desktop,dropmann/jasp-desktop,vankesteren/jasp-desktop,dropmann/jasp-desktop,AlexanderLyNL/jasp-desktop,dostodabsi/jasp-desktop,boutinb/jasp-desktop,dropmann/jasp-desktop,TimKDJ/jasp-desktop,AlexanderLyNL/jasp-desktop,AlexanderLyNL/jasp-desktop,FransMeerhoff/jasp-desktop,FransMeerhoff/jasp-desktop,TimKDJ/jasp-desktop,fdabl/jasp-desktop,aknight1-uva/jasp-desktop,boutinb/jasp-desktop,TimKDJ/jasp-desktop,raviselker/jasp-desktop,vankesteren/jasp-desktop,dropmann/jasp-desktop,AlexanderLyNL/jasp-desktop,jasp-stats/jasp-desktop,boutinb/jasp-desktop,aknight1-uva/jasp-desktop,TimKDJ/jasp-desktop,boutinb/jasp-desktop,tlevine/jasp-desktop,jasp-stats/jasp-desktop,FransMeerhoff/jasp-desktop,cgvarela/jasp-desktop,dropmann/jasp-desktop,raviselker/jasp-desktop,TimKDJ/jasp-desktop,fdabl/jasp-desktop,vankesteren/jasp-desktop,aknight1-uva/jasp-desktop,Tahiraj/jasp-desktop,dropmann/jasp-desktop,Tahiraj/jasp-desktop,FransMeerhoff/jasp-desktop,raviselker/jasp-desktop,TimKDJ/jasp-desktop,aknight1-uva/jasp-desktop,cgvarela/jasp-desktop,raviselker/jasp-desktop,FransMeerhoff/jasp-desktop,jasp-stats/jasp-desktop,vankesteren/jasp-desktop,boutinb/jasp-desktop,jasp-stats/jasp-desktop,dropmann/jasp-desktop,fdabl/jasp-desktop,cgvarela/jasp-desktop,tlevine/jasp-desktop,tlevine/jasp-desktop,fdabl/jasp-desktop,aknight1-uva/jasp-desktop,Tahiraj/jasp-desktop,FransMeerhoff/jasp-desktop,AlexanderLyNL/jasp-desktop,boutinb/jasp-desktop,fdabl/jasp-desktop,boutinb/jasp-desktop,dostodabsi/jasp-desktop,dostodabsi/jasp-desktop,vankesteren/jasp-desktop,fdabl/jasp-desktop
c
## Code Before: typedef std::pair<std::string, std::string> FieldPair; typedef std::vector<FieldPair> FieldPairs; class OptionFieldPairs : public OptionI<std::vector<std::pair<std::string, std::string> > > { public: OptionFieldPairs(std::string name); virtual Json::Value asJSON() const override; virtual void set(Json::Value &value) override; }; #endif // OPTIONFIELDPAIRS_H ## Instruction: Fix for GCC 4.6 compatibility ## Code After: typedef std::pair<std::string, std::string> FieldPair; typedef std::vector<FieldPair> FieldPairs; class OptionFieldPairs : public OptionI<std::vector<std::pair<std::string, std::string> > > { public: OptionFieldPairs(std::string name); virtual Json::Value asJSON() const OVERRIDE; virtual void set(Json::Value &value) OVERRIDE; }; #endif // OPTIONFIELDPAIRS_H
# ... existing code ... public: OptionFieldPairs(std::string name); virtual Json::Value asJSON() const OVERRIDE; virtual void set(Json::Value &value) OVERRIDE; }; #endif // OPTIONFIELDPAIRS_H # ... rest of the code ...
aa2a2a57030dec2e8b73b017de5f157aae0fb5e5
tests/qtgui/qpixmap_test.py
tests/qtgui/qpixmap_test.py
import unittest from helper import UsesQApplication from PySide.QtGui import QPixmap from PySide.QtCore import QVariant #Only test if is possible create a QPixmap from a QVariant class QPixmapTest(UsesQApplication): def testQVariantConstructor(self): pixmap = QPixmap() v = QVariant(pixmap) pixmap_copy = QPixmap(v) if __name__ == '__main__': unittest.main()
import unittest from helper import UsesQApplication from PySide.QtGui import QPixmap from PySide.QtCore import QVariant, QSize, QString class QPixmapTest(UsesQApplication): def testQVariantConstructor(self): pixmap = QPixmap() v = QVariant(pixmap) pixmap_copy = QPixmap(v) def testQSizeConstructor(self): pixmap = QPixmap(QSize(10,20)) self.assert_(pixmap.size().height(), 20) def testQStringConstructor(self): pixmap = QPixmap(QString("Testing!")) if __name__ == '__main__': unittest.main()
Improve qpixmap test to support qstring and qsize arguments.
Improve qpixmap test to support qstring and qsize arguments. Reviewed by Marcelo Lira <[email protected]>
Python
lgpl-2.1
BadSingleton/pyside2,enthought/pyside,gbaty/pyside2,IronManMark20/pyside2,gbaty/pyside2,gbaty/pyside2,M4rtinK/pyside-android,PySide/PySide,pankajp/pyside,pankajp/pyside,PySide/PySide,M4rtinK/pyside-bb10,BadSingleton/pyside2,IronManMark20/pyside2,enthought/pyside,BadSingleton/pyside2,IronManMark20/pyside2,M4rtinK/pyside-android,M4rtinK/pyside-bb10,qtproject/pyside-pyside,gbaty/pyside2,M4rtinK/pyside-bb10,M4rtinK/pyside-android,qtproject/pyside-pyside,pankajp/pyside,IronManMark20/pyside2,RobinD42/pyside,enthought/pyside,PySide/PySide,BadSingleton/pyside2,M4rtinK/pyside-bb10,M4rtinK/pyside-android,M4rtinK/pyside-bb10,gbaty/pyside2,BadSingleton/pyside2,enthought/pyside,qtproject/pyside-pyside,RobinD42/pyside,RobinD42/pyside,RobinD42/pyside,M4rtinK/pyside-bb10,enthought/pyside,PySide/PySide,qtproject/pyside-pyside,RobinD42/pyside,M4rtinK/pyside-android,enthought/pyside,enthought/pyside,pankajp/pyside,RobinD42/pyside,qtproject/pyside-pyside,IronManMark20/pyside2,M4rtinK/pyside-android,PySide/PySide,RobinD42/pyside,pankajp/pyside
python
## Code Before: import unittest from helper import UsesQApplication from PySide.QtGui import QPixmap from PySide.QtCore import QVariant #Only test if is possible create a QPixmap from a QVariant class QPixmapTest(UsesQApplication): def testQVariantConstructor(self): pixmap = QPixmap() v = QVariant(pixmap) pixmap_copy = QPixmap(v) if __name__ == '__main__': unittest.main() ## Instruction: Improve qpixmap test to support qstring and qsize arguments. Reviewed by Marcelo Lira <[email protected]> ## Code After: import unittest from helper import UsesQApplication from PySide.QtGui import QPixmap from PySide.QtCore import QVariant, QSize, QString class QPixmapTest(UsesQApplication): def testQVariantConstructor(self): pixmap = QPixmap() v = QVariant(pixmap) pixmap_copy = QPixmap(v) def testQSizeConstructor(self): pixmap = QPixmap(QSize(10,20)) self.assert_(pixmap.size().height(), 20) def testQStringConstructor(self): pixmap = QPixmap(QString("Testing!")) if __name__ == '__main__': unittest.main()
// ... existing code ... from helper import UsesQApplication from PySide.QtGui import QPixmap from PySide.QtCore import QVariant, QSize, QString class QPixmapTest(UsesQApplication): def testQVariantConstructor(self): pixmap = QPixmap() // ... modified code ... v = QVariant(pixmap) pixmap_copy = QPixmap(v) def testQSizeConstructor(self): pixmap = QPixmap(QSize(10,20)) self.assert_(pixmap.size().height(), 20) def testQStringConstructor(self): pixmap = QPixmap(QString("Testing!")) if __name__ == '__main__': unittest.main() // ... rest of the code ...
32a093a95bb1b94fba3ea36dc10b6e81086d9a5b
dbaas/dbaas_services/analyzing/tasks/analyze.py
dbaas/dbaas_services/analyzing/tasks/analyze.py
from dbaas.celery import app from account.models import User from logical.models import Database from util.decorators import only_one from simple_audit.models import AuditRequest from dbaas_services.analyzing.integration import AnalyzeService @app.task @only_one(key="analyze_databases_service_task", timeout=6000) def analyze_databases(self, endpoint, healh_check_route, healh_check_string, **kwargs): user = User.objects.get(username='admin') AuditRequest.new_request("analyze_databases", user, "localhost") try: databases = Database.objects.filter(is_in_quarantine=False) for database in databases: database_name, engine, instances = setup_database_info(database) result = analyze_service.run(engine=engine, database_name=database_name, instances=instances, **kwargs) print result except Exception: pass finally: AuditRequest.cleanup_request() def setup_database_info(database): databaseinfra = database.databaseinfra driver = databaseinfra.get_driver() database_instances = driver.get_database_instances() instances = [db_instance.dns.split('.')[0] for db_instance in database_instances] return database.name, database.engine_type, instances
import logging from dbaas.celery import app from account.models import User from logical.models import Database from util.decorators import only_one from simple_audit.models import AuditRequest from dbaas_services.analyzing.integration import AnalyzeService from dbaas_services.analyzing.exceptions import ServiceNotAvailable LOG = logging.getLogger(__name__) @app.task(bind=True) @only_one(key="analyze_databases_service_task", timeout=6000) def analyze_databases(self, endpoint, healh_check_route, healh_check_string, **kwargs): user = User.objects.get(username='admin') AuditRequest.new_request("analyze_databases", user, "localhost") try: try: analyze_service = AnalyzeService(endpoint, healh_check_route, healh_check_string) except ServiceNotAvailable as e: LOG.warn(e) return databases = Database.objects.filter(is_in_quarantine=False) for database in databases: database_name, engine, instances = setup_database_info(database) result = analyze_service.run(engine=engine, database_name=database_name, instances=instances, **kwargs) print result except Exception: pass finally: AuditRequest.cleanup_request() def setup_database_info(database): databaseinfra = database.databaseinfra driver = databaseinfra.get_driver() database_instances = driver.get_database_instances() instances = [db_instance.dns.split('.')[0] for db_instance in database_instances] return database.name, database.engine_type, instances
Check if service is working
Check if service is working
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
python
## Code Before: from dbaas.celery import app from account.models import User from logical.models import Database from util.decorators import only_one from simple_audit.models import AuditRequest from dbaas_services.analyzing.integration import AnalyzeService @app.task @only_one(key="analyze_databases_service_task", timeout=6000) def analyze_databases(self, endpoint, healh_check_route, healh_check_string, **kwargs): user = User.objects.get(username='admin') AuditRequest.new_request("analyze_databases", user, "localhost") try: databases = Database.objects.filter(is_in_quarantine=False) for database in databases: database_name, engine, instances = setup_database_info(database) result = analyze_service.run(engine=engine, database_name=database_name, instances=instances, **kwargs) print result except Exception: pass finally: AuditRequest.cleanup_request() def setup_database_info(database): databaseinfra = database.databaseinfra driver = databaseinfra.get_driver() database_instances = driver.get_database_instances() instances = [db_instance.dns.split('.')[0] for db_instance in database_instances] return database.name, database.engine_type, instances ## Instruction: Check if service is working ## Code After: import logging from dbaas.celery import app from account.models import User from logical.models import Database from util.decorators import only_one from simple_audit.models import AuditRequest from dbaas_services.analyzing.integration import AnalyzeService from dbaas_services.analyzing.exceptions import ServiceNotAvailable LOG = logging.getLogger(__name__) @app.task(bind=True) @only_one(key="analyze_databases_service_task", timeout=6000) def analyze_databases(self, endpoint, healh_check_route, healh_check_string, **kwargs): user = User.objects.get(username='admin') AuditRequest.new_request("analyze_databases", user, "localhost") try: try: analyze_service = AnalyzeService(endpoint, healh_check_route, healh_check_string) except ServiceNotAvailable as e: LOG.warn(e) return databases = Database.objects.filter(is_in_quarantine=False) for database in databases: database_name, engine, instances = setup_database_info(database) result = analyze_service.run(engine=engine, database_name=database_name, instances=instances, **kwargs) print result except Exception: pass finally: AuditRequest.cleanup_request() def setup_database_info(database): databaseinfra = database.databaseinfra driver = databaseinfra.get_driver() database_instances = driver.get_database_instances() instances = [db_instance.dns.split('.')[0] for db_instance in database_instances] return database.name, database.engine_type, instances
... import logging from dbaas.celery import app from account.models import User from logical.models import Database ... from util.decorators import only_one from simple_audit.models import AuditRequest from dbaas_services.analyzing.integration import AnalyzeService from dbaas_services.analyzing.exceptions import ServiceNotAvailable LOG = logging.getLogger(__name__) @app.task(bind=True) @only_one(key="analyze_databases_service_task", timeout=6000) def analyze_databases(self, endpoint, healh_check_route, healh_check_string, **kwargs): ... user = User.objects.get(username='admin') AuditRequest.new_request("analyze_databases", user, "localhost") try: try: analyze_service = AnalyzeService(endpoint, healh_check_route, healh_check_string) except ServiceNotAvailable as e: LOG.warn(e) return databases = Database.objects.filter(is_in_quarantine=False) for database in databases: database_name, engine, instances = setup_database_info(database) ...
67cb72b37ce0e68ceee7943295934f1d1fda179e
setup.py
setup.py
import os from setuptools import find_packages, setup from great import __url__ with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme: long_description = readme.read() classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] setup( name="great", packages=find_packages(), setup_requires=["setuptools_scm"], use_scm_version=True, install_requires=[ "Alchimia", "appdirs", "attrs", "filesystems", "hyperlink", "Minion", "pytoml", "SQLAlchemy", "Twisted", "txmusicbrainz", ], author="Julian Berman", author_email="[email protected]", classifiers=classifiers, description="A ratings aggregator", license="MIT", long_description=long_description, url=__url__, )
import os from setuptools import find_packages, setup from great import __url__ with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme: long_description = readme.read() classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] setup( name="great", packages=find_packages() + ["twisted.plugins"], setup_requires=["setuptools_scm"], use_scm_version=True, install_requires=[ "Alchimia", "appdirs", "attrs", "filesystems", "hyperlink", "Minion", "pytoml", "SQLAlchemy", "Twisted", "txmusicbrainz", ], author="Julian Berman", author_email="[email protected]", classifiers=classifiers, description="A ratings aggregator", license="MIT", long_description=long_description, url=__url__, )
Make sure to install the tap.
Make sure to install the tap.
Python
mit
Julian/Great,Julian/Great,Julian/Great
python
## Code Before: import os from setuptools import find_packages, setup from great import __url__ with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme: long_description = readme.read() classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] setup( name="great", packages=find_packages(), setup_requires=["setuptools_scm"], use_scm_version=True, install_requires=[ "Alchimia", "appdirs", "attrs", "filesystems", "hyperlink", "Minion", "pytoml", "SQLAlchemy", "Twisted", "txmusicbrainz", ], author="Julian Berman", author_email="[email protected]", classifiers=classifiers, description="A ratings aggregator", license="MIT", long_description=long_description, url=__url__, ) ## Instruction: Make sure to install the tap. ## Code After: import os from setuptools import find_packages, setup from great import __url__ with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme: long_description = readme.read() classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] setup( name="great", packages=find_packages() + ["twisted.plugins"], setup_requires=["setuptools_scm"], use_scm_version=True, install_requires=[ "Alchimia", "appdirs", "attrs", "filesystems", "hyperlink", "Minion", "pytoml", "SQLAlchemy", "Twisted", "txmusicbrainz", ], author="Julian Berman", author_email="[email protected]", classifiers=classifiers, description="A ratings aggregator", license="MIT", long_description=long_description, url=__url__, )
... setup( name="great", packages=find_packages() + ["twisted.plugins"], setup_requires=["setuptools_scm"], use_scm_version=True, ...
9442338d329e7f87d6265e0b0d3728a0df18d945
viper/lexer/reserved_tokens.py
viper/lexer/reserved_tokens.py
RESERVED_NAMES = { 'def', 'pass', 'return', 'class', 'interface', 'data', 'if', 'elif', 'else', 'or', 'and', 'not', 'for', 'true', 'false', } RESERVED_CLASSES = set()
RESERVED_NAMES = { 'def', 'pass', 'return', 'class', 'interface', 'data', 'static', 'public', 'private', 'protected', 'module', 'if', 'elif', 'else', 'or', 'and', 'not', 'for', 'true', 'false', } RESERVED_CLASSES = set()
Update list of reserved tokens
Update list of reserved tokens
Python
apache-2.0
pdarragh/Viper
python
## Code Before: RESERVED_NAMES = { 'def', 'pass', 'return', 'class', 'interface', 'data', 'if', 'elif', 'else', 'or', 'and', 'not', 'for', 'true', 'false', } RESERVED_CLASSES = set() ## Instruction: Update list of reserved tokens ## Code After: RESERVED_NAMES = { 'def', 'pass', 'return', 'class', 'interface', 'data', 'static', 'public', 'private', 'protected', 'module', 'if', 'elif', 'else', 'or', 'and', 'not', 'for', 'true', 'false', } RESERVED_CLASSES = set()
# ... existing code ... 'class', 'interface', 'data', 'static', 'public', 'private', 'protected', 'module', 'if', 'elif', 'else', # ... rest of the code ...
9f557a7632a1cd3b16dd6db79c7bb6a61ff79791
v0/tig.py
v0/tig.py
import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main()
import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) print args if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main()
Print parsed args, useful for demo.
Print parsed args, useful for demo.
Python
mit
bravegnu/tiny-git,jamesmortensen/tiny-git,jamesmortensen/tiny-git,bravegnu/tiny-git
python
## Code Before: import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main() ## Instruction: Print parsed args, useful for demo. ## Code After: import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) print args if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main()
... def main(): args = docopt.docopt(__doc__) print args if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: ...
b9cf2145097f8d1c702183a09bf2d54f669e2218
skimage/filter/__init__.py
skimage/filter/__init__.py
from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive']
from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive from . import rank __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive', 'rank']
Add filter.rank to __all__ of filter package
Add filter.rank to __all__ of filter package
Python
bsd-3-clause
michaelpacer/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,michaelpacer/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,keflavich/scikit-image,chintak/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,Britefury/scikit-image,bennlich/scikit-image,ofgulban/scikit-image,dpshelio/scikit-image,dpshelio/scikit-image,almarklein/scikit-image,keflavich/scikit-image,Midafi/scikit-image,pratapvardhan/scikit-image,emon10005/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,jwiggins/scikit-image,almarklein/scikit-image,youprofit/scikit-image,SamHames/scikit-image,GaZ3ll3/scikit-image,Midafi/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,SamHames/scikit-image,blink1073/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,chintak/scikit-image,newville/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,SamHames/scikit-image,blink1073/scikit-image,rjeli/scikit-image,newville/scikit-image,paalge/scikit-image,paalge/scikit-image,almarklein/scikit-image,bsipocz/scikit-image,paalge/scikit-image,emon10005/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,michaelaye/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,robintw/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,rjeli/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,WarrenWeckesser/scikits-image,chriscrosscutler/scikit-image
python
## Code Before: from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive'] ## Instruction: Add filter.rank to __all__ of filter package ## Code After: from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive from . import rank __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive', 'rank']
// ... existing code ... from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive from . import rank __all__ = ['inverse', // ... modified code ... 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive', 'rank'] // ... rest of the code ...
3b4c645792c1a58cdce3dc25171723e7139d66da
workflows/api/permissions.py
workflows/api/permissions.py
from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False
from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] if request.GET.get('preview', '0') == '1': if workflow.public: return True return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False
Return True for preview if workflow public
Return True for preview if workflow public
Python
mit
xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend
python
## Code Before: from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False ## Instruction: Return True for preview if workflow public ## Code After: from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] if request.GET.get('preview', '0') == '1': if workflow.public: return True return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False
# ... existing code ... serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] if request.GET.get('preview', '0') == '1': if workflow.public: return True return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff # ... rest of the code ...
4b6bb7b7d258a9f130b7d10f390f44dec855cc19
admin/src/gui/NewScoville.py
admin/src/gui/NewScoville.py
import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): def __init__(self): pass
import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): pass
Revert "added constructor (testcommit for new git interface)"
Revert "added constructor (testcommit for new git interface)" This reverts commit d5c0252b75e97103d61c3203e2a8d04a061c8a2f.
Python
agpl-3.0
skarphed/skarphed,skarphed/skarphed
python
## Code Before: import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): def __init__(self): pass ## Instruction: Revert "added constructor (testcommit for new git interface)" This reverts commit d5c0252b75e97103d61c3203e2a8d04a061c8a2f. ## Code After: import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): pass
# ... existing code ... builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): pass # ... rest of the code ...
eec8ddc6beb08a02577831b6f64b0455e5c1ef05
local.py
local.py
import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.register() class GNTPNotice(gntp.GNTPNotice): def send(self): print 'Sending Notification' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = [self.headers['Notification-Name']] ) noticeIcon = None if self.headers.get('Notification-Icon',False): resource = self.headers['Notification-Icon'].split('://') #print resource resource = self.resources.get(resource[1],False) #print resource if resource: noticeIcon = resource['Data'] growl.notify( noteType = self.headers['Notification-Name'], title = self.headers['Notification-Title'], description=self.headers['Notification-Text'], icon=noticeIcon )
import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Local Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.register() class GNTPNotice(gntp.GNTPNotice): def send(self): print 'Sending Local Notification' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = [self.headers['Notification-Name']] ) noticeIcon = None if self.headers.get('Notification-Icon',False): resource = self.headers['Notification-Icon'].split('://') #print resource resource = self.resources.get(resource[1],False) #print resource if resource: noticeIcon = resource['Data'] growl.notify( noteType = self.headers['Notification-Name'], title = self.headers['Notification-Title'], description=self.headers['Notification-Text'], )
Disable icon temporarily and adjust the debug print statements
Disable icon temporarily and adjust the debug print statements
Python
mit
kfdm/gntp
python
## Code Before: import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.register() class GNTPNotice(gntp.GNTPNotice): def send(self): print 'Sending Notification' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = [self.headers['Notification-Name']] ) noticeIcon = None if self.headers.get('Notification-Icon',False): resource = self.headers['Notification-Icon'].split('://') #print resource resource = self.resources.get(resource[1],False) #print resource if resource: noticeIcon = resource['Data'] growl.notify( noteType = self.headers['Notification-Name'], title = self.headers['Notification-Title'], description=self.headers['Notification-Text'], icon=noticeIcon ) ## Instruction: Disable icon temporarily and adjust the debug print statements ## Code After: import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Local Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.register() class GNTPNotice(gntp.GNTPNotice): def send(self): print 'Sending Local Notification' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = [self.headers['Notification-Name']] ) noticeIcon = None if self.headers.get('Notification-Icon',False): resource = self.headers['Notification-Icon'].split('://') #print resource resource = self.resources.get(resource[1],False) #print resource if resource: noticeIcon = resource['Data'] growl.notify( noteType = self.headers['Notification-Name'], title = self.headers['Notification-Title'], description=self.headers['Notification-Text'], )
// ... existing code ... class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Local Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, // ... modified code ... class GNTPNotice(gntp.GNTPNotice): def send(self): print 'Sending Local Notification' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = [self.headers['Notification-Name']] ... noteType = self.headers['Notification-Name'], title = self.headers['Notification-Title'], description=self.headers['Notification-Text'], ) // ... rest of the code ...
6988e876ded8bc7c9dd4b30503c98bba34fbafd6
stagemonitor-core/src/main/java/org/stagemonitor/core/instrument/StagemonitorRuntimeAgentAttacherDriver.java
stagemonitor-core/src/main/java/org/stagemonitor/core/instrument/StagemonitorRuntimeAgentAttacherDriver.java
package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
Remove @Override annotation from 1.7 added method
Remove @Override annotation from 1.7 added method
Java
apache-2.0
sdgdsffdsfff/stagemonitor,elevennl/stagemonitor,stagemonitor/stagemonitor,trampi/stagemonitor,hexdecteam/stagemonitor,marcust/stagemonitor,sdgdsffdsfff/stagemonitor,stagemonitor/stagemonitor,elevennl/stagemonitor,hexdecteam/stagemonitor,glamarre360/stagemonitor,elevennl/stagemonitor,elevennl/stagemonitor,glamarre360/stagemonitor,trampi/stagemonitor,sdgdsffdsfff/stagemonitor,trampi/stagemonitor,marcust/stagemonitor,glamarre360/stagemonitor,stagemonitor/stagemonitor,marcust/stagemonitor,hexdecteam/stagemonitor,hexdecteam/stagemonitor,glamarre360/stagemonitor,sdgdsffdsfff/stagemonitor,trampi/stagemonitor,stagemonitor/stagemonitor,marcust/stagemonitor
java
## Code Before: package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } } ## Instruction: Remove @Override annotation from 1.7 added method ## Code After: package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
# ... existing code ... return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } # ... rest of the code ...
4903f961a88751e684f703aaf08511cd5c486a84
wangle/concurrent/FiberIOExecutor.h
wangle/concurrent/FiberIOExecutor.h
/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/experimental/fibers/FiberManagerMap.h> #include <wangle/concurrent/IOExecutor.h> namespace wangle { /** * @class FiberIOExecutor * @brief An IOExecutor that executes funcs under mapped fiber context * * A FiberIOExecutor wraps an IOExecutor, but executes funcs on the FiberManager * mapped to the underlying IOExector's event base. */ class FiberIOExecutor : public IOExecutor { public: explicit FiberIOExecutor( const std::shared_ptr<IOExecutor>& ioExecutor) : ioExecutor_(ioExecutor) {} virtual void add(std::function<void()> f) override { auto eventBase = ioExecutor_->getEventBase(); getFiberManager(*eventBase).add(std::move(f)); } virtual EventBase* getEventBase() override { return ioExecutor_->getEventBase(); } private: std::shared_ptr<IOExecutor> ioExecutor_; }; } // namespace wangle
/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/fibers/FiberManagerMap.h> #include <wangle/concurrent/IOExecutor.h> namespace wangle { /** * @class FiberIOExecutor * @brief An IOExecutor that executes funcs under mapped fiber context * * A FiberIOExecutor wraps an IOExecutor, but executes funcs on the FiberManager * mapped to the underlying IOExector's event base. */ class FiberIOExecutor : public IOExecutor { public: explicit FiberIOExecutor( const std::shared_ptr<IOExecutor>& ioExecutor) : ioExecutor_(ioExecutor) {} virtual void add(std::function<void()> f) override { auto eventBase = ioExecutor_->getEventBase(); getFiberManager(*eventBase).add(std::move(f)); } virtual EventBase* getEventBase() override { return ioExecutor_->getEventBase(); } private: std::shared_ptr<IOExecutor> ioExecutor_; }; } // namespace wangle
Move fibers out of experimental
Move fibers out of experimental Summary: folly::fibers have been used by mcrouter for more than 2 years, so not really experimental. Reviewed By: pavlo-fb Differential Revision: D3320595 fbshipit-source-id: 68188f92b71a4206d57222993848521ca5437ef5
C
apache-2.0
facebook/wangle,facebook/wangle,facebook/wangle
c
## Code Before: /* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/experimental/fibers/FiberManagerMap.h> #include <wangle/concurrent/IOExecutor.h> namespace wangle { /** * @class FiberIOExecutor * @brief An IOExecutor that executes funcs under mapped fiber context * * A FiberIOExecutor wraps an IOExecutor, but executes funcs on the FiberManager * mapped to the underlying IOExector's event base. */ class FiberIOExecutor : public IOExecutor { public: explicit FiberIOExecutor( const std::shared_ptr<IOExecutor>& ioExecutor) : ioExecutor_(ioExecutor) {} virtual void add(std::function<void()> f) override { auto eventBase = ioExecutor_->getEventBase(); getFiberManager(*eventBase).add(std::move(f)); } virtual EventBase* getEventBase() override { return ioExecutor_->getEventBase(); } private: std::shared_ptr<IOExecutor> ioExecutor_; }; } // namespace wangle ## Instruction: Move fibers out of experimental Summary: folly::fibers have been used by mcrouter for more than 2 years, so not really experimental. Reviewed By: pavlo-fb Differential Revision: D3320595 fbshipit-source-id: 68188f92b71a4206d57222993848521ca5437ef5 ## Code After: /* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/fibers/FiberManagerMap.h> #include <wangle/concurrent/IOExecutor.h> namespace wangle { /** * @class FiberIOExecutor * @brief An IOExecutor that executes funcs under mapped fiber context * * A FiberIOExecutor wraps an IOExecutor, but executes funcs on the FiberManager * mapped to the underlying IOExector's event base. */ class FiberIOExecutor : public IOExecutor { public: explicit FiberIOExecutor( const std::shared_ptr<IOExecutor>& ioExecutor) : ioExecutor_(ioExecutor) {} virtual void add(std::function<void()> f) override { auto eventBase = ioExecutor_->getEventBase(); getFiberManager(*eventBase).add(std::move(f)); } virtual EventBase* getEventBase() override { return ioExecutor_->getEventBase(); } private: std::shared_ptr<IOExecutor> ioExecutor_; }; } // namespace wangle
... #pragma once #include <folly/fibers/FiberManagerMap.h> #include <wangle/concurrent/IOExecutor.h> namespace wangle { ...
cc09da295d61965af1552b35b7ece0caf4e5a399
accountant/interface/forms.py
accountant/interface/forms.py
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, }
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, } widgets = { 'game': forms.HiddenInput(), }
Hide Game ID input since it is automatically set
Hide Game ID input since it is automatically set
Python
mit
XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant
python
## Code Before: from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, } ## Instruction: Hide Game ID input since it is automatically set ## Code After: from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, } widgets = { 'game': forms.HiddenInput(), }
# ... existing code ... error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, } widgets = { 'game': forms.HiddenInput(), } # ... rest of the code ...
3072b6dd724255c3fba3bc6f837ec823d507e321
grammpy_transforms/contextfree.py
grammpy_transforms/contextfree.py
from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar)
from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, transform_grammar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) @staticmethod def remove_useless_symbols(grammar: Grammar, transform_grammar=False, *, perform_unreachable_alg = True, perform_nongenerating_alg = True) -> Grammar: if perform_nongenerating_alg: grammar = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) transform_grammar = False if perform_unreachable_alg: grammar = ContextFree.remove_unreachable_symbols(grammar, transform_grammar=transform_grammar) return grammar
Implement alg to remove useless symbols
Implement alg to remove useless symbols
Python
mit
PatrikValkovic/grammpy
python
## Code Before: from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) ## Instruction: Implement alg to remove useless symbols ## Code After: from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, transform_grammar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) @staticmethod def remove_useless_symbols(grammar: Grammar, transform_grammar=False, *, perform_unreachable_alg = True, perform_nongenerating_alg = True) -> Grammar: if perform_nongenerating_alg: grammar = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) transform_grammar = False if perform_unreachable_alg: grammar = ContextFree.remove_unreachable_symbols(grammar, transform_grammar=transform_grammar) return grammar
# ... existing code ... return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, transform_grammar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) @staticmethod def remove_useless_symbols(grammar: Grammar, transform_grammar=False, *, perform_unreachable_alg = True, perform_nongenerating_alg = True) -> Grammar: if perform_nongenerating_alg: grammar = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) transform_grammar = False if perform_unreachable_alg: grammar = ContextFree.remove_unreachable_symbols(grammar, transform_grammar=transform_grammar) return grammar # ... rest of the code ...
5b8b396d262c1a3629fbb7b5a046090f03d00d9a
app/src/main/java/org/stepik/android/cache/course_list/CourseListQueryCacheDataSourceImpl.kt
app/src/main/java/org/stepik/android/cache/course_list/CourseListQueryCacheDataSourceImpl.kt
package org.stepik.android.cache.course_list import io.reactivex.Completable import io.reactivex.Single import org.stepic.droid.storage.dao.IDao import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery import org.stepik.android.data.course_list.model.CourseListQueryData import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource import org.stepik.android.domain.course_list.model.CourseListQuery import javax.inject.Inject class CourseListQueryCacheDataSourceImpl @Inject constructor( private val courseListQueryDataDao: IDao<CourseListQueryData> ) : CourseListQueryCacheDataSource { override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> = Single.fromCallable { courseListQueryDataDao .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString()) ?.courses } override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable = Completable.fromCallable { courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses)) } }
package org.stepik.android.cache.course_list import io.reactivex.Completable import io.reactivex.Single import org.stepic.droid.storage.dao.IDao import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery import org.stepik.android.data.course_list.model.CourseListQueryData import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource import org.stepik.android.domain.course_list.model.CourseListQuery import javax.inject.Inject class CourseListQueryCacheDataSourceImpl @Inject constructor( private val courseListQueryDataDao: IDao<CourseListQueryData> ) : CourseListQueryCacheDataSource { override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> = Single.fromCallable { courseListQueryDataDao .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString()) ?.courses ?: LongArray(0) } override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable = Completable.fromCallable { courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses)) } }
Return empty LongArray when DB is empty
Return empty LongArray when DB is empty
Kotlin
apache-2.0
StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepik-android
kotlin
## Code Before: package org.stepik.android.cache.course_list import io.reactivex.Completable import io.reactivex.Single import org.stepic.droid.storage.dao.IDao import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery import org.stepik.android.data.course_list.model.CourseListQueryData import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource import org.stepik.android.domain.course_list.model.CourseListQuery import javax.inject.Inject class CourseListQueryCacheDataSourceImpl @Inject constructor( private val courseListQueryDataDao: IDao<CourseListQueryData> ) : CourseListQueryCacheDataSource { override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> = Single.fromCallable { courseListQueryDataDao .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString()) ?.courses } override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable = Completable.fromCallable { courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses)) } } ## Instruction: Return empty LongArray when DB is empty ## Code After: package org.stepik.android.cache.course_list import io.reactivex.Completable import io.reactivex.Single import org.stepic.droid.storage.dao.IDao import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery import org.stepik.android.data.course_list.model.CourseListQueryData import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource import org.stepik.android.domain.course_list.model.CourseListQuery import javax.inject.Inject class CourseListQueryCacheDataSourceImpl @Inject constructor( private val courseListQueryDataDao: IDao<CourseListQueryData> ) : CourseListQueryCacheDataSource { override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> = Single.fromCallable { courseListQueryDataDao .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString()) ?.courses ?: LongArray(0) } override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable = Completable.fromCallable { courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses)) } }
# ... existing code ... courseListQueryDataDao .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString()) ?.courses ?: LongArray(0) } override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable = # ... rest of the code ...
3697b3c702378bcbcea44f117f2b339d519cab63
android/app/src/main/java/com/google/firebase/codelab/friendlychat/mvvm/ui/base/BindingAdapter.java
android/app/src/main/java/com/google/firebase/codelab/friendlychat/mvvm/ui/base/BindingAdapter.java
package com.google.firebase.codelab.friendlychat.mvvm.ui.base; import com.bumptech.glide.Glide; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by VTCA on 6/19/2016. * keyword: databinding dapter */ public class BindingAdapter { @android.databinding.BindingAdapter("app:avatar") public static void setAvatar(CircleImageView view, String avatar) { Glide.with(view.getContext()) .load(avatar) .into(view); } }
package com.google.firebase.codelab.friendlychat.mvvm.ui.base; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import com.bumptech.glide.Glide; import com.google.firebase.codelab.friendlychat.R; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by VTCA on 6/19/2016. * keyword: databinding dapter */ public class BindingAdapter { @android.databinding.BindingAdapter("app:avatar") public static void setAvatar(CircleImageView view, String avatar) { if(TextUtils.isEmpty(avatar)){ view.setImageDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.ic_account_circle_black_36dp)); }else{ Glide.with(view.getContext()) .load(avatar) .into(view); } } }
Fix error when Avatar is empty
Fix error when Avatar is empty
Java
apache-2.0
letrungkien0210/friendlychat,letrungkien0210/friendlychat,letrungkien0210/friendlychat,letrungkien0210/friendlychat,letrungkien0210/friendlychat
java
## Code Before: package com.google.firebase.codelab.friendlychat.mvvm.ui.base; import com.bumptech.glide.Glide; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by VTCA on 6/19/2016. * keyword: databinding dapter */ public class BindingAdapter { @android.databinding.BindingAdapter("app:avatar") public static void setAvatar(CircleImageView view, String avatar) { Glide.with(view.getContext()) .load(avatar) .into(view); } } ## Instruction: Fix error when Avatar is empty ## Code After: package com.google.firebase.codelab.friendlychat.mvvm.ui.base; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import com.bumptech.glide.Glide; import com.google.firebase.codelab.friendlychat.R; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by VTCA on 6/19/2016. * keyword: databinding dapter */ public class BindingAdapter { @android.databinding.BindingAdapter("app:avatar") public static void setAvatar(CircleImageView view, String avatar) { if(TextUtils.isEmpty(avatar)){ view.setImageDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.ic_account_circle_black_36dp)); }else{ Glide.with(view.getContext()) .load(avatar) .into(view); } } }
// ... existing code ... package com.google.firebase.codelab.friendlychat.mvvm.ui.base; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import com.bumptech.glide.Glide; import com.google.firebase.codelab.friendlychat.R; import de.hdodenhof.circleimageview.CircleImageView; // ... modified code ... @android.databinding.BindingAdapter("app:avatar") public static void setAvatar(CircleImageView view, String avatar) { if(TextUtils.isEmpty(avatar)){ view.setImageDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.ic_account_circle_black_36dp)); }else{ Glide.with(view.getContext()) .load(avatar) .into(view); } } } // ... rest of the code ...
ea026eeeaae0ee30a5f3a4cb9f8cc2a9d1c37e6c
jackrabbit/utils.py
jackrabbit/utils.py
import collections def is_callable(o): return isinstance(o, collections.Callable)
import collections import sys if sys.platform == 'win32': from time import clock as time else: from time import time def is_callable(o): return isinstance(o, collections.Callable)
Add platform dependent time import for best resolution.
Add platform dependent time import for best resolution.
Python
mit
cbigler/jackrabbit
python
## Code Before: import collections def is_callable(o): return isinstance(o, collections.Callable) ## Instruction: Add platform dependent time import for best resolution. ## Code After: import collections import sys if sys.platform == 'win32': from time import clock as time else: from time import time def is_callable(o): return isinstance(o, collections.Callable)
... import collections import sys if sys.platform == 'win32': from time import clock as time else: from time import time def is_callable(o): ...
f1649dd4c544ddd5dec0c738cd212e197d899526
src/structures/data/actions/library/SetGlobalVariable.java
src/structures/data/actions/library/SetGlobalVariable.java
package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.DoubleParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("EditVariableKey"), new DoubleParam("EditVariableValue"), new CheckboxParam("RelativeVariable?")); } @Override public String getTitle() { return "SetGlobalVariable"; } @Override public String getDescription() { if((boolean) get("RelativeVariable?").getValue()){ return String.format("change %s by %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } else{ return String.format("make %s equal %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } } @Override protected String getSyntax() { return "library.set_variable('%s', %f, %b);"; } }
package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.GroovyParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("Variable Name"), new GroovyParam("Value"), new CheckboxParam("Relative")); } @Override public String getTitle() { return "Set Global Var"; } @Override public String getDescription() { if ((boolean) get("Relative").getValue()) { return String.format("Change global '%s' by %s", get("Variable Name").getValue(), get("Value").getValue()); } else{ return String.format("Set global '%s' to %s", get("Variable Name").getValue(), get("Value").getValue()); } } @Override public String compileSyntax() { if ((boolean) get("Relative").getValue()) { return String.format("globals.%s = globals.%s + %s;\n", get("Variable Name").getValue(), get("Variable Name").getValue(), get("Value").getValue()); } else { return String.format("globals.%s = %s;\n", get("Variable Name").getValue(), get("Value").getValue()); } } @Override protected String getSyntax() { return null; } }
Set Global Variable action created
Set Global Variable action created
Java
mit
ankitkayastha/VOOGASalad,nrg12/VOOGASalad
java
## Code Before: package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.DoubleParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("EditVariableKey"), new DoubleParam("EditVariableValue"), new CheckboxParam("RelativeVariable?")); } @Override public String getTitle() { return "SetGlobalVariable"; } @Override public String getDescription() { if((boolean) get("RelativeVariable?").getValue()){ return String.format("change %s by %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } else{ return String.format("make %s equal %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } } @Override protected String getSyntax() { return "library.set_variable('%s', %f, %b);"; } } ## Instruction: Set Global Variable action created ## Code After: package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.GroovyParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("Variable Name"), new GroovyParam("Value"), new CheckboxParam("Relative")); } @Override public String getTitle() { return "Set Global Var"; } @Override public String getDescription() { if ((boolean) get("Relative").getValue()) { return String.format("Change global '%s' by %s", get("Variable Name").getValue(), get("Value").getValue()); } else{ return String.format("Set global '%s' to %s", get("Variable Name").getValue(), get("Value").getValue()); } } @Override public String compileSyntax() { if ((boolean) get("Relative").getValue()) { return String.format("globals.%s = globals.%s + %s;\n", get("Variable Name").getValue(), get("Variable Name").getValue(), get("Value").getValue()); } else { return String.format("globals.%s = %s;\n", get("Variable Name").getValue(), get("Value").getValue()); } } @Override protected String getSyntax() { return null; } }
# ... existing code ... import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.GroovyParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("Variable Name"), new GroovyParam("Value"), new CheckboxParam("Relative")); } @Override public String getTitle() { return "Set Global Var"; } @Override public String getDescription() { if ((boolean) get("Relative").getValue()) { return String.format("Change global '%s' by %s", get("Variable Name").getValue(), get("Value").getValue()); } else{ return String.format("Set global '%s' to %s", get("Variable Name").getValue(), get("Value").getValue()); } } @Override public String compileSyntax() { if ((boolean) get("Relative").getValue()) { return String.format("globals.%s = globals.%s + %s;\n", get("Variable Name").getValue(), get("Variable Name").getValue(), get("Value").getValue()); } else { return String.format("globals.%s = %s;\n", get("Variable Name").getValue(), get("Value").getValue()); } } @Override protected String getSyntax() { return null; } } # ... rest of the code ...
c568f4d3ea475f341490bc81e89c28016e8412a2
corehq/apps/locations/dbaccessors.py
corehq/apps/locations/dbaccessors.py
from corehq.apps.users.models import CommCareUser def _users_by_location(location_id, include_docs): return CommCareUser.view( 'locations/users_by_location_id', startkey=[location_id], endkey=[location_id, {}], include_docs=include_docs, ).all() def get_users_by_location_id(location_id): """ Get all users for a given location """ return _users_by_location(location_id, include_docs=True) def get_user_ids_by_location(location_id): return [user['id'] for user in _users_by_location(location_id, include_docs=False)]
from corehq.apps.users.models import CommCareUser def _users_by_location(location_id, include_docs, wrap): view = CommCareUser.view if wrap else CommCareUser.get_db().view return view( 'locations/users_by_location_id', startkey=[location_id], endkey=[location_id, {}], include_docs=include_docs, ).all() def get_users_by_location_id(location_id, wrap=True): """ Get all users for a given location """ return _users_by_location(location_id, include_docs=True, wrap=wrap) def get_user_ids_by_location(location_id): return [user['id'] for user in _users_by_location(location_id, include_docs=False, wrap=False)]
Allow getting the unwrapped doc
Allow getting the unwrapped doc
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq
python
## Code Before: from corehq.apps.users.models import CommCareUser def _users_by_location(location_id, include_docs): return CommCareUser.view( 'locations/users_by_location_id', startkey=[location_id], endkey=[location_id, {}], include_docs=include_docs, ).all() def get_users_by_location_id(location_id): """ Get all users for a given location """ return _users_by_location(location_id, include_docs=True) def get_user_ids_by_location(location_id): return [user['id'] for user in _users_by_location(location_id, include_docs=False)] ## Instruction: Allow getting the unwrapped doc ## Code After: from corehq.apps.users.models import CommCareUser def _users_by_location(location_id, include_docs, wrap): view = CommCareUser.view if wrap else CommCareUser.get_db().view return view( 'locations/users_by_location_id', startkey=[location_id], endkey=[location_id, {}], include_docs=include_docs, ).all() def get_users_by_location_id(location_id, wrap=True): """ Get all users for a given location """ return _users_by_location(location_id, include_docs=True, wrap=wrap) def get_user_ids_by_location(location_id): return [user['id'] for user in _users_by_location(location_id, include_docs=False, wrap=False)]
# ... existing code ... from corehq.apps.users.models import CommCareUser def _users_by_location(location_id, include_docs, wrap): view = CommCareUser.view if wrap else CommCareUser.get_db().view return view( 'locations/users_by_location_id', startkey=[location_id], endkey=[location_id, {}], # ... modified code ... ).all() def get_users_by_location_id(location_id, wrap=True): """ Get all users for a given location """ return _users_by_location(location_id, include_docs=True, wrap=wrap) def get_user_ids_by_location(location_id): return [user['id'] for user in _users_by_location(location_id, include_docs=False, wrap=False)] # ... rest of the code ...
04d7e76cf372802e99ff3108cccd836d7aada0df
games/views/installers.py
games/views/installers.py
from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): print "InstallerRevisionListView" installer_id = self.request.parser_context['kwargs']['pk'] versions = [] for version in Version.objects.filter(content_type__model='installer', object_id=installer_id): versions.append(models.InstallerRevision(version.id)) return versions class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] version = models.InstallerRevision(revision_id) return version
from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id)
Simplify Installer revision API views
Simplify Installer revision API views
Python
agpl-3.0
lutris/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website
python
## Code Before: from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): print "InstallerRevisionListView" installer_id = self.request.parser_context['kwargs']['pk'] versions = [] for version in Version.objects.filter(content_type__model='installer', object_id=installer_id): versions.append(models.InstallerRevision(version.id)) return versions class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] version = models.InstallerRevision(revision_id) return version ## Instruction: Simplify Installer revision API views ## Code After: from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id)
# ... existing code ... serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] class InstallerRevisionDetailView(generics.RetrieveAPIView): # ... modified code ... def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id) # ... rest of the code ...
c42e0974424d056e306e3f51e8345f2a9600b2dc
extract_language_package.py
extract_language_package.py
import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) delete_intermediate_files_command = "rm " + full_destination_path + "/*.tar.gz" print(delete_intermediate_files_command) os.system(delete_intermediate_files_command)
import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) inner_delete_command = "rm " + inner_filename print(inner_delete_command) os.system(inner_delete_command)
Update extract language package to use inner delete commands to reduce the amount of space used at any given point in time.
Update extract language package to use inner delete commands to reduce the amount of space used at any given point in time.
Python
mit
brendandc/multilingual-google-image-scraper
python
## Code Before: import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) delete_intermediate_files_command = "rm " + full_destination_path + "/*.tar.gz" print(delete_intermediate_files_command) os.system(delete_intermediate_files_command) ## Instruction: Update extract language package to use inner delete commands to reduce the amount of space used at any given point in time. ## Code After: import optparse import os import glob optparser = optparse.OptionParser() optparser.add_option("-f", "--filename", dest="filename", help="Language package file") optparser.add_option("-d", "--destination", dest="destination", help="Base destination folder") optparser.add_option("-l", "--language", dest="language", help="Language to un-package") (opts, _) = optparser.parse_args() full_destination_path = opts.destination + "/" + opts.language if not os.path.exists(full_destination_path): os.makedirs(full_destination_path) outer_untar_command = "tar -xvf " + opts.filename + " -C " + full_destination_path print(outer_untar_command) os.system(outer_untar_command) for inner_filename in glob.glob(full_destination_path+"/*.tar.gz"): inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) inner_delete_command = "rm " + inner_filename print(inner_delete_command) os.system(inner_delete_command)
// ... existing code ... inner_untar_command = "tar -xvzf " + inner_filename + " -C " + full_destination_path print(inner_untar_command) os.system(inner_untar_command) inner_delete_command = "rm " + inner_filename print(inner_delete_command) os.system(inner_delete_command) // ... rest of the code ...
ffbe699a8435dd0abfb43a37c8528257cdaf386d
pymogilefs/request.py
pymogilefs/request.py
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode class Request: def __init__(self, config, **kwargs): self.config = config self._kwargs = kwargs or {} def __bytes__(self): kwargs = urlencode(self._kwargs) return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8')
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode class Request: def __init__(self, config, **kwargs): self.config = config self._kwargs = kwargs or {} def __bytes__(self): kwargs = urlencode(self._kwargs) return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8') # Python 2.7 compatibility def __str__(self): return self.__bytes__().decode()
Add __str__/__bytes__ Python 2.7 compatibility
Add __str__/__bytes__ Python 2.7 compatibility
Python
mit
bwind/pymogilefs,bwind/pymogilefs
python
## Code Before: try: from urllib.parse import urlencode except ImportError: from urllib import urlencode class Request: def __init__(self, config, **kwargs): self.config = config self._kwargs = kwargs or {} def __bytes__(self): kwargs = urlencode(self._kwargs) return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8') ## Instruction: Add __str__/__bytes__ Python 2.7 compatibility ## Code After: try: from urllib.parse import urlencode except ImportError: from urllib import urlencode class Request: def __init__(self, config, **kwargs): self.config = config self._kwargs = kwargs or {} def __bytes__(self): kwargs = urlencode(self._kwargs) return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8') # Python 2.7 compatibility def __str__(self): return self.__bytes__().decode()
... def __bytes__(self): kwargs = urlencode(self._kwargs) return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8') # Python 2.7 compatibility def __str__(self): return self.__bytes__().decode() ...
ea6a8de791bf200da2fe5e54a9f9ca68314f3489
forum/admin.py
forum/admin.py
from django.contrib import admin from forum.models import Category, Forum, Thread admin.site.register(Category) admin.site.register(Forum) admin.site.register(Thread)
from django.contrib import admin from forum.models import Category, Forum, Thread class ForumInline(admin.StackedInline): model = Forum class CategoryAdmin(admin.ModelAdmin): inlines = [ForumInline] admin.site.register(Category, CategoryAdmin) admin.site.register(Thread)
Modify forums directly in categories.
Modify forums directly in categories.
Python
mit
xfix/NextBoard
python
## Code Before: from django.contrib import admin from forum.models import Category, Forum, Thread admin.site.register(Category) admin.site.register(Forum) admin.site.register(Thread) ## Instruction: Modify forums directly in categories. ## Code After: from django.contrib import admin from forum.models import Category, Forum, Thread class ForumInline(admin.StackedInline): model = Forum class CategoryAdmin(admin.ModelAdmin): inlines = [ForumInline] admin.site.register(Category, CategoryAdmin) admin.site.register(Thread)
# ... existing code ... from django.contrib import admin from forum.models import Category, Forum, Thread class ForumInline(admin.StackedInline): model = Forum class CategoryAdmin(admin.ModelAdmin): inlines = [ForumInline] admin.site.register(Category, CategoryAdmin) admin.site.register(Thread) # ... rest of the code ...
cd1141ddcda08a97311886d93d4ca7e3d1f4a9d6
src/test/java/net/openhft/chronicle/wire/MethodReaderTest.java
src/test/java/net/openhft/chronicle/wire/MethodReaderTest.java
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesUtil; import org.junit.Test; import java.io.IOException; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; interface MockMethods { void method1(MockDto dto); void method2(MockDto dto); } /** * Created by peter on 17/05/2017. */ public class MethodReaderTest { @Test public void readMethods() throws IOException { Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")); Wire wire2 = new TextWire(Bytes.allocateElasticDirect()); // expected Bytes expected = BytesUtil.readFile("methods-in.yaml"); MockMethods writer = wire2.methodWriter(MockMethods.class); MethodReader reader = wire.methodReader(writer); for (int i = 0; i < 2; i++) { assertTrue(reader.readOne()); while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ') wire2.bytes().writeSkip(-1); wire2.bytes().append("---\n"); } assertFalse(reader.readOne()); assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim()); } } class MockDto extends AbstractMarshallable { String field1; double field2; }
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesUtil; import org.junit.Test; import java.io.IOException; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; interface MockMethods { void method1(MockDto dto); void method2(MockDto dto); } /** * Created by peter on 17/05/2017. */ public class MethodReaderTest { @Test public void readMethods() throws IOException { Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")).useTextDocuments(); Wire wire2 = new TextWire(Bytes.allocateElasticDirect()); // expected Bytes expected = BytesUtil.readFile("methods-in.yaml"); MockMethods writer = wire2.methodWriter(MockMethods.class); MethodReader reader = wire.methodReader(writer); for (int i = 0; i < 2; i++) { assertTrue(reader.readOne()); while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ') wire2.bytes().writeSkip(-1); wire2.bytes().append("---\n"); } assertFalse(reader.readOne()); assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim()); } } class MockDto extends AbstractMarshallable { String field1; double field2; }
Allow TextWire to write binary headers as well as plain text.
Allow TextWire to write binary headers as well as plain text.
Java
apache-2.0
OpenHFT/Chronicle-Wire,OpenHFT/Chronicle-Wire
java
## Code Before: package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesUtil; import org.junit.Test; import java.io.IOException; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; interface MockMethods { void method1(MockDto dto); void method2(MockDto dto); } /** * Created by peter on 17/05/2017. */ public class MethodReaderTest { @Test public void readMethods() throws IOException { Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")); Wire wire2 = new TextWire(Bytes.allocateElasticDirect()); // expected Bytes expected = BytesUtil.readFile("methods-in.yaml"); MockMethods writer = wire2.methodWriter(MockMethods.class); MethodReader reader = wire.methodReader(writer); for (int i = 0; i < 2; i++) { assertTrue(reader.readOne()); while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ') wire2.bytes().writeSkip(-1); wire2.bytes().append("---\n"); } assertFalse(reader.readOne()); assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim()); } } class MockDto extends AbstractMarshallable { String field1; double field2; } ## Instruction: Allow TextWire to write binary headers as well as plain text. ## Code After: package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesUtil; import org.junit.Test; import java.io.IOException; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; interface MockMethods { void method1(MockDto dto); void method2(MockDto dto); } /** * Created by peter on 17/05/2017. */ public class MethodReaderTest { @Test public void readMethods() throws IOException { Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")).useTextDocuments(); Wire wire2 = new TextWire(Bytes.allocateElasticDirect()); // expected Bytes expected = BytesUtil.readFile("methods-in.yaml"); MockMethods writer = wire2.methodWriter(MockMethods.class); MethodReader reader = wire.methodReader(writer); for (int i = 0; i < 2; i++) { assertTrue(reader.readOne()); while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ') wire2.bytes().writeSkip(-1); wire2.bytes().append("---\n"); } assertFalse(reader.readOne()); assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim()); } } class MockDto extends AbstractMarshallable { String field1; double field2; }
... public class MethodReaderTest { @Test public void readMethods() throws IOException { Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")).useTextDocuments(); Wire wire2 = new TextWire(Bytes.allocateElasticDirect()); // expected Bytes expected = BytesUtil.readFile("methods-in.yaml"); ...
38f81754a540d7e1212e8b6247aff174aceefced
src/user.c
src/user.c
task blink(); task usercontrol(){ int DY, DT; bool isReset = false; startTask(blink); //Enable Positioning System startTask(positionsystem); while(true){ //Driving DY = threshold(PAIRED_CH2^2 / MAX_POWER, 5); DT = threshold(PAIRED_CH1^2 / MAX_POWER, 5); drive(DY, DT); //Mogo mogo(threshold(PAIRED_CH3, 15)); //Arm arm((PAIRED_BTN6U - PAIRED_BTN6D) * MAX_POWER); //Lift lift((PAIRED_BTN7U - PAIRED_BTN7D) * MAX_POWER); //Intake intake((PAIRED_BTN5U - PAIRED_BTN5D) * MAX_POWER); //Reset (can be done multiple times, only required once) if(SensorValue[resetButton]){ resetAll(); isReset = true; stopTask(blink); SensorValue[resetLED] = false; waitUntil(!SensorValue[resetButton]); } } } task blink(){ while(true){ SensorValue[resetLED] = !SensorValue[resetLED]; wait1Msec(1000); } }
task blink(); task usercontrol(){ int DY, DT; bool isReset = false; startTask(blink); //Enable Positioning System startTask(positionsystem); while(true){ //Driving DY = threshold(PAIRED_CH2^2 / MAX_POWER, 5) + ((PAIRED_BTN8U - PAIRED_BTN8D) * MAX_POWER); DT = threshold(PAIRED_CH1^2 / MAX_POWER, 5) + ((PAIRED_BTN8R - PAIRED_BTN8L) * MAX_POWER); drive(DY, DT); //Mogo mogo(threshold(PAIRED_CH3, 15)); //Arm arm((PAIRED_BTN6U - PAIRED_BTN6D) * MAX_POWER); //Lift lift((PAIRED_BTN7U - PAIRED_BTN7D) * MAX_POWER); //Intake intake((PAIRED_BTN5U - PAIRED_BTN5D) * MAX_POWER); //Reset (can be done multiple times, only required once) if(abs(SensorValue[aclZ]) > 50){ startTask(blink); } if(SensorValue[resetButton]){ resetAll(); isReset = true; stopTask(blink); SensorValue[resetLED] = false; waitUntil(!SensorValue[resetButton]); } } } task blink(){ while(true){ SensorValue[resetLED] = !SensorValue[resetLED]; wait1Msec(1000); } }
Add button driving and reset encoder warning when bot picked up
Add button driving and reset encoder warning when bot picked up
C
mit
18moorei/code-red-in-the-zone
c
## Code Before: task blink(); task usercontrol(){ int DY, DT; bool isReset = false; startTask(blink); //Enable Positioning System startTask(positionsystem); while(true){ //Driving DY = threshold(PAIRED_CH2^2 / MAX_POWER, 5); DT = threshold(PAIRED_CH1^2 / MAX_POWER, 5); drive(DY, DT); //Mogo mogo(threshold(PAIRED_CH3, 15)); //Arm arm((PAIRED_BTN6U - PAIRED_BTN6D) * MAX_POWER); //Lift lift((PAIRED_BTN7U - PAIRED_BTN7D) * MAX_POWER); //Intake intake((PAIRED_BTN5U - PAIRED_BTN5D) * MAX_POWER); //Reset (can be done multiple times, only required once) if(SensorValue[resetButton]){ resetAll(); isReset = true; stopTask(blink); SensorValue[resetLED] = false; waitUntil(!SensorValue[resetButton]); } } } task blink(){ while(true){ SensorValue[resetLED] = !SensorValue[resetLED]; wait1Msec(1000); } } ## Instruction: Add button driving and reset encoder warning when bot picked up ## Code After: task blink(); task usercontrol(){ int DY, DT; bool isReset = false; startTask(blink); //Enable Positioning System startTask(positionsystem); while(true){ //Driving DY = threshold(PAIRED_CH2^2 / MAX_POWER, 5) + ((PAIRED_BTN8U - PAIRED_BTN8D) * MAX_POWER); DT = threshold(PAIRED_CH1^2 / MAX_POWER, 5) + ((PAIRED_BTN8R - PAIRED_BTN8L) * MAX_POWER); drive(DY, DT); //Mogo mogo(threshold(PAIRED_CH3, 15)); //Arm arm((PAIRED_BTN6U - PAIRED_BTN6D) * MAX_POWER); //Lift lift((PAIRED_BTN7U - PAIRED_BTN7D) * MAX_POWER); //Intake intake((PAIRED_BTN5U - PAIRED_BTN5D) * MAX_POWER); //Reset (can be done multiple times, only required once) if(abs(SensorValue[aclZ]) > 50){ startTask(blink); } if(SensorValue[resetButton]){ resetAll(); isReset = true; stopTask(blink); SensorValue[resetLED] = false; waitUntil(!SensorValue[resetButton]); } } } task blink(){ while(true){ SensorValue[resetLED] = !SensorValue[resetLED]; wait1Msec(1000); } }
# ... existing code ... while(true){ //Driving DY = threshold(PAIRED_CH2^2 / MAX_POWER, 5) + ((PAIRED_BTN8U - PAIRED_BTN8D) * MAX_POWER); DT = threshold(PAIRED_CH1^2 / MAX_POWER, 5) + ((PAIRED_BTN8R - PAIRED_BTN8L) * MAX_POWER); drive(DY, DT); //Mogo # ... modified code ... intake((PAIRED_BTN5U - PAIRED_BTN5D) * MAX_POWER); //Reset (can be done multiple times, only required once) if(abs(SensorValue[aclZ]) > 50){ startTask(blink); } if(SensorValue[resetButton]){ resetAll(); isReset = true; # ... rest of the code ...
317926c18ac2e139d2018acd767d10b4f53428f3
installer/installer_config/views.py
installer/installer_config/views.py
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
Remove unneeded post method from CreateEnvProfile view
Remove unneeded post method from CreateEnvProfile view
Python
mit
ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer
python
## Code Before: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response ## Instruction: Remove unneeded post method from CreateEnvProfile view ## Code After: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
// ... existing code ... from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile // ... modified code ... form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile ... def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response // ... rest of the code ...
9651c0278d93bf5c4620e198baac975f0c84e9a0
src/unittest/stattestmain.py
src/unittest/stattestmain.py
def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.initText("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Reset to put the stats in a consistent state. m5.stats.reset() stattest_run() m5.stats.dump()
def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.addStatVisitor("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Reset to put the stats in a consistent state. m5.stats.reset() stattest_run() m5.stats.dump()
Fix the stats unit test.
tests: Fix the stats unit test. This has been broken since February. The interface for opening initializing where the stats output should go was changed, but the test wasn't updated. Change-Id: I54bd8be15bf870352d5fcfad95ded28d87c7cc5a Reviewed-on: https://gem5-review.googlesource.com/6001 Reviewed-by: Andreas Sandberg <[email protected]> Maintainer: Andreas Sandberg <[email protected]>
Python
bsd-3-clause
TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu
python
## Code Before: def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.initText("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Reset to put the stats in a consistent state. m5.stats.reset() stattest_run() m5.stats.dump() ## Instruction: tests: Fix the stats unit test. This has been broken since February. The interface for opening initializing where the stats output should go was changed, but the test wasn't updated. Change-Id: I54bd8be15bf870352d5fcfad95ded28d87c7cc5a Reviewed-on: https://gem5-review.googlesource.com/6001 Reviewed-by: Andreas Sandberg <[email protected]> Maintainer: Andreas Sandberg <[email protected]> ## Code After: def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.addStatVisitor("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Reset to put the stats in a consistent state. m5.stats.reset() stattest_run() m5.stats.dump()
... # Initialize the global statistics m5.stats.initSimStats() m5.stats.addStatVisitor("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() ...
1cc10287a7a9666d7478adc1271250ba49663e24
drf_to_s3/tests/test_parsers.py
drf_to_s3/tests/test_parsers.py
import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': '[email protected]', } } self.assertEquals(result, expected)
import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': '[email protected]', } } self.assertEquals(result, expected) @unittest.expectedFailure def test_form_parser_handle_unicode_right(self): unicode_str = u'测试' flattened = { 'user[name]': unicode_str.encode('utf-8'), 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {'encoding':'utf-8'}) expected = { 'user':{ 'name': unicode_str, 'email': u'[email protected]', } } self.assertEquals(result, expected)
Add a failing unit test of unicode parsing
Add a failing unit test of unicode parsing
Python
mit
pombredanne/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3,bodylabs/drf-to-s3,pombredanne/drf-to-s3
python
## Code Before: import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': '[email protected]', } } self.assertEquals(result, expected) ## Instruction: Add a failing unit test of unicode parsing ## Code After: import unittest, urllib from rest_framework.compat import BytesIO class TestParser(unittest.TestCase): def setUp(self): from drf_to_s3.parsers import NestedFormParser self.parser = NestedFormParser() def test_form_parser_unflattens(self): flattened = { 'user[name]': 'Foobar', 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {}) expected = { 'user': { 'name': 'Foobar', 'email': '[email protected]', } } self.assertEquals(result, expected) @unittest.expectedFailure def test_form_parser_handle_unicode_right(self): unicode_str = u'测试' flattened = { 'user[name]': unicode_str.encode('utf-8'), 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {'encoding':'utf-8'}) expected = { 'user':{ 'name': unicode_str, 'email': u'[email protected]', } } self.assertEquals(result, expected)
// ... existing code ... } } self.assertEquals(result, expected) @unittest.expectedFailure def test_form_parser_handle_unicode_right(self): unicode_str = u'测试' flattened = { 'user[name]': unicode_str.encode('utf-8'), 'user[email]': '[email protected]', } stream = BytesIO(urllib.urlencode(flattened)) result = self.parser.parse(stream, 'application/x-www-form-urlencoded', {'encoding':'utf-8'}) expected = { 'user':{ 'name': unicode_str, 'email': u'[email protected]', } } self.assertEquals(result, expected) // ... rest of the code ...
d5a578e6b72fae3c92827895055ed32baf8aa806
coney/response_codes.py
coney/response_codes.py
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
Add additional codes used by server implementation
Add additional codes used by server implementation
Python
mit
cbigler/jackrabbit
python
## Code Before: class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code' ## Instruction: Add additional codes used by server implementation ## Code After: class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
... RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod ...
a5c1a854d758c11c0abe636c0ecabe5a1a01ed29
squidb-tests/src/com/yahoo/squidb/test/TestNonIntegerPrimaryKeySpec.java
squidb-tests/src/com/yahoo/squidb/test/TestNonIntegerPrimaryKeySpec.java
package com.yahoo.squidb.test; import com.yahoo.squidb.annotations.ColumnSpec; import com.yahoo.squidb.annotations.PrimaryKey; import com.yahoo.squidb.annotations.TableModelSpec; @TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey") public class TestNonIntegerPrimaryKeySpec { @PrimaryKey @ColumnSpec(constraints = "NOT NULL") String key; String value; }
package com.yahoo.squidb.test; import com.yahoo.squidb.annotations.ColumnSpec; import com.yahoo.squidb.annotations.PrimaryKey; import com.yahoo.squidb.annotations.TableModelSpec; @TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey") public class TestNonIntegerPrimaryKeySpec { @PrimaryKey @ColumnSpec(name = "keyCol", constraints = "NOT NULL") String key; String value; }
Fix a column name warning in the unit tests generated by our own validation
Fix a column name warning in the unit tests generated by our own validation
Java
apache-2.0
yahoo/squidb,yahoo/squidb,yahoo/squidb,yahoo/squidb,yahoo/squidb
java
## Code Before: package com.yahoo.squidb.test; import com.yahoo.squidb.annotations.ColumnSpec; import com.yahoo.squidb.annotations.PrimaryKey; import com.yahoo.squidb.annotations.TableModelSpec; @TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey") public class TestNonIntegerPrimaryKeySpec { @PrimaryKey @ColumnSpec(constraints = "NOT NULL") String key; String value; } ## Instruction: Fix a column name warning in the unit tests generated by our own validation ## Code After: package com.yahoo.squidb.test; import com.yahoo.squidb.annotations.ColumnSpec; import com.yahoo.squidb.annotations.PrimaryKey; import com.yahoo.squidb.annotations.TableModelSpec; @TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey") public class TestNonIntegerPrimaryKeySpec { @PrimaryKey @ColumnSpec(name = "keyCol", constraints = "NOT NULL") String key; String value; }
... public class TestNonIntegerPrimaryKeySpec { @PrimaryKey @ColumnSpec(name = "keyCol", constraints = "NOT NULL") String key; String value; ...
156c049cc3965f969ee252dc5859cf0713bcbe27
grip/__init__.py
grip/__init__.py
__version__ = '1.2.0' from . import command from .server import default_filenames, serve from .renderer import render_content, render_page
__version__ = '1.2.0' from . import command from .renderer import render_content, render_page from .server import default_filenames, create_app, serve from .exporter import export
Add create_app and export to API.
Add create_app and export to API.
Python
mit
jbarreras/grip,jbarreras/grip,joeyespo/grip,mgoddard-pivotal/grip,ssundarraj/grip,ssundarraj/grip,mgoddard-pivotal/grip,joeyespo/grip
python
## Code Before: __version__ = '1.2.0' from . import command from .server import default_filenames, serve from .renderer import render_content, render_page ## Instruction: Add create_app and export to API. ## Code After: __version__ = '1.2.0' from . import command from .renderer import render_content, render_page from .server import default_filenames, create_app, serve from .exporter import export
// ... existing code ... from . import command from .renderer import render_content, render_page from .server import default_filenames, create_app, serve from .exporter import export // ... rest of the code ...
09e6c915e668c0b41eca75e3105ebac6f8bfcf58
setup.py
setup.py
import os from distutils.core import setup from sphinx.setup_command import BuildDoc import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass={'build_sphinx': BuildDoc}, )
import os from distutils.core import setup try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} except ImportError: print "Sphinx not installed--needed to build documentation" # default cmdclass to None to avoid cmdclass = {} import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass=cmdclass, )
Allow the package to be built without Sphinx being required.
Allow the package to be built without Sphinx being required.
Python
bsd-2-clause
glorpen/webassets,glorpen/webassets,0x1997/webassets,rs/webassets,aconrad/webassets,JDeuce/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,aconrad/webassets,wijerasa/webassets,john2x/webassets,aconrad/webassets,heynemann/webassets,0x1997/webassets,glorpen/webassets,john2x/webassets,wijerasa/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,JDeuce/webassets
python
## Code Before: import os from distutils.core import setup from sphinx.setup_command import BuildDoc import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass={'build_sphinx': BuildDoc}, ) ## Instruction: Allow the package to be built without Sphinx being required. ## Code After: import os from distutils.core import setup try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} except ImportError: print "Sphinx not installed--needed to build documentation" # default cmdclass to None to avoid cmdclass = {} import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass=cmdclass, )
// ... existing code ... import os from distutils.core import setup try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} except ImportError: print "Sphinx not installed--needed to build documentation" # default cmdclass to None to avoid cmdclass = {} import django_assets // ... modified code ... ], packages = find_packages('django_assets'), cmdclass=cmdclass, ) // ... rest of the code ...
cbc8dfb9e472377335c7969369d8f60a4f3692d9
src/main/java/org/dita/dost/platform/ImportXSLAction.java
src/main/java/org/dita/dost/platform/ImportXSLAction.java
/* * This file is part of the DITA Open Toolkit project. * * Copyright 2008 IBM Corporation * * See the accompanying LICENSE file for applicable license. */ package org.dita.dost.platform; import org.dita.dost.util.FileUtils; import org.dita.dost.util.XMLUtils.AttributesBuilder; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * ImportXSLAction class. * */ final class ImportXSLAction extends ImportAction { /** * get result. */ @Override public void getResult(final ContentHandler buf) throws SAXException { for (final FileValue value: valueSet) { final String href = getHref(value); buf.startElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import", new AttributesBuilder() .add("href", href) .build()); buf.endElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import"); } } private String getHref(final FileValue value) { final String templateFilePath = paramTable.get(FileGenerator.PARAM_TEMPLATE); return FileUtils.getRelativeUnixPath(templateFilePath, value.value); } }
/* * This file is part of the DITA Open Toolkit project. * * Copyright 2008 IBM Corporation * * See the accompanying LICENSE file for applicable license. */ package org.dita.dost.platform; import org.dita.dost.util.URLUtils; import org.dita.dost.util.XMLUtils.AttributesBuilder; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import java.net.URI; /** * ImportXSLAction class. * */ final class ImportXSLAction extends ImportAction { /** * get result. */ @Override public void getResult(final ContentHandler buf) throws SAXException { for (final FileValue value: valueSet) { final URI href = getHref(value); buf.startElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import", new AttributesBuilder() .add("href", href.toString()) .build()); buf.endElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import"); } } private URI getHref(final FileValue value) { final URI pluginDir = featureTable.get(value.id).getPluginDir().toURI(); final URI templateFile = URLUtils.toFile(value.value).toURI(); final URI template = pluginDir.relativize(templateFile); return URI.create("plugin:" + value.id + ":" + template); } }
Change XSLT import to use plugin URI scheme
Change XSLT import to use plugin URI scheme Signed-off-by: Jarno Elovirta <[email protected]>
Java
apache-2.0
infotexture/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,shaneataylor/dita-ot,drmacro/dita-ot,infotexture/dita-ot,dita-ot/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,infotexture/dita-ot,infotexture/dita-ot,shaneataylor/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot
java
## Code Before: /* * This file is part of the DITA Open Toolkit project. * * Copyright 2008 IBM Corporation * * See the accompanying LICENSE file for applicable license. */ package org.dita.dost.platform; import org.dita.dost.util.FileUtils; import org.dita.dost.util.XMLUtils.AttributesBuilder; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * ImportXSLAction class. * */ final class ImportXSLAction extends ImportAction { /** * get result. */ @Override public void getResult(final ContentHandler buf) throws SAXException { for (final FileValue value: valueSet) { final String href = getHref(value); buf.startElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import", new AttributesBuilder() .add("href", href) .build()); buf.endElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import"); } } private String getHref(final FileValue value) { final String templateFilePath = paramTable.get(FileGenerator.PARAM_TEMPLATE); return FileUtils.getRelativeUnixPath(templateFilePath, value.value); } } ## Instruction: Change XSLT import to use plugin URI scheme Signed-off-by: Jarno Elovirta <[email protected]> ## Code After: /* * This file is part of the DITA Open Toolkit project. * * Copyright 2008 IBM Corporation * * See the accompanying LICENSE file for applicable license. */ package org.dita.dost.platform; import org.dita.dost.util.URLUtils; import org.dita.dost.util.XMLUtils.AttributesBuilder; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import java.net.URI; /** * ImportXSLAction class. * */ final class ImportXSLAction extends ImportAction { /** * get result. */ @Override public void getResult(final ContentHandler buf) throws SAXException { for (final FileValue value: valueSet) { final URI href = getHref(value); buf.startElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import", new AttributesBuilder() .add("href", href.toString()) .build()); buf.endElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import"); } } private URI getHref(final FileValue value) { final URI pluginDir = featureTable.get(value.id).getPluginDir().toURI(); final URI templateFile = URLUtils.toFile(value.value).toURI(); final URI template = pluginDir.relativize(templateFile); return URI.create("plugin:" + value.id + ":" + template); } }
// ... existing code ... */ package org.dita.dost.platform; import org.dita.dost.util.URLUtils; import org.dita.dost.util.XMLUtils.AttributesBuilder; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import java.net.URI; /** * ImportXSLAction class. // ... modified code ... @Override public void getResult(final ContentHandler buf) throws SAXException { for (final FileValue value: valueSet) { final URI href = getHref(value); buf.startElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import", new AttributesBuilder() .add("href", href.toString()) .build()); buf.endElement("http://www.w3.org/1999/XSL/Transform", "import", "xsl:import"); } } private URI getHref(final FileValue value) { final URI pluginDir = featureTable.get(value.id).getPluginDir().toURI(); final URI templateFile = URLUtils.toFile(value.value).toURI(); final URI template = pluginDir.relativize(templateFile); return URI.create("plugin:" + value.id + ":" + template); } } // ... rest of the code ...
a95b1b2b5331e4248fe1d80244c763df4d3aca41
taiga/urls.py
taiga/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns() urlpatterns += mediafiles_urlpatterns()
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns()
Set prefix to static url patterm call
Set prefix to static url patterm call
Python
agpl-3.0
jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,astagi/taiga-back,coopsource/taiga-back,CMLL/taiga-back,gauravjns/taiga-back,Rademade/taiga-back,EvgeneOskin/taiga-back,dycodedev/taiga-back,CMLL/taiga-back,astagi/taiga-back,dayatz/taiga-back,19kestier/taiga-back,19kestier/taiga-back,coopsource/taiga-back,obimod/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,bdang2012/taiga-back-casting,gauravjns/taiga-back,gam-phon/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,astagi/taiga-back,19kestier/taiga-back,CoolCloud/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,Rademade/taiga-back,forging2012/taiga-back,dycodedev/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,dayatz/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,Tigerwhit4/taiga-back,Tigerwhit4/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,jeffdwyatt/taiga-back,crr0004/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,obimod/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,frt-arch/taiga-back,dycodedev/taiga-back,joshisa/taiga-back,Zaneh-/bearded-tribble-back,astronaut1712/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,Tigerwhit4/taiga-back,gauravjns/taiga-back,CMLL/taiga-back,WALR/taiga-back,joshisa/taiga-back,obimod/taiga-back,jeffdwyatt/taiga-back,forging2012/taiga-back,astagi/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,coopsource/taiga-back,joshisa/taiga-back,crr0004/taiga-back,EvgeneOskin/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,CMLL/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,gam-phon/taiga-back,Tigerwhit4/taiga-back,Rademade/taiga-back,frt-arch/taiga-back,seanchen/taiga-back,WALR/taiga-back,astronaut1712/taiga-back,joshisa/taiga-back,rajiteh/taiga-back
python
## Code Before: from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns() urlpatterns += mediafiles_urlpatterns() ## Instruction: Set prefix to static url patterm call ## Code After: from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', include(admin.site.urls)), ) def mediafiles_urlpatterns(): """ Method for serve media files with runserver. """ _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] from django.views.static import serve return patterns('', (r'^%s(?P<path>.*)$' % 'media', serve, {'document_root': settings.MEDIA_ROOT}) ) urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns()
// ... existing code ... ) urlpatterns += staticfiles_urlpatterns(prefix="/static/") urlpatterns += mediafiles_urlpatterns() // ... rest of the code ...
4c629e16c6dcd5ea78ddccca75c0a5cee602cfa6
setup.py
setup.py
from setuptools import setup, find_packages VERSION="0.5.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="[email protected]", maintainer="UF CTS-IT", maintainer_email="[email protected]", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir = {'nacc': 'nacc'}, packages = find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main" ] } )
from setuptools import setup, find_packages VERSION="0.5.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="[email protected]", maintainer="UF CTS-IT", maintainer_email="[email protected]", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir = {'nacc': 'nacc'}, packages = find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main" ] }, install_requires=[ "cappy @ git+https://github.com/ctsit/[email protected]" ] )
Add cappy to dependency list
Add cappy to dependency list
Python
bsd-2-clause
ctsit/nacculator,ctsit/nacculator,ctsit/nacculator
python
## Code Before: from setuptools import setup, find_packages VERSION="0.5.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="[email protected]", maintainer="UF CTS-IT", maintainer_email="[email protected]", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir = {'nacc': 'nacc'}, packages = find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main" ] } ) ## Instruction: Add cappy to dependency list ## Code After: from setuptools import setup, find_packages VERSION="0.5.0" setup( name="nacculator", version=VERSION, author="Taeber Rapczak", author_email="[email protected]", maintainer="UF CTS-IT", maintainer_email="[email protected]", url="https://github.com/ctsit/nacculator", license="BSD 2-Clause", description="CSV to NACC's UDS3 format converter", keywords=["REDCap", "NACC", "UDS", "Clinical data"], download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION, package_dir = {'nacc': 'nacc'}, packages = find_packages(), entry_points={ "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main" ] }, install_requires=[ "cappy @ git+https://github.com/ctsit/[email protected]" ] )
// ... existing code ... "console_scripts": [ "redcap2nacc = nacc.redcap2nacc:main" ] }, install_requires=[ "cappy @ git+https://github.com/ctsit/[email protected]" ] ) // ... rest of the code ...
3640a8c6057ffac8f8d0f7cd6af8954b4169543d
commands.py
commands.py
from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: _local("python -m unittest discover -t . -s tests") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}")
from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True, fail_fast=False): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: fail_fast = "-f" if fail_fast else "" _local(f"python -m unittest discover -t . -s tests {fail_fast}") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}")
Add --fail-fast flag to test command
Add --fail-fast flag to test command
Python
mit
wylee/django-local-settings
python
## Code Before: from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: _local("python -m unittest discover -t . -s tests") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}") ## Instruction: Add --fail-fast flag to test command ## Code After: from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True, fail_fast=False): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: fail_fast = "-f" if fail_fast else "" _local(f"python -m unittest discover -t . -s tests {fail_fast}") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}")
// ... existing code ... @command def test(with_coverage=True, check=True, fail_fast=False): if with_coverage: _local( "coverage run " // ... modified code ... "&& coverage report" ) else: fail_fast = "-f" if fail_fast else "" _local(f"python -m unittest discover -t . -s tests {fail_fast}") if check: format_code(check=True) lint() // ... rest of the code ...
b2eebbdcc14dd47d6ad8bb385966f13ed13890c1
superdesk/coverages.py
superdesk/coverages.py
from superdesk.base_model import BaseModel def init_app(app): CoverageModel(app=app) def rel(resource, embeddable=False): return { 'type': 'objectid', 'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable} } class CoverageModel(BaseModel): endpoint_name = 'coverages' schema = { 'headline': {'type': 'string'}, 'type': {'type': 'string'}, 'ed_note': {'type': 'string'}, 'scheduled': {'type': 'datetime'}, 'delivery': rel('archive'), 'assigned_user': rel('users', True), 'assigned_desk': rel('desks', True), 'planning_item': rel('planning'), }
from superdesk.base_model import BaseModel def init_app(app): CoverageModel(app=app) def rel(resource, embeddable=False): return { 'type': 'objectid', 'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable} } class CoverageModel(BaseModel): endpoint_name = 'coverages' schema = { 'headline': {'type': 'string'}, 'type': {'type': 'string'}, 'ed_note': {'type': 'string'}, 'scheduled': {'type': 'datetime'}, 'delivery': {'type': 'string'}, 'assigned_user': rel('users', True), 'assigned_desk': rel('desks', True), 'planning_item': {'type': 'string'}, }
Fix data relation not working for custom Guids
Fix data relation not working for custom Guids
Python
agpl-3.0
plamut/superdesk,sivakuna-aap/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk,mugurrus/superdesk,ioanpocol/superdesk,pavlovicnemanja/superdesk,Aca-jov/superdesk,akintolga/superdesk,vied12/superdesk,gbbr/superdesk,fritzSF/superdesk,ancafarcas/superdesk,ioanpocol/superdesk-ntb,mdhaman/superdesk-aap,marwoodandrew/superdesk-aap,darconny/superdesk,akintolga/superdesk-aap,amagdas/superdesk,sivakuna-aap/superdesk,thnkloud9/superdesk,fritzSF/superdesk,akintolga/superdesk-aap,ancafarcas/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,amagdas/superdesk,vied12/superdesk,verifiedpixel/superdesk,superdesk/superdesk-ntb,Aca-jov/superdesk,superdesk/superdesk,akintolga/superdesk,marwoodandrew/superdesk-aap,hlmnrmr/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk-server,pavlovicnemanja/superdesk,liveblog/superdesk,thnkloud9/superdesk,superdesk/superdesk-aap,plamut/superdesk,vied12/superdesk,ioanpocol/superdesk-ntb,plamut/superdesk,darconny/superdesk,sjunaid/superdesk,superdesk/superdesk-aap,amagdas/superdesk,verifiedpixel/superdesk,vied12/superdesk,darconny/superdesk,fritzSF/superdesk,sivakuna-aap/superdesk,amagdas/superdesk,superdesk/superdesk-aap,gbbr/superdesk,marwoodandrew/superdesk-aap,mdhaman/superdesk,petrjasek/superdesk-ntb,sivakuna-aap/superdesk,akintolga/superdesk-aap,akintolga/superdesk,superdesk/superdesk-ntb,fritzSF/superdesk,marwoodandrew/superdesk,marwoodandrew/superdesk,verifiedpixel/superdesk,amagdas/superdesk,marwoodandrew/superdesk-aap,sjunaid/superdesk,petrjasek/superdesk-ntb,sjunaid/superdesk,Aca-jov/superdesk,ioanpocol/superdesk-ntb,petrjasek/superdesk-server,pavlovicnemanja92/superdesk,superdesk/superdesk,ancafarcas/superdesk,superdesk/superdesk,mdhaman/superdesk,fritzSF/superdesk,vied12/superdesk,pavlovicnemanja92/superdesk,petrjasek/superdesk-ntb,hlmnrmr/superdesk,marwoodandrew/superdesk,superdesk/superdesk-ntb,petrjasek/superdesk,hlmnrmr/superdesk,petrjasek/superdesk,mugurrus/superdesk,gbbr/superdesk,pavlovicnemanja92/superdesk,plamut/superdesk,liveblog/superdesk,verifiedpixel/superdesk,petrjasek/superdesk,mdhaman/superdesk,petrjasek/superdesk-ntb,mugurrus/superdesk,mdhaman/superdesk-aap,superdesk/superdesk-aap,superdesk/superdesk-ntb,marwoodandrew/superdesk,pavlovicnemanja92/superdesk,ioanpocol/superdesk,thnkloud9/superdesk,marwoodandrew/superdesk,liveblog/superdesk,mdhaman/superdesk-aap,ioanpocol/superdesk,akintolga/superdesk,plamut/superdesk,liveblog/superdesk,superdesk/superdesk,akintolga/superdesk-aap
python
## Code Before: from superdesk.base_model import BaseModel def init_app(app): CoverageModel(app=app) def rel(resource, embeddable=False): return { 'type': 'objectid', 'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable} } class CoverageModel(BaseModel): endpoint_name = 'coverages' schema = { 'headline': {'type': 'string'}, 'type': {'type': 'string'}, 'ed_note': {'type': 'string'}, 'scheduled': {'type': 'datetime'}, 'delivery': rel('archive'), 'assigned_user': rel('users', True), 'assigned_desk': rel('desks', True), 'planning_item': rel('planning'), } ## Instruction: Fix data relation not working for custom Guids ## Code After: from superdesk.base_model import BaseModel def init_app(app): CoverageModel(app=app) def rel(resource, embeddable=False): return { 'type': 'objectid', 'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable} } class CoverageModel(BaseModel): endpoint_name = 'coverages' schema = { 'headline': {'type': 'string'}, 'type': {'type': 'string'}, 'ed_note': {'type': 'string'}, 'scheduled': {'type': 'datetime'}, 'delivery': {'type': 'string'}, 'assigned_user': rel('users', True), 'assigned_desk': rel('desks', True), 'planning_item': {'type': 'string'}, }
... 'type': {'type': 'string'}, 'ed_note': {'type': 'string'}, 'scheduled': {'type': 'datetime'}, 'delivery': {'type': 'string'}, 'assigned_user': rel('users', True), 'assigned_desk': rel('desks', True), 'planning_item': {'type': 'string'}, } ...
1ec2779f5e4470c6ed19b56d16185c6174ab520c
tests/test_readers.py
tests/test_readers.py
try: import unittest2 except ImportError, e: import unittest as unittest2 import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest2.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } self.assertDictEqual(metadata, expected)
try: import unittest2 as unittest except ImportError, e: import unittest import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } for key, value in expected.items(): self.assertEquals(value, metadata[key], key)
Make the readers tests a bit more verbose.
Make the readers tests a bit more verbose.
Python
agpl-3.0
11craft/pelican,51itclub/pelican,simonjj/pelican,sunzhongwei/pelican,goerz/pelican,51itclub/pelican,Rogdham/pelican,lucasplus/pelican,gymglish/pelican,sunzhongwei/pelican,sunzhongwei/pelican,koobs/pelican,UdeskDeveloper/pelican,ingwinlu/pelican,kennethlyn/pelican,karlcow/pelican,zackw/pelican,alexras/pelican,HyperGroups/pelican,rbarraud/pelican,crmackay/pelican,koobs/pelican,iurisilvio/pelican,jimperio/pelican,zackw/pelican,btnpushnmunky/pelican,ehashman/pelican,douglaskastle/pelican,HyperGroups/pelican,deanishe/pelican,iKevinY/pelican,ls2uper/pelican,karlcow/pelican,Rogdham/pelican,Rogdham/pelican,catdog2/pelican,kernc/pelican,number5/pelican,btnpushnmunky/pelican,crmackay/pelican,iurisilvio/pelican,Natim/pelican,GiovanniMoretti/pelican,avaris/pelican,HyperGroups/pelican,51itclub/pelican,deved69/pelican-1,liyonghelpme/myBlog,abrahamvarricatt/pelican,catdog2/pelican,kernc/pelican,jvehent/pelican,11craft/pelican,douglaskastle/pelican,jvehent/pelican,kennethlyn/pelican,garbas/pelican,gymglish/pelican,levanhien8/pelican,iurisilvio/pelican,lazycoder-ru/pelican,UdeskDeveloper/pelican,douglaskastle/pelican,koobs/pelican,treyhunner/pelican,florianjacob/pelican,Summonee/pelican,JeremyMorgan/pelican,joetboole/pelican,alexras/pelican,kennethlyn/pelican,ehashman/pelican,jo-tham/pelican,Polyconseil/pelican,JeremyMorgan/pelican,deved69/pelican-1,treyhunner/pelican,Scheirle/pelican,jimperio/pelican,deved69/pelican-1,avaris/pelican,Scheirle/pelican,btnpushnmunky/pelican,jo-tham/pelican,joetboole/pelican,fbs/pelican,ls2uper/pelican,eevee/pelican,ingwinlu/pelican,jvehent/pelican,TC01/pelican,talha131/pelican,iKevinY/pelican,kernc/pelican,florianjacob/pelican,getpelican/pelican,karlcow/pelican,goerz/pelican,deanishe/pelican,lazycoder-ru/pelican,levanhien8/pelican,JeremyMorgan/pelican,number5/pelican,liyonghelpme/myBlog,Summonee/pelican,levanhien8/pelican,ionelmc/pelican,janaurka/git-debug-presentiation,joetboole/pelican,ls2uper/pelican,farseerfc/pelican,simonjj/pelican,11craft/pelican,TC01/pelican,alexras/pelican,crmackay/pelican,goerz/pelican,liyonghelpme/myBlog,GiovanniMoretti/pelican,janaurka/git-debug-presentiation,lucasplus/pelican,number5/pelican,simonjj/pelican,abrahamvarricatt/pelican,treyhunner/pelican,eevee/pelican,lazycoder-ru/pelican,rbarraud/pelican,garbas/pelican,janaurka/git-debug-presentiation,arty-name/pelican,liyonghelpme/myBlog,rbarraud/pelican,TC01/pelican,catdog2/pelican,ehashman/pelican,Summonee/pelican,talha131/pelican,Scheirle/pelican,farseerfc/pelican,0xMF/pelican,justinmayer/pelican,florianjacob/pelican,deanishe/pelican,garbas/pelican,gymglish/pelican,abrahamvarricatt/pelican,jimperio/pelican,zackw/pelican,sunzhongwei/pelican,liyonghelpme/myBlog,UdeskDeveloper/pelican,getpelican/pelican,Polyconseil/pelican,lucasplus/pelican,eevee/pelican,GiovanniMoretti/pelican
python
## Code Before: try: import unittest2 except ImportError, e: import unittest as unittest2 import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest2.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } self.assertDictEqual(metadata, expected) ## Instruction: Make the readers tests a bit more verbose. ## Code After: try: import unittest2 as unittest except ImportError, e: import unittest import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } for key, value in expected.items(): self.assertEquals(value, metadata[key], key)
// ... existing code ... try: import unittest2 as unittest except ImportError, e: import unittest import datetime import os // ... modified code ... CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) ... 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } for key, value in expected.items(): self.assertEquals(value, metadata[key], key) // ... rest of the code ...
5b8a39dc0fc5e383c30451a819c8e1542fd6f7ed
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
Remove unnecessary scratch file flag
Remove unnecessary scratch file flag
Python
mit
everyonesdesign/OpenSearchInNewTab
python
## Code Before: import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) ) ## Instruction: Remove unnecessary scratch file flag ## Code After: import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
// ... existing code ... def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() // ... rest of the code ...
582811074db86be964648dc9457855db3549a2b5
data_structures/Disjoint_Set_Union/Python/dsu.py
data_structures/Disjoint_Set_Union/Python/dsu.py
parent=[] size=[] def initialize(n): for i in range(0,n+1): parent.append(i) size.append(1) def find(x): if parent[x] == x: return x else: return find(parent[x]) def join(a,b): p_a = find(a) p_b = find(b) if p_a != p_b: if size[p_a] < size[p_b]: parent[p_a] = p_b size[p_b] += size[p_a] else: parent[p_b] = p_a size[p_a] += size[p_b] ''' Main Program Starts Here ''' n=5 initialize(n) join(1,2) join(2,3) join(4,5) print(find(3))
parent=[] size=[] def initialize(n): for i in range(0,n+1): parent.append(i) size.append(1) def find(x): if parent[x] == x: return x else: return find(parent[x]) def join(a,b): p_a = find(a) p_b = find(b) if p_a != p_b: if size[p_a] < size[p_b]: parent[p_a] = p_b size[p_b] += size[p_a] else: parent[p_b] = p_a size[p_a] += size[p_b] ''' Main Program Starts Here ''' def main(): n=5 initialize(n) join(1,2) assert(find(2) == 1) assert(find(3) == 3) join(2,3) assert(find(3) == 1) assert(find(5) == 5) join(4,5) assert(find(5) == 4) join(3,4) assert(find(5) == 1) if __name__ == '__main__': main()
Test for DSU on Python
Test for DSU on Python
Python
cc0-1.0
ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms
python
## Code Before: parent=[] size=[] def initialize(n): for i in range(0,n+1): parent.append(i) size.append(1) def find(x): if parent[x] == x: return x else: return find(parent[x]) def join(a,b): p_a = find(a) p_b = find(b) if p_a != p_b: if size[p_a] < size[p_b]: parent[p_a] = p_b size[p_b] += size[p_a] else: parent[p_b] = p_a size[p_a] += size[p_b] ''' Main Program Starts Here ''' n=5 initialize(n) join(1,2) join(2,3) join(4,5) print(find(3)) ## Instruction: Test for DSU on Python ## Code After: parent=[] size=[] def initialize(n): for i in range(0,n+1): parent.append(i) size.append(1) def find(x): if parent[x] == x: return x else: return find(parent[x]) def join(a,b): p_a = find(a) p_b = find(b) if p_a != p_b: if size[p_a] < size[p_b]: parent[p_a] = p_b size[p_b] += size[p_a] else: parent[p_b] = p_a size[p_a] += size[p_b] ''' Main Program Starts Here ''' def main(): n=5 initialize(n) join(1,2) assert(find(2) == 1) assert(find(3) == 3) join(2,3) assert(find(3) == 1) assert(find(5) == 5) join(4,5) assert(find(5) == 4) join(3,4) assert(find(5) == 1) if __name__ == '__main__': main()
... ''' Main Program Starts Here ''' def main(): n=5 initialize(n) join(1,2) assert(find(2) == 1) assert(find(3) == 3) join(2,3) assert(find(3) == 1) assert(find(5) == 5) join(4,5) assert(find(5) == 4) join(3,4) assert(find(5) == 1) if __name__ == '__main__': main() ...
6c351939243f758119ed91de299d6d37dc305359
application/main/routes/__init__.py
application/main/routes/__init__.py
from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), ]
from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ]
Expand class name routing target
Expand class name routing target
Python
bsd-3-clause
p22co/edaemon,paulsnar/edaemon,p22co/edaemon,p22co/edaemon,paulsnar/edaemon,paulsnar/edaemon
python
## Code Before: from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), ] ## Instruction: Expand class name routing target ## Code After: from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ]
... (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ] ...
2187b149f96542c898eeefaad74fe6cb41bd31c9
sample-app/src/main/java/org/example/shelf/controller/SecureDocController.java
sample-app/src/main/java/org/example/shelf/controller/SecureDocController.java
package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping("/jsondoc") public String jsondoc() { return "forward:/jsondoc"; } }
package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.ApiResponseBodyType; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.core.model.doc.Livedoc; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.hildan.livedoc.springmvc.converter.LivedocMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping(value = "/jsondoc", produces = LivedocMessageConverter.APPLICATION_LIVEDOC) @ApiResponseBodyType(Livedoc.class) // the String is a forward, Livedoc can't know that public String jsondoc() { return "forward:/jsondoc"; } }
Fix return type of fowarded secure livedoc handler in Sample App
Fix return type of fowarded secure livedoc handler in Sample App
Java
mit
joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc,joffrey-bion/livedoc
java
## Code Before: package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping("/jsondoc") public String jsondoc() { return "forward:/jsondoc"; } } ## Instruction: Fix return type of fowarded secure livedoc handler in Sample App ## Code After: package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.ApiResponseBodyType; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.core.model.doc.Livedoc; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.hildan.livedoc.springmvc.converter.LivedocMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping(value = "/jsondoc", produces = LivedocMessageConverter.APPLICATION_LIVEDOC) @ApiResponseBodyType(Livedoc.class) // the String is a forward, Livedoc can't know that public String jsondoc() { return "forward:/jsondoc"; } }
# ... existing code ... package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.ApiResponseBodyType; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.core.model.doc.Livedoc; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.hildan.livedoc.springmvc.converter.LivedocMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; # ... modified code ... * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping(value = "/jsondoc", produces = LivedocMessageConverter.APPLICATION_LIVEDOC) @ApiResponseBodyType(Livedoc.class) // the String is a forward, Livedoc can't know that public String jsondoc() { return "forward:/jsondoc"; } # ... rest of the code ...
813dd27a2057d2e32726ff6b43ab8ca1411303c7
fabfile.py
fabfile.py
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
Prepare for deploy in deploy script.
Prepare for deploy in deploy script.
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
python
## Code Before: from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn') ## Instruction: Prepare for deploy in deploy script. ## Code After: from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
# ... existing code ... local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') # ... rest of the code ...
87d868283d1972330da593fa605bd05e574cf2fd
sslyze/cli/output_generator.py
sslyze/cli/output_generator.py
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): pass @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None pass @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None pass @abstractmethod def scans_started(self): # type: (None) -> None pass @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None pass @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None pass
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): """The CLI was just started and successfully parsed the command line. """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None """The CLI found a server that it could not connect to; no scans will be performed against this server. """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None """The CLI found a server that it was able to connect to; scans will be run against this server. """ @abstractmethod def scans_started(self): # type: (None) -> None """The CLI has finished testing connectivity with the supplied servers and will now start the scans. """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None """The CLI has finished scanning one single server. """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None """The CLI has finished scanning all the supplied servers and will now exit. """
Document how output generators work
Document how output generators work
Python
agpl-3.0
nabla-c0d3/sslyze
python
## Code Before: from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): pass @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None pass @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None pass @abstractmethod def scans_started(self): # type: (None) -> None pass @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None pass @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None pass ## Instruction: Document how output generators work ## Code After: from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): """The CLI was just started and successfully parsed the command line. """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None """The CLI found a server that it could not connect to; no scans will be performed against this server. """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None """The CLI found a server that it was able to connect to; scans will be run against this server. """ @abstractmethod def scans_started(self): # type: (None) -> None """The CLI has finished testing connectivity with the supplied servers and will now start the scans. """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None """The CLI has finished scanning one single server. """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None """The CLI has finished scanning all the supplied servers and will now exit. """
... @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): """The CLI was just started and successfully parsed the command line. """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None """The CLI found a server that it could not connect to; no scans will be performed against this server. """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None """The CLI found a server that it was able to connect to; scans will be run against this server. """ @abstractmethod def scans_started(self): # type: (None) -> None """The CLI has finished testing connectivity with the supplied servers and will now start the scans. """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None """The CLI has finished scanning one single server. """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None """The CLI has finished scanning all the supplied servers and will now exit. """ ...
368854f495865683da111ee54d882a5e37a33457
nimble-core/src/main/java/com/lenguyenthanh/nimble/view/ViewHelper.java
nimble-core/src/main/java/com/lenguyenthanh/nimble/view/ViewHelper.java
package com.lenguyenthanh.nimble.view; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; public class ViewHelper { private ViewHelper() { } private static ViewHelper instance; public synchronized static ViewHelper getInstance() { if(instance == null){ instance = new ViewHelper(); } return instance; } public Activity getActivity(Context context) { while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (!(context instanceof Activity)) { throw new IllegalStateException( "Expected an activity context, got " + context.getClass().getSimpleName()); } return (Activity) context; } }
package com.lenguyenthanh.nimble.view; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; public final class ViewHelper { private static ViewHelper instance; private ViewHelper() { } public static ViewHelper getInstance() { synchronized (ViewHelper.class) { if (instance == null) { instance = new ViewHelper(); } } return instance; } public Activity getActivity(final Context viewContext) { Context context = viewContext; while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (!(context instanceof Activity)) { throw new IllegalStateException( "Expected an activity context, got " + context.getClass().getSimpleName()); } return (Activity) context; } }
Fix potential bugs follow PMD
Fix potential bugs follow PMD
Java
apache-2.0
lenguyenthanh/nimble
java
## Code Before: package com.lenguyenthanh.nimble.view; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; public class ViewHelper { private ViewHelper() { } private static ViewHelper instance; public synchronized static ViewHelper getInstance() { if(instance == null){ instance = new ViewHelper(); } return instance; } public Activity getActivity(Context context) { while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (!(context instanceof Activity)) { throw new IllegalStateException( "Expected an activity context, got " + context.getClass().getSimpleName()); } return (Activity) context; } } ## Instruction: Fix potential bugs follow PMD ## Code After: package com.lenguyenthanh.nimble.view; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; public final class ViewHelper { private static ViewHelper instance; private ViewHelper() { } public static ViewHelper getInstance() { synchronized (ViewHelper.class) { if (instance == null) { instance = new ViewHelper(); } } return instance; } public Activity getActivity(final Context viewContext) { Context context = viewContext; while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (!(context instanceof Activity)) { throw new IllegalStateException( "Expected an activity context, got " + context.getClass().getSimpleName()); } return (Activity) context; } }
# ... existing code ... import android.content.Context; import android.content.ContextWrapper; public final class ViewHelper { private static ViewHelper instance; private ViewHelper() { } public static ViewHelper getInstance() { synchronized (ViewHelper.class) { if (instance == null) { instance = new ViewHelper(); } } return instance; } public Activity getActivity(final Context viewContext) { Context context = viewContext; while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } # ... rest of the code ...
da22196a8167a57c5edf39578ceece4efd8cfd63
app/views.py
app/views.py
from app import app from flask import make_response @app.route('/') @app.route('/index') def index(): return make_response(open(app.root_path + '/templates/index.html').read())
from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = { 'nickname': 'Marvolo' } # fake user posts = [ # fake array of posts { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title = 'Home', user = user, posts = posts)
Set up mock data for index
Set up mock data for index
Python
apache-2.0
happyraul/tv
python
## Code Before: from app import app from flask import make_response @app.route('/') @app.route('/index') def index(): return make_response(open(app.root_path + '/templates/index.html').read()) ## Instruction: Set up mock data for index ## Code After: from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = { 'nickname': 'Marvolo' } # fake user posts = [ # fake array of posts { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title = 'Home', user = user, posts = posts)
# ... existing code ... from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = { 'nickname': 'Marvolo' } # fake user posts = [ # fake array of posts { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title = 'Home', user = user, posts = posts) # ... rest of the code ...
730f909e146b0ac5dbcf9b8be65cb8f82c68d883
test/CodeGen/x86_64-arguments.c
test/CodeGen/x86_64-arguments.c
// RUN: clang -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { }
// RUN: clang -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t && // RUN: grep 'define void @f7(i32 %a0)' %t char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { } typedef enum { A, B, C } E; void f7(E a0) { }
Add test for enum types
Add test for enum types git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@65540 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang
c
## Code Before: // RUN: clang -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { } ## Instruction: Add test for enum types git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@65540 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: clang -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t && // RUN: grep 'define void @f7(i32 %a0)' %t char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { } typedef enum { A, B, C } E; void f7(E a0) { }
// ... existing code ... // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t && // RUN: grep 'define void @f7(i32 %a0)' %t char f0(void) { } // ... modified code ... void f6(char a0, short a1, int a2, long long a3, void *a4) { } typedef enum { A, B, C } E; void f7(E a0) { } // ... rest of the code ...
009c1d506b5e95b5cb19dbc943f21c8d79fa5f5b
src/test/java/uk/co/sleonard/unison/input/LocationFinderImplTest.java
src/test/java/uk/co/sleonard/unison/input/LocationFinderImplTest.java
/** * LocationFinderImplTest * * @author ${author} * @since 29-May-2016 */ package uk.co.sleonard.unison.input; import java.net.URL; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import uk.co.sleonard.unison.datahandling.DAO.Location; public class LocationFinderImplTest { private LocationFinderImpl finder; @Before public void setUp() throws Exception { final URL resource = this.getClass().getClassLoader().getResource("locationFinder/"); this.finder = new LocationFinderImpl(resource.toString()); } @Test public final void testCreateLocation() { final Location actual = this.finder.createLocation("213.205.194.135"); Assert.assertNotNull(actual); Assert.assertEquals("United Kingdom", actual.getCountry()); Assert.assertEquals("London", actual.getCity()); Assert.assertEquals("GB", actual.getCountryCode()); } }
/** * LocationFinderImplTest * * @author ${author} * @since 29-May-2016 */ package uk.co.sleonard.unison.input; import java.net.URL; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import uk.co.sleonard.unison.datahandling.DAO.Location; public class LocationFinderImplTest { private LocationFinderImpl finder; @Before public void setUp() throws Exception { final URL resource = this.getClass().getClassLoader().getResource("locationFinder/"); this.finder = new LocationFinderImpl(resource.toString()); } @Test public final void testCreateLocation() { final Location actual = this.finder.createLocation("213.205.194.135"); Assert.assertNotNull(actual); Assert.assertEquals("United Kingdom", actual.getCountry()); Assert.assertEquals("London", actual.getCity()); Assert.assertEquals("GB", actual.getCountryCode()); Location actual2 = this.finder.createLocation("wrongipaddress"); Assert.assertNull(actual2.getCountry()); Assert.assertNull(actual2.getCity()); Assert.assertNull(actual2.getCountryCode()); } }
Adjust in test, for to cover my last change.
Adjust in test, for to cover my last change.
Java
apache-2.0
leonarduk/unison,eltonnuness/unison,leonarduk/unison,eltonnuness/unison
java
## Code Before: /** * LocationFinderImplTest * * @author ${author} * @since 29-May-2016 */ package uk.co.sleonard.unison.input; import java.net.URL; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import uk.co.sleonard.unison.datahandling.DAO.Location; public class LocationFinderImplTest { private LocationFinderImpl finder; @Before public void setUp() throws Exception { final URL resource = this.getClass().getClassLoader().getResource("locationFinder/"); this.finder = new LocationFinderImpl(resource.toString()); } @Test public final void testCreateLocation() { final Location actual = this.finder.createLocation("213.205.194.135"); Assert.assertNotNull(actual); Assert.assertEquals("United Kingdom", actual.getCountry()); Assert.assertEquals("London", actual.getCity()); Assert.assertEquals("GB", actual.getCountryCode()); } } ## Instruction: Adjust in test, for to cover my last change. ## Code After: /** * LocationFinderImplTest * * @author ${author} * @since 29-May-2016 */ package uk.co.sleonard.unison.input; import java.net.URL; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import uk.co.sleonard.unison.datahandling.DAO.Location; public class LocationFinderImplTest { private LocationFinderImpl finder; @Before public void setUp() throws Exception { final URL resource = this.getClass().getClassLoader().getResource("locationFinder/"); this.finder = new LocationFinderImpl(resource.toString()); } @Test public final void testCreateLocation() { final Location actual = this.finder.createLocation("213.205.194.135"); Assert.assertNotNull(actual); Assert.assertEquals("United Kingdom", actual.getCountry()); Assert.assertEquals("London", actual.getCity()); Assert.assertEquals("GB", actual.getCountryCode()); Location actual2 = this.finder.createLocation("wrongipaddress"); Assert.assertNull(actual2.getCountry()); Assert.assertNull(actual2.getCity()); Assert.assertNull(actual2.getCountryCode()); } }
// ... existing code ... Assert.assertEquals("United Kingdom", actual.getCountry()); Assert.assertEquals("London", actual.getCity()); Assert.assertEquals("GB", actual.getCountryCode()); Location actual2 = this.finder.createLocation("wrongipaddress"); Assert.assertNull(actual2.getCountry()); Assert.assertNull(actual2.getCity()); Assert.assertNull(actual2.getCountryCode()); } } // ... rest of the code ...
e65a8c057d9dbd156222542a0e544d294292de00
thinglang/lexer/symbols/base.py
thinglang/lexer/symbols/base.py
from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, stack): return stack[self.value] def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self")
from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, resolver): return resolver.resolve(self) def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self")
Use new resolver in LexicalID resolution
Use new resolver in LexicalID resolution
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
python
## Code Before: from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, stack): return stack[self.value] def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self") ## Instruction: Use new resolver in LexicalID resolution ## Code After: from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, resolver): return resolver.resolve(self) def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self")
// ... existing code ... class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value // ... modified code ... def describe(self): return self.value def evaluate(self, resolver): return resolver.resolve(self) def __hash__(self): return hash(self.value) // ... rest of the code ...
8c1da33165c6852164f60ffe0a8a823167c18ba2
livedata-support/src/main/kotlin/com/chibatching/kotpref/livedata/KotprefLiveDataExtensions.kt
livedata-support/src/main/kotlin/com/chibatching/kotpref/livedata/KotprefLiveDataExtensions.kt
package com.chibatching.kotpref.livedata import android.content.SharedPreferences import androidx.lifecycle.LiveData import com.chibatching.kotpref.KotprefModel import kotlin.reflect.KProperty0 fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> { return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener { private val key: String = [email protected](property) ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref") init { postValue(property.get()) } override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) { if (propertyName == key) { postValue(property.get()) } } override fun onActive() { this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this) if (value != property.get()) { value = property.get() } } override fun onInactive() { this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this) } } }
package com.chibatching.kotpref.livedata import android.content.SharedPreferences import androidx.lifecycle.LiveData import com.chibatching.kotpref.KotprefModel import kotlin.reflect.KProperty0 fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> { return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener { private val key: String = [email protected](property) ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref") override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) { if (propertyName == key) { postValue(property.get()) } } override fun onActive() { this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this) if (value != property.get()) { value = property.get() } } override fun onInactive() { this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this) } } }
Fix that LiveData initial value fires twice
Fix that LiveData initial value fires twice
Kotlin
apache-2.0
chibatching/Kotpref
kotlin
## Code Before: package com.chibatching.kotpref.livedata import android.content.SharedPreferences import androidx.lifecycle.LiveData import com.chibatching.kotpref.KotprefModel import kotlin.reflect.KProperty0 fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> { return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener { private val key: String = [email protected](property) ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref") init { postValue(property.get()) } override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) { if (propertyName == key) { postValue(property.get()) } } override fun onActive() { this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this) if (value != property.get()) { value = property.get() } } override fun onInactive() { this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this) } } } ## Instruction: Fix that LiveData initial value fires twice ## Code After: package com.chibatching.kotpref.livedata import android.content.SharedPreferences import androidx.lifecycle.LiveData import com.chibatching.kotpref.KotprefModel import kotlin.reflect.KProperty0 fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> { return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener { private val key: String = [email protected](property) ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref") override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) { if (propertyName == key) { postValue(property.get()) } } override fun onActive() { this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this) if (value != property.get()) { value = property.get() } } override fun onInactive() { this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this) } } }
... return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener { private val key: String = [email protected](property) ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref") override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) { if (propertyName == key) { ...
8fd5c5c8c7aec1cc045f7f2fcbecb16be129c19b
jobs/templatetags/jobs_tags.py
jobs/templatetags/jobs_tags.py
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
Add fix for non pages like search.
Add fix for non pages like search.
Python
mit
OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website
python
## Code Before: from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None ## Instruction: Add fix for non pages like search. ## Code After: from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
// ... existing code ... @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) // ... rest of the code ...
2fbf7ea2dd7f163bb86f60e5c607af2fd43e1739
kicost/currency_converter/download_rates.py
kicost/currency_converter/download_rates.py
import sys from bs4 import BeautifulSoup if sys.version_info[0] < 3: from urllib2 import urlopen, URLError else: from urllib.request import urlopen, URLError # Author information. __author__ = 'Salvador Eduardo Tropea' __webpage__ = 'https://github.com/set-soft/' __company__ = 'INTI-CMNB - Argentina' url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' def download_rates(): content = '' try: content = urlopen(url).read().decode('utf8') except URLError: pass soup = BeautifulSoup(content, 'xml') rates = {'EUR': 1.0} date = '' for entry in soup.find_all('Cube'): currency = entry.get('currency') if currency is not None: rates[currency] = float(entry.get('rate')) elif entry.get('time'): date = entry.get('time') return date, rates
import os import sys from bs4 import BeautifulSoup if sys.version_info[0] < 3: from urllib2 import urlopen, URLError else: from urllib.request import urlopen, URLError # Author information. __author__ = 'Salvador Eduardo Tropea' __webpage__ = 'https://github.com/set-soft/' __company__ = 'INTI-CMNB - Argentina' url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' def download_rates(): content = '' if os.environ.get('KICOST_CURRENCY_RATES'): with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f: content = f.read() else: try: content = urlopen(url).read().decode('utf8') except URLError: pass soup = BeautifulSoup(content, 'xml') rates = {'EUR': 1.0} date = '' for entry in soup.find_all('Cube'): currency = entry.get('currency') if currency is not None: rates[currency] = float(entry.get('rate')) elif entry.get('time'): date = entry.get('time') return date, rates
Allow to fake the currency rates.
Allow to fake the currency rates. - The envidonment variable KICOST_CURRENCY_RATES can be used to fake the cunrrency rates. - It must indicate the name of an XML file containing the desired rates. - The format is the one used by the European Central Bank.
Python
mit
xesscorp/KiCost,xesscorp/KiCost,hildogjr/KiCost,hildogjr/KiCost,xesscorp/KiCost,hildogjr/KiCost
python
## Code Before: import sys from bs4 import BeautifulSoup if sys.version_info[0] < 3: from urllib2 import urlopen, URLError else: from urllib.request import urlopen, URLError # Author information. __author__ = 'Salvador Eduardo Tropea' __webpage__ = 'https://github.com/set-soft/' __company__ = 'INTI-CMNB - Argentina' url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' def download_rates(): content = '' try: content = urlopen(url).read().decode('utf8') except URLError: pass soup = BeautifulSoup(content, 'xml') rates = {'EUR': 1.0} date = '' for entry in soup.find_all('Cube'): currency = entry.get('currency') if currency is not None: rates[currency] = float(entry.get('rate')) elif entry.get('time'): date = entry.get('time') return date, rates ## Instruction: Allow to fake the currency rates. - The envidonment variable KICOST_CURRENCY_RATES can be used to fake the cunrrency rates. - It must indicate the name of an XML file containing the desired rates. - The format is the one used by the European Central Bank. ## Code After: import os import sys from bs4 import BeautifulSoup if sys.version_info[0] < 3: from urllib2 import urlopen, URLError else: from urllib.request import urlopen, URLError # Author information. __author__ = 'Salvador Eduardo Tropea' __webpage__ = 'https://github.com/set-soft/' __company__ = 'INTI-CMNB - Argentina' url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' def download_rates(): content = '' if os.environ.get('KICOST_CURRENCY_RATES'): with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f: content = f.read() else: try: content = urlopen(url).read().decode('utf8') except URLError: pass soup = BeautifulSoup(content, 'xml') rates = {'EUR': 1.0} date = '' for entry in soup.find_all('Cube'): currency = entry.get('currency') if currency is not None: rates[currency] = float(entry.get('rate')) elif entry.get('time'): date = entry.get('time') return date, rates
// ... existing code ... import os import sys from bs4 import BeautifulSoup // ... modified code ... def download_rates(): content = '' if os.environ.get('KICOST_CURRENCY_RATES'): with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f: content = f.read() else: try: content = urlopen(url).read().decode('utf8') except URLError: pass soup = BeautifulSoup(content, 'xml') rates = {'EUR': 1.0} date = '' // ... rest of the code ...
65b4c081c3a66ccd373062f8e7c1d63295c8d8d1
cache_relation/app_settings.py
cache_relation/app_settings.py
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
from django.conf import settings # Default cache timeout CACHE_RELATION_DEFAULT_DURATION = getattr( settings, 'CACHE_RELATION_DEFAULT_DURATION', 60 * 60 * 24 * 3, )
Allow global settings to override.
Allow global settings to override. Signed-off-by: Chris Lamb <[email protected]>
Python
bsd-3-clause
thread/django-sensible-caching,playfire/django-cache-toolbox,lamby/django-sensible-caching,lamby/django-cache-toolbox
python
## Code Before: CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3 ## Instruction: Allow global settings to override. Signed-off-by: Chris Lamb <[email protected]> ## Code After: from django.conf import settings # Default cache timeout CACHE_RELATION_DEFAULT_DURATION = getattr( settings, 'CACHE_RELATION_DEFAULT_DURATION', 60 * 60 * 24 * 3, )
// ... existing code ... from django.conf import settings # Default cache timeout CACHE_RELATION_DEFAULT_DURATION = getattr( settings, 'CACHE_RELATION_DEFAULT_DURATION', 60 * 60 * 24 * 3, ) // ... rest of the code ...
aff5a09eb3d61f77cb277b076820481b8ba145d5
tests/test_coroutine.py
tests/test_coroutine.py
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') ''') except ImportError: import trollius as asyncio from trollius import From def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) if __name__ == '__main__': import unittest unittest.main()
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') return "." def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield from fut result.append(value) value = yield from hello_world(result, 0.001) result.append(value) ''') except ImportError: import trollius as asyncio from trollius import From, Return def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') raise Return(".") def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield From(fut) result.append(value) value = yield From(hello_world(result, 0.001)) result.append(value) class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) def test_waiter(self): result = [] self.loop.run_until_complete(waiter(result)) self.assertEqual(result, ['Future', 'Hello', 'World', '.']) if __name__ == '__main__': import unittest unittest.main()
Add more complex coroutine example
Add more complex coroutine example
Python
apache-2.0
overcastcloud/aioeventlet
python
## Code Before: import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') ''') except ImportError: import trollius as asyncio from trollius import From def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) if __name__ == '__main__': import unittest unittest.main() ## Instruction: Add more complex coroutine example ## Code After: import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') return "." def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield from fut result.append(value) value = yield from hello_world(result, 0.001) result.append(value) ''') except ImportError: import trollius as asyncio from trollius import From, Return def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') raise Return(".") def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield From(fut) result.append(value) value = yield From(hello_world(result, 0.001)) result.append(value) class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) def test_waiter(self): result = [] self.loop.run_until_complete(waiter(result)) self.assertEqual(result, ['Future', 'Hello', 'World', '.']) if __name__ == '__main__': import unittest unittest.main()
... # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') return "." def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield from fut result.append(value) value = yield from hello_world(result, 0.001) result.append(value) ''') except ImportError: import trollius as asyncio from trollius import From, Return def hello_world(result, delay): result.append("Hello") ... # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') raise Return(".") def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield From(fut) result.append(value) value = yield From(hello_world(result, 0.001)) result.append(value) class CallbackTests(tests.TestCase): def test_hello_world(self): ... self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) def test_waiter(self): result = [] self.loop.run_until_complete(waiter(result)) self.assertEqual(result, ['Future', 'Hello', 'World', '.']) if __name__ == '__main__': import unittest ...
f88d747f7959808884451245aeba65edf7c490bf
synapse/replication/slave/storage/filtering.py
synapse/replication/slave/storage/filtering.py
from ._base import BaseSlavedStore from synapse.storage.filtering import FilteringStore class SlavedFilteringStore(BaseSlavedStore): def __init__(self, db_conn, hs): super(SlavedFilteringStore, self).__init__(db_conn, hs) get_user_filter = FilteringStore.__dict__["get_user_filter"]
from ._base import BaseSlavedStore from synapse.storage.filtering import FilteringStore class SlavedFilteringStore(BaseSlavedStore): def __init__(self, db_conn, hs): super(SlavedFilteringStore, self).__init__(db_conn, hs) # Filters are immutable so this cache doesn't need to be expired get_user_filter = FilteringStore.__dict__["get_user_filter"]
Add a comment explaining why the filter cache doesn't need exipiring
Add a comment explaining why the filter cache doesn't need exipiring
Python
apache-2.0
TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,TribeMedia/synapse
python
## Code Before: from ._base import BaseSlavedStore from synapse.storage.filtering import FilteringStore class SlavedFilteringStore(BaseSlavedStore): def __init__(self, db_conn, hs): super(SlavedFilteringStore, self).__init__(db_conn, hs) get_user_filter = FilteringStore.__dict__["get_user_filter"] ## Instruction: Add a comment explaining why the filter cache doesn't need exipiring ## Code After: from ._base import BaseSlavedStore from synapse.storage.filtering import FilteringStore class SlavedFilteringStore(BaseSlavedStore): def __init__(self, db_conn, hs): super(SlavedFilteringStore, self).__init__(db_conn, hs) # Filters are immutable so this cache doesn't need to be expired get_user_filter = FilteringStore.__dict__["get_user_filter"]
... def __init__(self, db_conn, hs): super(SlavedFilteringStore, self).__init__(db_conn, hs) # Filters are immutable so this cache doesn't need to be expired get_user_filter = FilteringStore.__dict__["get_user_filter"] ...
06ec0a7f0a6a53fddfb2038b0ae8cc1bad2c8511
blankspot/node_registration/models.py
blankspot/node_registration/models.py
from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) def __unicode__(self): return (self.nick) def get_absolute_url(self): return reverse('contact-detail', kwargs={'pk': self.pk}) class Position(models.Model): contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation.
Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation.
Python
agpl-3.0
frlan/blankspot
python
## Code Before: from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) def __unicode__(self): return (self.nick) def get_absolute_url(self): return reverse('contact-detail', kwargs={'pk': self.pk}) class Position(models.Model): contact = models.ForeignKey('Contact') street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) ## Instruction: Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation. ## Code After: from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
// ... existing code ... from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) // ... rest of the code ...
e6cf8c244cdffa08d67a45c3a44236c3b91aab78
examples/rmg/liquid_phase/input.py
examples/rmg/liquid_phase/input.py
database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='octane', reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationTime=(5,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, )
database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # Constraints on generated species generatedSpeciesConstraints( maximumRadicalElectrons = 3, ) # List of species species( label='octane', multiplicity = 1, reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', multiplicity = 3, reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationTime=(5,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, )
Update RMG example liquid_phase with multiplicity label
Update RMG example liquid_phase with multiplicity label
Python
mit
chatelak/RMG-Py,pierrelb/RMG-Py,enochd/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,nyee/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,comocheng/RMG-Py
python
## Code Before: database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='octane', reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationTime=(5,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, ) ## Instruction: Update RMG example liquid_phase with multiplicity label ## Code After: database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # Constraints on generated species generatedSpeciesConstraints( maximumRadicalElectrons = 3, ) # List of species species( label='octane', multiplicity = 1, reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', multiplicity = 3, reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationTime=(5,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, )
# ... existing code ... kineticsEstimator = 'rate rules', ) # Constraints on generated species generatedSpeciesConstraints( maximumRadicalElectrons = 3, ) # List of species species( label='octane', multiplicity = 1, reactive=True, structure=SMILES("C(CCCCC)CC"), ) # ... modified code ... species( label='oxygen', multiplicity = 3, reactive=True, structure=SMILES("[O][O]"), ) # ... rest of the code ...
95eb73ce7645ae6275fbb958ec803ce521b16198
helusers/urls.py
helusers/urls.py
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." )
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
Check configuration before specifying urlpatterns
Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
python
## Code Before: """URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) ## Instruction: Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case. ## Code After: """URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
// ... existing code ... app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] ) // ... rest of the code ...
f81ddc6297b1372cdba3a5161b4f30d0a42d2f58
src/factor.py
src/factor.py
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n}
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n < 1: raise ValueError if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n}
Raise ValueError if n < 1
Raise ValueError if n < 1
Python
mit
mackorone/euler
python
## Code Before: from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n} ## Instruction: Raise ValueError if n < 1 ## Code After: from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n < 1: raise ValueError if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n}
# ... existing code ... def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n < 1: raise ValueError if n == 1: return Counter() divisor = 2 # ... rest of the code ...
e8bcd56727199de75a0dcefe7590d3866a14f39d
django_mailbox/tests/test_mailbox.py
django_mailbox/tests/test_mailbox.py
from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, )
import os from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None)
Add tests to update Mailbox.last_polling
Add tests to update Mailbox.last_polling
Python
mit
coddingtonbear/django-mailbox,ad-m/django-mailbox
python
## Code Before: from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) ## Instruction: Add tests to update Mailbox.last_polling ## Code After: import os from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None)
// ... existing code ... import os from django.test import TestCase from django_mailbox.models import Mailbox // ... modified code ... expected_protocol, actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None) // ... rest of the code ...
3d4a71f6bb84fe4e5c7f51b109a55a7560ebb673
test/test_absolute_import.py
test/test_absolute_import.py
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.scope.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.scope.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.scope.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
Use Parser.module instead of Parser.scope
Use Parser.module instead of Parser.scope
Python
mit
jonashaag/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,jonashaag/jedi,flurischt/jedi,flurischt/jedi,dwillmer/jedi
python
## Code Before: import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.scope.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.scope.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.scope.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions() ## Instruction: Use Parser.module instead of Parser.scope ## Code After: import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
... Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): ... Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): ... """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") ...
8170ad6cdfd2346bc24a3d743663b4866416ca83
Engine.py
Engine.py
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) #Create a function to add a shape def addshape(self, s): self.shapes.append(s) #Create a function to render the shapes def render(self): #For each of the shapes, check the type and render it for s in shapes: #If the shape is a cube, call the rendercube method if s.type == Shape.CUBE: rendercube(s)
Add functions to add shapes and iterate over each shape to render.
Add functions to add shapes and iterate over each shape to render.
Python
mit
thebillington/pyPhys3D
python
## Code Before: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) ## Instruction: Add functions to add shapes and iterate over each shape to render. ## Code After: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) #Create a function to add a shape def addshape(self, s): self.shapes.append(s) #Create a function to render the shapes def render(self): #For each of the shapes, check the type and render it for s in shapes: #If the shape is a cube, call the rendercube method if s.type == Shape.CUBE: rendercube(s)
// ... existing code ... #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) #Create a function to add a shape def addshape(self, s): self.shapes.append(s) #Create a function to render the shapes def render(self): #For each of the shapes, check the type and render it for s in shapes: #If the shape is a cube, call the rendercube method if s.type == Shape.CUBE: rendercube(s) // ... rest of the code ...
b73b8797c3c9c6c9aa92bd6873e15a5b717f4142
test/test_nap.py
test/test_nap.py
import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource)
from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') )
Add tests which test default parameters for nap api
Add tests which test default parameters for nap api
Python
mit
kimmobrunfeldt/nap
python
## Code Before: import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) ## Instruction: Add tests which test default parameters for nap api ## Code After: from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') )
... from mock import MagicMock, patch import unittest import requests ... """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') ) ...
a42b9b3c6c73322e771fea0590e618d4ea8e6ec9
github-android/src/main/java/com/github/mobile/android/gist/GistFileListAdapter.java
github-android/src/main/java/com/github/mobile/android/gist/GistFileListAdapter.java
package com.github.mobile.android.gist; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.github.mobile.android.R; import org.eclipse.egit.github.core.GistFile; /** * Adapter for viewing the files in a Gist */ public class GistFileListAdapter extends ArrayAdapter<GistFile> { private final Activity activity; /** * Create adapter for files * * @param activity * @param files */ public GistFileListAdapter(Activity activity, GistFile[] files) { super(activity, R.layout.gist_view_file_item, files); this.activity = activity; } @Override public View getView(int position, View convertView, ViewGroup parent) { final GistFile file = getItem(position); final TextView view = (TextView) activity.getLayoutInflater().inflate(R.layout.gist_view_file_item, null); view.setText(file.getFilename()); return view; } }
package com.github.mobile.android.gist; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.github.mobile.android.R.layout; import org.eclipse.egit.github.core.GistFile; /** * Adapter for viewing the files in a Gist */ public class GistFileListAdapter extends ArrayAdapter<GistFile> { private final Activity activity; /** * Create adapter for files * * @param activity * @param files */ public GistFileListAdapter(Activity activity, GistFile[] files) { super(activity, layout.gist_view_file_item, files); this.activity = activity; } @Override public View getView(int position, View convertView, ViewGroup parent) { final TextView view = (TextView) activity.getLayoutInflater().inflate(layout.gist_view_file_item, null); view.setText("» " + getItem(position).getFilename()); return view; } }
Indent Gist file name with '»' character
Indent Gist file name with '»' character
Java
apache-2.0
larsgrefer/github-android-app,karllindmark/PocketHub,theiven70/PocketHub,pockethub/PocketHub,larsgrefer/github-android-app,yytang2012/PocketHub,zhuxiaohao/PocketHub,usr80/Android,wang0818/android,wshh08/PocketHub,gmyboy/android,Leaking/android,Chalmers-SEP-GitHubApp-Group/android,yuanhuihui/PocketHub,sam14305/bhoot.life,qiancy/PocketHub,zhuxiaohao/PocketHub,yummy222/PocketHub,yummy222/PocketHub,xiaopengs/PocketHub,GeekHades/PocketHub,xiaopengs/PocketHub,njucsyyh/android,condda/android,DeLaSalleUniversity-Manila/forkhub-JJCpro10,karllindmark/PocketHub,mishin/ForkHub,xiaoleigua/PocketHub,kostaskoukouvis/android,Leaking/android,Cl3Kener/darkhub,Meisolsson/PocketHub,sudosurootdev/packages_apps_Github,PKRoma/PocketHub,tempbottle/PocketHub,KingLiuDao/android,sudosurootdev/packages_apps_Github,micrologic/PocketHub,common2015/PocketHub,xen0n/android,Tadakatsu/android,bineanzhou/android_github,xfumihiro/PocketHub,pockethub/PocketHub,gvaish/PocketHub,jchenga/android,esironal/PocketHub,Androidbsw/android,reproio/github-for-android,Bloody-Badboy/PocketHub,reproio/github-for-android,Bloody-Badboy/PocketHub,hgl888/PocketHub,yuanhuihui/PocketHub,simple88/PocketHub,danielferecatu/android,lzy-h2o2/PocketHub,zhengxiaopeng/github-app,forkhubs/android,roadrunner1987/PocketHub,fadils/android,Bloody-Badboy/PocketHub,yytang2012/PocketHub,larsgrefer/github-android-app,LeoLamCY/PocketHub,njucsyyh/android,ISkyLove/PocketHub,Cl3Kener/darkhub,nvoron23/android,navychang/android,theiven70/PocketHub,sydneyagcaoili/PocketHub,tsdl2013/android,jonan/ForkHub,huangsongyan/PocketHub,pockethub/PocketHub,huangsongyan/PocketHub,liqk2014/PocketHub,wshh08/PocketHub,songful/PocketHub,hufsm/PocketHub,shekibobo/android,KishorAndroid/PocketHub,tsdl2013/android,chaoallsome/PocketHub,sam14305/bhoot.life,yongjhih/PocketHub,kostaskoukouvis/android,roadrunner1987/PocketHub,condda/android,PKRoma/github-android,samuelralak/ForkHub,hgl888/PocketHub,erpragatisingh/android-1,hgl888/PocketHub,pockethub/PocketHub,xfumihiro/PocketHub,common2015/PocketHub,yongjhih/PocketHub,weiyihz/PocketHub,Androidbsw/android,KingLiuDao/android,jchenga/android,arcivanov/ForkHub,esironal/PocketHub,lzy-h2o2/PocketHub,Liyue1314/PocketHub,yytang2012/PocketHub,Calamus-Cajan/PocketHub,gvaish/PocketHub,LeoLamCY/PocketHub,xfumihiro/ForkHub,acemaster/android,PKRoma/github-android,hufsm/PocketHub,PKRoma/github-android,arcivanov/ForkHub,Chalmers-SEP-GitHubApp-Group/android,sydneyagcaoili/PocketHub,acemaster/android,abhishekbm/android,wubin28/android,weiyihz/PocketHub,usr80/Android,condda/android,repanda/PocketHub,zhengxiaopeng/github-app,funsociety/PocketHub,karllindmark/PocketHub,rmad17/PocketHub,samuelralak/ForkHub,Kevin16Wang/PocketHub,marceloneil/PocketHub,xfumihiro/PocketHub,PKRoma/PocketHub,rmad17/PocketHub,larsgrefer/pocket-hub,qiancy/PocketHub,Liyue1314/PocketHub,GeekHades/PocketHub,chaoallsome/PocketHub,liqk2014/PocketHub,repanda/PocketHub,work4life/PocketHub,supercocoa/PocketHub,reproio/github-for-android,cnoldtree/PocketHub,zhuxiaohao/PocketHub,PKRoma/PocketHub,navychang/android,xen0n/android,ISkyLove/PocketHub,samuelralak/ForkHub,Tadakatsu/android,soztzfsnf/PocketHub,supercocoa/PocketHub,vfs1234/android,jonan/ForkHub,marceloneil/PocketHub,mishin/ForkHub,vfs1234/android,ywk248248/Forkhub_cloned,acemaster/android,songful/PocketHub,larsgrefer/pocket-hub,JLLK/PocketHub-scala,funsociety/PocketHub,JosephYao/android,Kevin16Wang/PocketHub,Meisolsson/PocketHub,DeLaSalleUniversity-Manila/forkhub-JJCpro10,roadrunner1987/PocketHub,Katariaa/PocketHub,M13Kd/PocketHub,forkhubs/android,zhangtianqiu/githubandroid,Calamus-Cajan/PocketHub,zhangtianqiu/githubandroid,Damonzh/PocketHub,larsgrefer/pocket-hub,gvaish/PocketHub,supercocoa/PocketHub,Katariaa/PocketHub,zhengxiaopeng/github-app,PeterDaveHello/PocketHub,GeekHades/PocketHub,micrologic/PocketHub,work4life/PocketHub,Meisolsson/PocketHub,ywk248248/Forkhub_cloned,M13Kd/PocketHub,xiaoleigua/PocketHub,yongjhih/PocketHub,tempbottle/PocketHub,Tadakatsu/android,chaoallsome/PocketHub,kebenxiaoming/android-1,erpragatisingh/android-1,cnoldtree/PocketHub,weiyihz/PocketHub,Meisolsson/PocketHub,gmyboy/android,nvoron23/android,kebenxiaoming/android-1,shekibobo/android,hufsm/PocketHub,wubin28/android,KingLiuDao/android,mishin/ForkHub,rmad17/PocketHub,yuanhuihui/PocketHub,Damonzh/PocketHub,abhishekbm/android,bineanzhou/android_github,tempbottle/PocketHub,xen0n/android,xiaopengs/PocketHub,esironal/PocketHub,Calamus-Cajan/PocketHub,sydneyagcaoili/PocketHub,xiaoleigua/PocketHub,KishorAndroid/PocketHub,DeLaSalleUniversity-Manila/forkhub-JJCpro10,kebenxiaoming/android-1,PeterDaveHello/PocketHub,shekibobo/android,simple88/PocketHub,qiancy/PocketHub,simple88/PocketHub,Damonzh/PocketHub,M13Kd/PocketHub,JosephYao/android,liqk2014/PocketHub,lzy-h2o2/PocketHub,fadils/android,soztzfsnf/PocketHub,nvoron23/android,generalzou/PocketHub,micrologic/PocketHub,ywk248248/Forkhub_cloned,cnoldtree/PocketHub,zhangtianqiu/githubandroid,danielferecatu/android,repanda/PocketHub,marceloneil/PocketHub,wshh08/PocketHub,wang0818/android,LeoLamCY/PocketHub,generalzou/PocketHub,sam14305/bhoot.life,huangsongyan/PocketHub,vfs1234/android,yummy222/PocketHub,xfumihiro/ForkHub,erpragatisingh/android-1,ISkyLove/PocketHub,tsdl2013/android,generalzou/PocketHub,forkhubs/android,funsociety/PocketHub,jonan/ForkHub,Katariaa/PocketHub,fadils/android,navychang/android,common2015/PocketHub,njucsyyh/android,gmyboy/android,PeterDaveHello/PocketHub,Androidbsw/android,danielferecatu/android,bineanzhou/android_github,jchenga/android,soztzfsnf/PocketHub,songful/PocketHub,theiven70/PocketHub,xfumihiro/ForkHub,Cl3Kener/darkhub,JosephYao/android,wubin28/android,Kevin16Wang/PocketHub,PKRoma/PocketHub,KishorAndroid/PocketHub,songful/PocketHub,wang0818/android,arcivanov/ForkHub,Liyue1314/PocketHub,abhishekbm/android,work4life/PocketHub
java
## Code Before: package com.github.mobile.android.gist; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.github.mobile.android.R; import org.eclipse.egit.github.core.GistFile; /** * Adapter for viewing the files in a Gist */ public class GistFileListAdapter extends ArrayAdapter<GistFile> { private final Activity activity; /** * Create adapter for files * * @param activity * @param files */ public GistFileListAdapter(Activity activity, GistFile[] files) { super(activity, R.layout.gist_view_file_item, files); this.activity = activity; } @Override public View getView(int position, View convertView, ViewGroup parent) { final GistFile file = getItem(position); final TextView view = (TextView) activity.getLayoutInflater().inflate(R.layout.gist_view_file_item, null); view.setText(file.getFilename()); return view; } } ## Instruction: Indent Gist file name with '»' character ## Code After: package com.github.mobile.android.gist; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.github.mobile.android.R.layout; import org.eclipse.egit.github.core.GistFile; /** * Adapter for viewing the files in a Gist */ public class GistFileListAdapter extends ArrayAdapter<GistFile> { private final Activity activity; /** * Create adapter for files * * @param activity * @param files */ public GistFileListAdapter(Activity activity, GistFile[] files) { super(activity, layout.gist_view_file_item, files); this.activity = activity; } @Override public View getView(int position, View convertView, ViewGroup parent) { final TextView view = (TextView) activity.getLayoutInflater().inflate(layout.gist_view_file_item, null); view.setText("» " + getItem(position).getFilename()); return view; } }
# ... existing code ... import android.widget.ArrayAdapter; import android.widget.TextView; import com.github.mobile.android.R.layout; import org.eclipse.egit.github.core.GistFile; # ... modified code ... * @param files */ public GistFileListAdapter(Activity activity, GistFile[] files) { super(activity, layout.gist_view_file_item, files); this.activity = activity; } @Override public View getView(int position, View convertView, ViewGroup parent) { final TextView view = (TextView) activity.getLayoutInflater().inflate(layout.gist_view_file_item, null); view.setText("» " + getItem(position).getFilename()); return view; } } # ... rest of the code ...
f45e182ec206ab08b1bea699033938b562558670
test/test_compression.py
test/test_compression.py
import unittest import bmemcached import bz2 class MemcachedTests(unittest.TestCase): def setUp(self): self.server = '127.0.0.1:11211' self.client = bmemcached.Client(self.server, 'user', 'password') self.bzclient = bmemcached.Client(self.server, 'user', 'password', bz2) self.data = b'this is test data. ' * 32 def tearDown(self): self.client.delete(b'test_key') self.client.delete(b'test_key2') self.client.disconnect_all() self.bzclient.disconnect_all() def testCompressedData(self): self.client.set(b'test_key', self.data) self.assertEqual(self.data, self.client.get(b'test_key')) def testBZ2CompressedData(self): self.bzclient.set(b'test_key', self.data) self.assertEqual(self.data, self.bzclient.get(b'test_key')) def testCompressionMissmatch(self): self.client.set(b'test_key', self.data) self.bzclient.set(b'test_key2', self.data) self.assertEqual(self.client.get(b'test_key'), self.bzclient.get(b'test_key2')) self.assertRaises(IOError, self.bzclient.get, b'test_key')
import unittest import bz2 import bmemcached class MemcachedTests(unittest.TestCase): def setUp(self): self.server = '127.0.0.1:11211' self.client = bmemcached.Client(self.server, 'user', 'password') self.bzclient = bmemcached.Client(self.server, 'user', 'password', compression=bz2) self.data = b'this is test data. ' * 32 def tearDown(self): self.client.delete(b'test_key') self.client.delete(b'test_key2') self.client.disconnect_all() self.bzclient.disconnect_all() def testCompressedData(self): self.client.set(b'test_key', self.data) self.assertEqual(self.data, self.client.get(b'test_key')) def testBZ2CompressedData(self): self.bzclient.set(b'test_key', self.data) self.assertEqual(self.data, self.bzclient.get(b'test_key')) def testCompressionMissmatch(self): self.client.set(b'test_key', self.data) self.bzclient.set(b'test_key2', self.data) self.assertEqual(self.client.get(b'test_key'), self.bzclient.get(b'test_key2')) self.assertRaises(IOError, self.bzclient.get, b'test_key')
Use keyword arguments to avoid accidentally setting timeout
Use keyword arguments to avoid accidentally setting timeout
Python
mit
xmonster-tech/python-binary-memcached,jaysonsantos/python-binary-memcached,xmonster-tech/python-binary-memcached,jaysonsantos/python-binary-memcached
python
## Code Before: import unittest import bmemcached import bz2 class MemcachedTests(unittest.TestCase): def setUp(self): self.server = '127.0.0.1:11211' self.client = bmemcached.Client(self.server, 'user', 'password') self.bzclient = bmemcached.Client(self.server, 'user', 'password', bz2) self.data = b'this is test data. ' * 32 def tearDown(self): self.client.delete(b'test_key') self.client.delete(b'test_key2') self.client.disconnect_all() self.bzclient.disconnect_all() def testCompressedData(self): self.client.set(b'test_key', self.data) self.assertEqual(self.data, self.client.get(b'test_key')) def testBZ2CompressedData(self): self.bzclient.set(b'test_key', self.data) self.assertEqual(self.data, self.bzclient.get(b'test_key')) def testCompressionMissmatch(self): self.client.set(b'test_key', self.data) self.bzclient.set(b'test_key2', self.data) self.assertEqual(self.client.get(b'test_key'), self.bzclient.get(b'test_key2')) self.assertRaises(IOError, self.bzclient.get, b'test_key') ## Instruction: Use keyword arguments to avoid accidentally setting timeout ## Code After: import unittest import bz2 import bmemcached class MemcachedTests(unittest.TestCase): def setUp(self): self.server = '127.0.0.1:11211' self.client = bmemcached.Client(self.server, 'user', 'password') self.bzclient = bmemcached.Client(self.server, 'user', 'password', compression=bz2) self.data = b'this is test data. ' * 32 def tearDown(self): self.client.delete(b'test_key') self.client.delete(b'test_key2') self.client.disconnect_all() self.bzclient.disconnect_all() def testCompressedData(self): self.client.set(b'test_key', self.data) self.assertEqual(self.data, self.client.get(b'test_key')) def testBZ2CompressedData(self): self.bzclient.set(b'test_key', self.data) self.assertEqual(self.data, self.bzclient.get(b'test_key')) def testCompressionMissmatch(self): self.client.set(b'test_key', self.data) self.bzclient.set(b'test_key2', self.data) self.assertEqual(self.client.get(b'test_key'), self.bzclient.get(b'test_key2')) self.assertRaises(IOError, self.bzclient.get, b'test_key')
// ... existing code ... import unittest import bz2 import bmemcached class MemcachedTests(unittest.TestCase): def setUp(self): self.server = '127.0.0.1:11211' self.client = bmemcached.Client(self.server, 'user', 'password') self.bzclient = bmemcached.Client(self.server, 'user', 'password', compression=bz2) self.data = b'this is test data. ' * 32 def tearDown(self): // ... modified code ... self.assertEqual(self.client.get(b'test_key'), self.bzclient.get(b'test_key2')) self.assertRaises(IOError, self.bzclient.get, b'test_key') // ... rest of the code ...
f20b64d03463cbd35bcacea1d80848b19d15ea6a
KVODelegate/KVODelegate.h
KVODelegate/KVODelegate.h
// // KVODelegate.h // KVODelegate // // Created by Ian Gregory on 15-03-2017. // Copyright © 2017 ThatsJustCheesy. All rights reserved. // #import <Foundation/Foundation.h> #import <KVODelegate/KVOObservationDelegate.h> #import <KVODelegate/KVONotificationDelegate.h>
// // KVODelegate.h // KVODelegate // // Created by Ian Gregory on 15-03-2017. // Copyright © 2017 ThatsJustCheesy. All rights reserved. // #import <Foundation/Foundation.h> #import "KVOObservationDelegate.h" #import "KVONotificationDelegate.h"
Use quoted includes in umbrella header
Use quoted includes in umbrella header
C
mit
ThatsJustCheesy/KVODelegate,ThatsJustCheesy/KVODelegate
c
## Code Before: // // KVODelegate.h // KVODelegate // // Created by Ian Gregory on 15-03-2017. // Copyright © 2017 ThatsJustCheesy. All rights reserved. // #import <Foundation/Foundation.h> #import <KVODelegate/KVOObservationDelegate.h> #import <KVODelegate/KVONotificationDelegate.h> ## Instruction: Use quoted includes in umbrella header ## Code After: // // KVODelegate.h // KVODelegate // // Created by Ian Gregory on 15-03-2017. // Copyright © 2017 ThatsJustCheesy. All rights reserved. // #import <Foundation/Foundation.h> #import "KVOObservationDelegate.h" #import "KVONotificationDelegate.h"
... #import <Foundation/Foundation.h> #import "KVOObservationDelegate.h" #import "KVONotificationDelegate.h" ...
599760942e556c5d23deb0904beafcdf11235595
stoneridge_reporter.py
stoneridge_reporter.py
import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(f) unlink_ok = False with file(fpath, 'rb') as f: try: requests.post(self.url, files={fname: f}) unlink_ok = True except: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run()
import argparse import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(fpath) unlink_ok = False with file(fpath, 'rb') as f: try: post_data = 'data=%s' % (f.read(),) r = requests.post(self.url, data=post_data) unlink_ok = True except Exception, e: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run()
Make reporter succeed in talking to the graph server
Make reporter succeed in talking to the graph server
Python
mpl-2.0
mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge
python
## Code Before: import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(f) unlink_ok = False with file(fpath, 'rb') as f: try: requests.post(self.url, files={fname: f}) unlink_ok = True except: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run() ## Instruction: Make reporter succeed in talking to the graph server ## Code After: import argparse import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(fpath) unlink_ok = False with file(fpath, 'rb') as f: try: post_data = 'data=%s' % (f.read(),) r = requests.post(self.url, data=post_data) unlink_ok = True except Exception, e: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run()
// ... existing code ... import argparse import glob import os import requests // ... modified code ... def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(fpath) unlink_ok = False with file(fpath, 'rb') as f: try: post_data = 'data=%s' % (f.read(),) r = requests.post(self.url, data=post_data) unlink_ok = True except Exception, e: pass if unlink_ok: os.unlink(fpath) // ... rest of the code ...
2448675327ceaa844ae2fab4a15c46d0981cad17
test/test_encode_int.c
test/test_encode_int.c
unsigned char output[6]; void test_output() { if (output[0] != BERT_MAGIC) { test_fail("bert_encoder_push did not add the magic byte"); } if (output[1] != BERT_INT) { test_fail("bert_encoder_push did not add the INT magic byte"); } unsigned int i; for (i=2;i<6;i++) { if (output[i] != 0xff) { test_fail("output[%u] is 0x%x, expected 0x%x",output[i],0xff); } } } int main() { bert_encoder_t *encoder = test_encoder(output,6); bert_data_t *data; if (!(data = bert_data_create_int(0xffffffff))) { test_fail("malloc failed"); } test_encoder_push(encoder,data); bert_data_destroy(data); bert_encoder_destroy(encoder); test_output(); return 0; }
unsigned char output[6]; void test_output() { if (output[0] != BERT_MAGIC) { test_fail("bert_encoder_push did not add the magic byte"); } if (output[1] != BERT_INT) { test_fail("bert_encoder_push did not add the INT magic byte"); } unsigned char bytes[] = {0xff, 0xff, 0xff, 0xff}; test_bytes(output+2,bytes,4); } int main() { bert_encoder_t *encoder = test_encoder(output,6); bert_data_t *data; if (!(data = bert_data_create_int(0xffffffff))) { test_fail("malloc failed"); } test_encoder_push(encoder,data); bert_data_destroy(data); bert_encoder_destroy(encoder); test_output(); return 0; }
Make use of test_bytes in the int encoder test.
Make use of test_bytes in the int encoder test.
C
mit
postmodern/libBERT
c
## Code Before: unsigned char output[6]; void test_output() { if (output[0] != BERT_MAGIC) { test_fail("bert_encoder_push did not add the magic byte"); } if (output[1] != BERT_INT) { test_fail("bert_encoder_push did not add the INT magic byte"); } unsigned int i; for (i=2;i<6;i++) { if (output[i] != 0xff) { test_fail("output[%u] is 0x%x, expected 0x%x",output[i],0xff); } } } int main() { bert_encoder_t *encoder = test_encoder(output,6); bert_data_t *data; if (!(data = bert_data_create_int(0xffffffff))) { test_fail("malloc failed"); } test_encoder_push(encoder,data); bert_data_destroy(data); bert_encoder_destroy(encoder); test_output(); return 0; } ## Instruction: Make use of test_bytes in the int encoder test. ## Code After: unsigned char output[6]; void test_output() { if (output[0] != BERT_MAGIC) { test_fail("bert_encoder_push did not add the magic byte"); } if (output[1] != BERT_INT) { test_fail("bert_encoder_push did not add the INT magic byte"); } unsigned char bytes[] = {0xff, 0xff, 0xff, 0xff}; test_bytes(output+2,bytes,4); } int main() { bert_encoder_t *encoder = test_encoder(output,6); bert_data_t *data; if (!(data = bert_data_create_int(0xffffffff))) { test_fail("malloc failed"); } test_encoder_push(encoder,data); bert_data_destroy(data); bert_encoder_destroy(encoder); test_output(); return 0; }
// ... existing code ... test_fail("bert_encoder_push did not add the INT magic byte"); } unsigned char bytes[] = {0xff, 0xff, 0xff, 0xff}; test_bytes(output+2,bytes,4); } int main() // ... rest of the code ...
0867054258e231b2ce9b028c5ce2bc3a26bca7be
gamernews/apps/threadedcomments/views.py
gamernews/apps/threadedcomments/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from news.models import Blob, BlobInstance from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted( request ): if request.GET['c']: comment_id, blob_id = request.GET['c'].split( ':' ) blob = Blob.objects.get( pk=blob_id ) if post: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" )
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from news.models import Blob, BlobInstance from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted(request): if request.GET['c']: comment_id, blob_id = request.GET['c'] comment = Comment.objects.get( pk=comment_id ) blob = Blob.objects.get(pk=blob_id) if blob: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" )
Remove name, url and email from comment form
Remove name, url and email from comment form
Python
mit
underlost/GamerNews,underlost/GamerNews
python
## Code Before: from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from news.models import Blob, BlobInstance from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted( request ): if request.GET['c']: comment_id, blob_id = request.GET['c'].split( ':' ) blob = Blob.objects.get( pk=blob_id ) if post: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" ) ## Instruction: Remove name, url and email from comment form ## Code After: from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from news.models import Blob, BlobInstance from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted(request): if request.GET['c']: comment_id, blob_id = request.GET['c'] comment = Comment.objects.get( pk=comment_id ) blob = Blob.objects.get(pk=blob_id) if blob: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" )
... variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted(request): if request.GET['c']: comment_id, blob_id = request.GET['c'] comment = Comment.objects.get( pk=comment_id ) blob = Blob.objects.get(pk=blob_id) if blob: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" ) ...
caa860cede791d4787e773624a7627ef963fbeed
src/QGCConfig.h
src/QGCConfig.h
/** @brief Polling interval in ms */ #define SERIAL_POLL_INTERVAL 4 /** @brief Heartbeat emission rate, in Hertz (times per second) */ #define MAVLINK_HEARTBEAT_DEFAULT_RATE 1 #define WITH_TEXT_TO_SPEECH 1 #define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_VERSION "v. 2.0.3 (beta)" namespace QGC { const QString APPNAME = "QGROUNDCONTROL"; const QString ORG_NAME = "QGROUNDCONTROL.ORG"; //can be customized by forks to e.g. mycompany.com to maintain separate Settings for customized apps const QString ORG_DOMAIN = "org.qgroundcontrol";//can be customized by forks const int APPLICATIONVERSION = 203; // 2.0.3 } #endif // QGC_CONFIGURATION_H
/** @brief Polling interval in ms */ #define SERIAL_POLL_INTERVAL 4 /** @brief Heartbeat emission rate, in Hertz (times per second) */ #define MAVLINK_HEARTBEAT_DEFAULT_RATE 1 #define WITH_TEXT_TO_SPEECH 1 #define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_VERSION_BASE "v2.0.3" #define QGC_APPLICATION_VERSION_SUFFIX ".234 (Daily Build)" #ifdef QGC_APPLICATION_VERSION_SUFFIX #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE QGC_APPLICATION_VERSION_SUFFIX #else #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE " (Developer Build)" #endif namespace QGC { const QString APPNAME = "QGROUNDCONTROL"; const QString ORG_NAME = "QGROUNDCONTROL.ORG"; //can be customized by forks to e.g. mycompany.com to maintain separate Settings for customized apps const QString ORG_DOMAIN = "org.qgroundcontrol";//can be customized by forks const int APPLICATIONVERSION = 203; // 2.0.3 } #endif // QGC_CONFIGURATION_H
Allow version suffix from command line
Allow version suffix from command line
C
agpl-3.0
hejunbok/qgroundcontrol,caoxiongkun/qgroundcontrol,catch-twenty-two/qgroundcontrol,iidioter/qgroundcontrol,RedoXyde/PX4_qGCS,iidioter/qgroundcontrol,Hunter522/qgroundcontrol,TheIronBorn/qgroundcontrol,jy723/qgroundcontrol,ethz-asl/qgc_asl,LIKAIMO/qgroundcontrol,catch-twenty-two/qgroundcontrol,UAVenture/qgroundcontrol,dagoodma/qgroundcontrol,scott-eddy/qgroundcontrol,iidioter/qgroundcontrol,fizzaly/qgroundcontrol,remspoor/qgroundcontrol,RedoXyde/PX4_qGCS,ethz-asl/qgc_asl,scott-eddy/qgroundcontrol,scott-eddy/qgroundcontrol,greenoaktree/qgroundcontrol,LIKAIMO/qgroundcontrol,devbharat/qgroundcontrol,greenoaktree/qgroundcontrol,hejunbok/qgroundcontrol,catch-twenty-two/qgroundcontrol,kd0aij/qgroundcontrol,jy723/qgroundcontrol,CornerOfSkyline/qgroundcontrol,Hunter522/qgroundcontrol,TheIronBorn/qgroundcontrol,jy723/qgroundcontrol,lis-epfl/qgroundcontrol,CornerOfSkyline/qgroundcontrol,catch-twenty-two/qgroundcontrol,devbharat/qgroundcontrol,cfelipesouza/qgroundcontrol,iidioter/qgroundcontrol,LIKAIMO/qgroundcontrol,ethz-asl/qgc_asl,fizzaly/qgroundcontrol,iidioter/qgroundcontrol,fizzaly/qgroundcontrol,dagoodma/qgroundcontrol,scott-eddy/qgroundcontrol,TheIronBorn/qgroundcontrol,fizzaly/qgroundcontrol,kd0aij/qgroundcontrol,BMP-TECH/qgroundcontrol,TheIronBorn/qgroundcontrol,ethz-asl/qgc_asl,fizzaly/qgroundcontrol,nado1688/qgroundcontrol,greenoaktree/qgroundcontrol,caoxiongkun/qgroundcontrol,nado1688/qgroundcontrol,BMP-TECH/qgroundcontrol,greenoaktree/qgroundcontrol,caoxiongkun/qgroundcontrol,fizzaly/qgroundcontrol,UAVenture/qgroundcontrol,caoxiongkun/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,iidioter/qgroundcontrol,kd0aij/qgroundcontrol,BMP-TECH/qgroundcontrol,TheIronBorn/qgroundcontrol,jy723/qgroundcontrol,hejunbok/qgroundcontrol,catch-twenty-two/qgroundcontrol,scott-eddy/qgroundcontrol,lis-epfl/qgroundcontrol,hejunbok/qgroundcontrol,dagoodma/qgroundcontrol,remspoor/qgroundcontrol,cfelipesouza/qgroundcontrol,cfelipesouza/qgroundcontrol,mihadyuk/qgroundcontrol,CornerOfSkyline/qgroundcontrol,CornerOfSkyline/qgroundcontrol,nado1688/qgroundcontrol,lis-epfl/qgroundcontrol,dagoodma/qgroundcontrol,UAVenture/qgroundcontrol,UAVenture/qgroundcontrol,remspoor/qgroundcontrol,kd0aij/qgroundcontrol,mihadyuk/qgroundcontrol,kd0aij/qgroundcontrol,lis-epfl/qgroundcontrol,remspoor/qgroundcontrol,ethz-asl/qgc_asl,devbharat/qgroundcontrol,nado1688/qgroundcontrol,kd0aij/qgroundcontrol,mihadyuk/qgroundcontrol,caoxiongkun/qgroundcontrol,RedoXyde/PX4_qGCS,lis-epfl/qgroundcontrol,mihadyuk/qgroundcontrol,devbharat/qgroundcontrol,jy723/qgroundcontrol,LIKAIMO/qgroundcontrol,Hunter522/qgroundcontrol,cfelipesouza/qgroundcontrol,cfelipesouza/qgroundcontrol,caoxiongkun/qgroundcontrol,mihadyuk/qgroundcontrol,scott-eddy/qgroundcontrol,LIKAIMO/qgroundcontrol,CornerOfSkyline/qgroundcontrol,hejunbok/qgroundcontrol,remspoor/qgroundcontrol,remspoor/qgroundcontrol,greenoaktree/qgroundcontrol,UAVenture/qgroundcontrol,jy723/qgroundcontrol,BMP-TECH/qgroundcontrol,CornerOfSkyline/qgroundcontrol,nado1688/qgroundcontrol,nado1688/qgroundcontrol,Hunter522/qgroundcontrol,BMP-TECH/qgroundcontrol,LIKAIMO/qgroundcontrol,RedoXyde/PX4_qGCS,catch-twenty-two/qgroundcontrol,hejunbok/qgroundcontrol,devbharat/qgroundcontrol,TheIronBorn/qgroundcontrol,RedoXyde/PX4_qGCS,dagoodma/qgroundcontrol,Hunter522/qgroundcontrol,greenoaktree/qgroundcontrol,dagoodma/qgroundcontrol,mihadyuk/qgroundcontrol,Hunter522/qgroundcontrol,BMP-TECH/qgroundcontrol,cfelipesouza/qgroundcontrol,devbharat/qgroundcontrol
c
## Code Before: /** @brief Polling interval in ms */ #define SERIAL_POLL_INTERVAL 4 /** @brief Heartbeat emission rate, in Hertz (times per second) */ #define MAVLINK_HEARTBEAT_DEFAULT_RATE 1 #define WITH_TEXT_TO_SPEECH 1 #define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_VERSION "v. 2.0.3 (beta)" namespace QGC { const QString APPNAME = "QGROUNDCONTROL"; const QString ORG_NAME = "QGROUNDCONTROL.ORG"; //can be customized by forks to e.g. mycompany.com to maintain separate Settings for customized apps const QString ORG_DOMAIN = "org.qgroundcontrol";//can be customized by forks const int APPLICATIONVERSION = 203; // 2.0.3 } #endif // QGC_CONFIGURATION_H ## Instruction: Allow version suffix from command line ## Code After: /** @brief Polling interval in ms */ #define SERIAL_POLL_INTERVAL 4 /** @brief Heartbeat emission rate, in Hertz (times per second) */ #define MAVLINK_HEARTBEAT_DEFAULT_RATE 1 #define WITH_TEXT_TO_SPEECH 1 #define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_VERSION_BASE "v2.0.3" #define QGC_APPLICATION_VERSION_SUFFIX ".234 (Daily Build)" #ifdef QGC_APPLICATION_VERSION_SUFFIX #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE QGC_APPLICATION_VERSION_SUFFIX #else #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE " (Developer Build)" #endif namespace QGC { const QString APPNAME = "QGROUNDCONTROL"; const QString ORG_NAME = "QGROUNDCONTROL.ORG"; //can be customized by forks to e.g. mycompany.com to maintain separate Settings for customized apps const QString ORG_DOMAIN = "org.qgroundcontrol";//can be customized by forks const int APPLICATIONVERSION = 203; // 2.0.3 } #endif // QGC_CONFIGURATION_H
# ... existing code ... #define WITH_TEXT_TO_SPEECH 1 #define QGC_APPLICATION_NAME "QGroundControl" #define QGC_APPLICATION_VERSION_BASE "v2.0.3" #define QGC_APPLICATION_VERSION_SUFFIX ".234 (Daily Build)" #ifdef QGC_APPLICATION_VERSION_SUFFIX #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE QGC_APPLICATION_VERSION_SUFFIX #else #define QGC_APPLICATION_VERSION QGC_APPLICATION_VERSION_BASE " (Developer Build)" #endif namespace QGC # ... rest of the code ...
a419f6dcb7968d6af1e3ef8eae29b723d96b5fd2
stayput/jinja2/__init__.py
stayput/jinja2/__init__.py
from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item): return self.env.from_string(item.contents).render(site=self.site, item=item)
from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item, site, *args, **kwargs): return self.env.from_string(item.contents).render(site=self.site, item=item)
Update for stayput master and ensure forward compatibility
Update for stayput master and ensure forward compatibility
Python
mit
veeti/stayput_jinja2
python
## Code Before: from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item): return self.env.from_string(item.contents).render(site=self.site, item=item) ## Instruction: Update for stayput master and ensure forward compatibility ## Code After: from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item, site, *args, **kwargs): return self.env.from_string(item.contents).render(site=self.site, item=item)
# ... existing code ... self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item, site, *args, **kwargs): return self.env.from_string(item.contents).render(site=self.site, item=item) # ... rest of the code ...
0992b2f0b1ef8a37bc9a3e72416c299c7b17455b
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
package org.wordpress.aztec.spans import android.content.Context import android.text.style.ImageSpan import android.text.style.ParagraphStyle import android.view.View import android.widget.Toast internal class AztecCommentSpan(html: StringBuilder, context: Context, drawable: Int) : ImageSpan(context, drawable), ParagraphStyle { val mHtml: StringBuilder = html fun getHtml(): StringBuilder { return mHtml } fun onClick(view: View) { Toast.makeText(view.context, mHtml.toString(), Toast.LENGTH_SHORT).show() } }
package org.wordpress.aztec.spans import android.content.Context import android.text.style.ImageSpan import android.view.View import android.widget.Toast internal class AztecCommentSpan(val mComment: AztecCommentSpan.Comment, context: Context, drawable: Int) : ImageSpan(context, drawable) { companion object { private val HTML_MORE: String = "<!--more-->" private val HTML_PAGE: String = "<!--nextpage-->" } enum class Comment constructor(internal val mHtml: String) { MORE(HTML_MORE), PAGE(HTML_PAGE) } fun onClick(view: View) { Toast.makeText(view.context, mComment.mHtml.toString(), Toast.LENGTH_SHORT).show() } }
Add more and page types to custom comment span
Add more and page types to custom comment span
Kotlin
mpl-2.0
wordpress-mobile/AztecEditor-Android,wordpress-mobile/AztecEditor-Android,wordpress-mobile/AztecEditor-Android
kotlin
## Code Before: package org.wordpress.aztec.spans import android.content.Context import android.text.style.ImageSpan import android.text.style.ParagraphStyle import android.view.View import android.widget.Toast internal class AztecCommentSpan(html: StringBuilder, context: Context, drawable: Int) : ImageSpan(context, drawable), ParagraphStyle { val mHtml: StringBuilder = html fun getHtml(): StringBuilder { return mHtml } fun onClick(view: View) { Toast.makeText(view.context, mHtml.toString(), Toast.LENGTH_SHORT).show() } } ## Instruction: Add more and page types to custom comment span ## Code After: package org.wordpress.aztec.spans import android.content.Context import android.text.style.ImageSpan import android.view.View import android.widget.Toast internal class AztecCommentSpan(val mComment: AztecCommentSpan.Comment, context: Context, drawable: Int) : ImageSpan(context, drawable) { companion object { private val HTML_MORE: String = "<!--more-->" private val HTML_PAGE: String = "<!--nextpage-->" } enum class Comment constructor(internal val mHtml: String) { MORE(HTML_MORE), PAGE(HTML_PAGE) } fun onClick(view: View) { Toast.makeText(view.context, mComment.mHtml.toString(), Toast.LENGTH_SHORT).show() } }
... import android.content.Context import android.text.style.ImageSpan import android.view.View import android.widget.Toast internal class AztecCommentSpan(val mComment: AztecCommentSpan.Comment, context: Context, drawable: Int) : ImageSpan(context, drawable) { companion object { private val HTML_MORE: String = "<!--more-->" private val HTML_PAGE: String = "<!--nextpage-->" } enum class Comment constructor(internal val mHtml: String) { MORE(HTML_MORE), PAGE(HTML_PAGE) } fun onClick(view: View) { Toast.makeText(view.context, mComment.mHtml.toString(), Toast.LENGTH_SHORT).show() } } ...
daac07ae27a9e67687a60c985b7a107607eaaafb
src/org/coffeebrew/lang/parser/CoffeeScriptParser.java
src/org/coffeebrew/lang/parser/CoffeeScriptParser.java
package org.coffeebrew.lang.parser; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.impl.source.tree.PlainTextFileElement; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /** * Parser implementation for CoffeeScript language support * * @author Michael Kessler * @since 0.1.0 */ public class CoffeeScriptParser implements PsiParser { @NotNull public ASTNode parse(IElementType root, PsiBuilder builder) { return new PlainTextFileElement(builder.getOriginalText()); } }
package org.coffeebrew.lang.parser; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.PlainTextTokenTypes; import com.intellij.psi.impl.source.tree.PlainTextASTFactory; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /** * Parser implementation for CoffeeScript language support * * @author Michael Kessler * @since 0.1.0 */ public class CoffeeScriptParser implements PsiParser { @NotNull public ASTNode parse(IElementType root, PsiBuilder builder) { return new PlainTextASTFactory().createLeaf(PlainTextTokenTypes.PLAIN_TEXT, builder.getOriginalText()); } }
Fix wrong AST Node parsing on idea-x
Fix wrong AST Node parsing on idea-x
Java
unlicense
consulo/consulo-coffeescript,netzpirat/coffee-brew
java
## Code Before: package org.coffeebrew.lang.parser; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.impl.source.tree.PlainTextFileElement; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /** * Parser implementation for CoffeeScript language support * * @author Michael Kessler * @since 0.1.0 */ public class CoffeeScriptParser implements PsiParser { @NotNull public ASTNode parse(IElementType root, PsiBuilder builder) { return new PlainTextFileElement(builder.getOriginalText()); } } ## Instruction: Fix wrong AST Node parsing on idea-x ## Code After: package org.coffeebrew.lang.parser; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.PlainTextTokenTypes; import com.intellij.psi.impl.source.tree.PlainTextASTFactory; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /** * Parser implementation for CoffeeScript language support * * @author Michael Kessler * @since 0.1.0 */ public class CoffeeScriptParser implements PsiParser { @NotNull public ASTNode parse(IElementType root, PsiBuilder builder) { return new PlainTextASTFactory().createLeaf(PlainTextTokenTypes.PLAIN_TEXT, builder.getOriginalText()); } }
// ... existing code ... import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.PlainTextTokenTypes; import com.intellij.psi.impl.source.tree.PlainTextASTFactory; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; // ... modified code ... @NotNull public ASTNode parse(IElementType root, PsiBuilder builder) { return new PlainTextASTFactory().createLeaf(PlainTextTokenTypes.PLAIN_TEXT, builder.getOriginalText()); } } // ... rest of the code ...
140973d538e645c87cd8de9dcd0efa8315599892
src/protocolsupport/protocol/packet/middleimpl/serverbound/play/v_6_7/EntityAction.java
src/protocolsupport/protocol/packet/middleimpl/serverbound/play/v_6_7/EntityAction.java
package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7; import io.netty.buffer.ByteBuf; import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction; import protocolsupport.utils.CollectionsUtils.ArrayMap; public class EntityAction extends MiddleEntityAction { private static final ArrayMap<Action> actionById = new ArrayMap<>( new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK), new ArrayMap.Entry<>(3, Action.LEAVE_BED), new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT), new ArrayMap.Entry<>(6, Action.STOP_JUMP) //this won't work now anyway, but still map it ); @Override public void readFromClientData(ByteBuf clientdata) { entityId = clientdata.readInt(); action = actionById.get(clientdata.readByte()); jumpBoost = clientdata.readInt(); } }
package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7; import io.netty.buffer.ByteBuf; import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction; import protocolsupport.utils.CollectionsUtils.ArrayMap; public class EntityAction extends MiddleEntityAction { private static final ArrayMap<Action> actionById = new ArrayMap<>( new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK), new ArrayMap.Entry<>(3, Action.LEAVE_BED), new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT), new ArrayMap.Entry<>(6, Action.STOP_JUMP), new ArrayMap.Entry<>(7, Action.OPEN_HORSE_INV) ); @Override public void readFromClientData(ByteBuf clientdata) { entityId = clientdata.readInt(); action = actionById.get(clientdata.readByte()); jumpBoost = clientdata.readInt(); } }
Add missing entity action mapping for horse inventory open for 1.6-1.7
Add missing entity action mapping for horse inventory open for 1.6-1.7
Java
agpl-3.0
ProtocolSupport/ProtocolSupport
java
## Code Before: package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7; import io.netty.buffer.ByteBuf; import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction; import protocolsupport.utils.CollectionsUtils.ArrayMap; public class EntityAction extends MiddleEntityAction { private static final ArrayMap<Action> actionById = new ArrayMap<>( new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK), new ArrayMap.Entry<>(3, Action.LEAVE_BED), new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT), new ArrayMap.Entry<>(6, Action.STOP_JUMP) //this won't work now anyway, but still map it ); @Override public void readFromClientData(ByteBuf clientdata) { entityId = clientdata.readInt(); action = actionById.get(clientdata.readByte()); jumpBoost = clientdata.readInt(); } } ## Instruction: Add missing entity action mapping for horse inventory open for 1.6-1.7 ## Code After: package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7; import io.netty.buffer.ByteBuf; import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction; import protocolsupport.utils.CollectionsUtils.ArrayMap; public class EntityAction extends MiddleEntityAction { private static final ArrayMap<Action> actionById = new ArrayMap<>( new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK), new ArrayMap.Entry<>(3, Action.LEAVE_BED), new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT), new ArrayMap.Entry<>(6, Action.STOP_JUMP), new ArrayMap.Entry<>(7, Action.OPEN_HORSE_INV) ); @Override public void readFromClientData(ByteBuf clientdata) { entityId = clientdata.readInt(); action = actionById.get(clientdata.readByte()); jumpBoost = clientdata.readInt(); } }
# ... existing code ... new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK), new ArrayMap.Entry<>(3, Action.LEAVE_BED), new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT), new ArrayMap.Entry<>(6, Action.STOP_JUMP), new ArrayMap.Entry<>(7, Action.OPEN_HORSE_INV) ); @Override # ... rest of the code ...
3a70e339637285355e594f9bec15481eae631a63
ibmcnx/config/j2ee/RoleBackup.py
ibmcnx/config/j2ee/RoleBackup.py
import sys import os import ibmcnx.functions # Only load commands if not initialized directly (call from menu) if __name__ == "__main__": execfile("ibmcnx/loadCnxApps.py") path = raw_input( "Please provide a path for your backup files: " ) ibmcnx.functions.checkBackupPath( path ) apps = AdminApp.list() appsList = apps.splitlines() for app in appsList: filename = path + "/" + app + ".txt" print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename} my_file = open( filename, 'w' ) my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) ) my_file.flush my_file.close()
import sys import os import ibmcnx.functions path = raw_input( "Please provide a path for your backup files: " ) ibmcnx.functions.checkBackupPath( path ) apps = AdminApp.list() appsList = apps.splitlines() for app in appsList: filename = path + "/" + app + ".txt" print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename} my_file = open( filename, 'w' ) my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) ) my_file.flush my_file.close()
Test all scripts on Windows
10: Test all scripts on Windows Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
python
## Code Before: import sys import os import ibmcnx.functions # Only load commands if not initialized directly (call from menu) if __name__ == "__main__": execfile("ibmcnx/loadCnxApps.py") path = raw_input( "Please provide a path for your backup files: " ) ibmcnx.functions.checkBackupPath( path ) apps = AdminApp.list() appsList = apps.splitlines() for app in appsList: filename = path + "/" + app + ".txt" print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename} my_file = open( filename, 'w' ) my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) ) my_file.flush my_file.close() ## Instruction: 10: Test all scripts on Windows Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 ## Code After: import sys import os import ibmcnx.functions path = raw_input( "Please provide a path for your backup files: " ) ibmcnx.functions.checkBackupPath( path ) apps = AdminApp.list() appsList = apps.splitlines() for app in appsList: filename = path + "/" + app + ".txt" print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename} my_file = open( filename, 'w' ) my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) ) my_file.flush my_file.close()
// ... existing code ... import sys import os import ibmcnx.functions path = raw_input( "Please provide a path for your backup files: " ) ibmcnx.functions.checkBackupPath( path ) // ... rest of the code ...
6bcb69ac540ea19d4c2e2c033e42fe5b5b24799e
izpack-api/src/main/java/com/izforge/izpack/api/data/binding/Listener.java
izpack-api/src/main/java/com/izforge/izpack/api/data/binding/Listener.java
package com.izforge.izpack.api.data.binding; /** * Listener entity * * @author Anthonin Bonnefoy */ public class Listener { private String classname; private Stage stage; private OsModel os; private String jar; public Listener(String classname, Stage stage, OsModel os, String jar) { this.classname = classname; this.stage = stage; this.os = os; this.jar = jar; } public String getClassname() { return classname; } public String getJar() { return jar; } public Stage getStage() { return stage; } public OsModel getOs() { return os; } @Override public String toString() { return "Listener{" + "classname='" + classname + '\'' + ", stage=" + stage + ", os=" + os + '}'; } }
package com.izforge.izpack.api.data.binding; import java.util.List; /** * Listener entity * * @author Anthonin Bonnefoy */ public class Listener { private String classname; private Stage stage; private List<OsModel> osList; private String jar; public Listener(String classname, Stage stage, List<OsModel> osList, String jar) { this.classname = classname; this.stage = stage; this.osList = osList; this.jar = jar; } public String getClassname() { return classname; } public String getJar() { return jar; } public Stage getStage() { return stage; } public List<OsModel> getOsList() { return osList; } @Override public String toString() { return "Listener{" + "classname='" + classname + '\'' + ", stage=" + stage + ", osList=" + osList + '}'; } }
Change os constraint to list of os in listener model
Change os constraint to list of os in listener model
Java
apache-2.0
maichler/izpack,rkrell/izpack,optotronic/izpack,bradcfisher/izpack,Murdock01/izpack,mtjandra/izpack,codehaus/izpack,optotronic/izpack,Murdock01/izpack,akuhtz/izpack,rsharipov/izpack,codehaus/izpack,codehaus/izpack,tomas-forsman/izpack,rsharipov/izpack,maichler/izpack,stenix71/izpack,mtjandra/izpack,mtjandra/izpack,izpack/izpack,yukron/izpack,optotronic/izpack,yukron/izpack,stenix71/izpack,rkrell/izpack,mtjandra/izpack,akuhtz/izpack,codehaus/izpack,stenix71/izpack,rsharipov/izpack,rkrell/izpack,stenix71/izpack,tomas-forsman/izpack,rkrell/izpack,rkrell/izpack,mtjandra/izpack,tomas-forsman/izpack,maichler/izpack,Helpstone/izpack,maichler/izpack,Murdock01/izpack,izpack/izpack,tomas-forsman/izpack,Helpstone/izpack,optotronic/izpack,tomas-forsman/izpack,bradcfisher/izpack,tomas-forsman/izpack,rkrell/izpack,izpack/izpack,stenix71/izpack,codehaus/izpack,izpack/izpack,Helpstone/izpack,Helpstone/izpack,optotronic/izpack,maichler/izpack,mtjandra/izpack,rsharipov/izpack,Helpstone/izpack,akuhtz/izpack,codehaus/izpack,optotronic/izpack,Murdock01/izpack,stenix71/izpack,bradcfisher/izpack,Murdock01/izpack,maichler/izpack,Murdock01/izpack,yukron/izpack,izpack/izpack,yukron/izpack,akuhtz/izpack,rkrell/izpack,yukron/izpack,rsharipov/izpack,Murdock01/izpack,bradcfisher/izpack,stenix71/izpack,bradcfisher/izpack,bradcfisher/izpack,codehaus/izpack,akuhtz/izpack,izpack/izpack,tomas-forsman/izpack,rsharipov/izpack,izpack/izpack,maichler/izpack,akuhtz/izpack,Helpstone/izpack,yukron/izpack,rsharipov/izpack,mtjandra/izpack,bradcfisher/izpack,optotronic/izpack,yukron/izpack,Helpstone/izpack,akuhtz/izpack
java
## Code Before: package com.izforge.izpack.api.data.binding; /** * Listener entity * * @author Anthonin Bonnefoy */ public class Listener { private String classname; private Stage stage; private OsModel os; private String jar; public Listener(String classname, Stage stage, OsModel os, String jar) { this.classname = classname; this.stage = stage; this.os = os; this.jar = jar; } public String getClassname() { return classname; } public String getJar() { return jar; } public Stage getStage() { return stage; } public OsModel getOs() { return os; } @Override public String toString() { return "Listener{" + "classname='" + classname + '\'' + ", stage=" + stage + ", os=" + os + '}'; } } ## Instruction: Change os constraint to list of os in listener model ## Code After: package com.izforge.izpack.api.data.binding; import java.util.List; /** * Listener entity * * @author Anthonin Bonnefoy */ public class Listener { private String classname; private Stage stage; private List<OsModel> osList; private String jar; public Listener(String classname, Stage stage, List<OsModel> osList, String jar) { this.classname = classname; this.stage = stage; this.osList = osList; this.jar = jar; } public String getClassname() { return classname; } public String getJar() { return jar; } public Stage getStage() { return stage; } public List<OsModel> getOsList() { return osList; } @Override public String toString() { return "Listener{" + "classname='" + classname + '\'' + ", stage=" + stage + ", osList=" + osList + '}'; } }
... package com.izforge.izpack.api.data.binding; import java.util.List; /** * Listener entity ... private Stage stage; private List<OsModel> osList; private String jar; public Listener(String classname, Stage stage, List<OsModel> osList, String jar) { this.classname = classname; this.stage = stage; this.osList = osList; this.jar = jar; } ... return stage; } public List<OsModel> getOsList() { return osList; } @Override ... return "Listener{" + "classname='" + classname + '\'' + ", stage=" + stage + ", osList=" + osList + '}'; } } ...
a103968558963c032db7294ed15560429861550d
django_filepicker/widgets.py
django_filepicker/widgets.py
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
Allow Filepicker JS version to be configured
Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.
Python
mit
filepicker/filepicker-django,filepicker/filepicker-django,FundedByMe/filepicker-django,FundedByMe/filepicker-django
python
## Code Before: from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,) ## Instruction: Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement. ## Code After: from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
// ... existing code ... from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE // ... rest of the code ...
c24a1c12b24c75827e87e46fd544c63acd648c4d
Source/Models/FORMFieldValidation.h
Source/Models/FORMFieldValidation.h
@import Foundation; @import CoreGraphics; @interface FORMFieldValidation : NSObject @property (nonatomic, getter = isRequired) BOOL required; @property (nonatomic) NSUInteger minimumLength; @property (nonatomic) NSInteger maximumLength; @property (nonatomic) NSString *format; @property (nonatomic) CGFloat minimumValue; @property (nonatomic) CGFloat maximumValue; - (instancetype)initWithDictionary:(NSDictionary *)dictionary; @end
@import Foundation; @import CoreGraphics; @interface FORMFieldValidation : NSObject @property (nonatomic, getter = isRequired) BOOL required; @property (nonatomic) NSUInteger minimumLength; @property (nonatomic) NSInteger maximumLength; @property (nonatomic) NSString *format; @property (nonatomic) CGFloat minimumValue; @property (nonatomic) CGFloat maximumValue; - (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; @end
Add designated initializer macro to field validation
Add designated initializer macro to field validation
C
mit
wangmb/Form,wangmb/Form,kalsariyac/Form,kalsariyac/Form,Jamonek/Form,steve21124/Form,0x73/Form,0x73/Form,Jamonek/Form,KevinJacob/Form,KevinJacob/Form,steve21124/Form,kalsariyac/Form,wangmb/Form,steve21124/Form,fhchina/Form,fhchina/Form,fhchina/Form,Jamonek/Form,KevinJacob/Form
c
## Code Before: @import Foundation; @import CoreGraphics; @interface FORMFieldValidation : NSObject @property (nonatomic, getter = isRequired) BOOL required; @property (nonatomic) NSUInteger minimumLength; @property (nonatomic) NSInteger maximumLength; @property (nonatomic) NSString *format; @property (nonatomic) CGFloat minimumValue; @property (nonatomic) CGFloat maximumValue; - (instancetype)initWithDictionary:(NSDictionary *)dictionary; @end ## Instruction: Add designated initializer macro to field validation ## Code After: @import Foundation; @import CoreGraphics; @interface FORMFieldValidation : NSObject @property (nonatomic, getter = isRequired) BOOL required; @property (nonatomic) NSUInteger minimumLength; @property (nonatomic) NSInteger maximumLength; @property (nonatomic) NSString *format; @property (nonatomic) CGFloat minimumValue; @property (nonatomic) CGFloat maximumValue; - (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; @end
... @property (nonatomic) CGFloat minimumValue; @property (nonatomic) CGFloat maximumValue; - (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; @end ...
ae2f1014bbe83d64f17fee6a9ebd2c12cdc9a1bf
app/main/errors.py
app/main/errors.py
from flask import render_template from app.main import main @main.app_errorhandler(400) def bad_request(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 400 @main.app_errorhandler(404) def page_not_found(e): return render_template("errors/404.html", **main.config['BASE_TEMPLATE_DATA']), 404 @main.app_errorhandler(500) def exception(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 500 @main.app_errorhandler(503) def service_unavailable(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 503
from flask import render_template from app.main import main from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error(e): return _render_error_template(e.status_code) @main.app_errorhandler(400) def bad_request(e): return _render_error_template(400) @main.app_errorhandler(404) def page_not_found(e): return _render_error_template(404) @main.app_errorhandler(500) def exception(e): return _render_error_template(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_template(503) def _render_error_template(status_code): return render_template( _get_template(status_code), **main.config['BASE_TEMPLATE_DATA'] ), status_code def _get_template(status_code): if status_code == 404: return "errors/404.html" else: return "errors/500.html"
Add APIError flask error handler
Add APIError flask error handler This is modelled after the similar change in the supplier frontend https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5
Python
mit
alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
python
## Code Before: from flask import render_template from app.main import main @main.app_errorhandler(400) def bad_request(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 400 @main.app_errorhandler(404) def page_not_found(e): return render_template("errors/404.html", **main.config['BASE_TEMPLATE_DATA']), 404 @main.app_errorhandler(500) def exception(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 500 @main.app_errorhandler(503) def service_unavailable(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 503 ## Instruction: Add APIError flask error handler This is modelled after the similar change in the supplier frontend https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5 ## Code After: from flask import render_template from app.main import main from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error(e): return _render_error_template(e.status_code) @main.app_errorhandler(400) def bad_request(e): return _render_error_template(400) @main.app_errorhandler(404) def page_not_found(e): return _render_error_template(404) @main.app_errorhandler(500) def exception(e): return _render_error_template(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_template(503) def _render_error_template(status_code): return render_template( _get_template(status_code), **main.config['BASE_TEMPLATE_DATA'] ), status_code def _get_template(status_code): if status_code == 404: return "errors/404.html" else: return "errors/500.html"
... from flask import render_template from app.main import main from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error(e): return _render_error_template(e.status_code) @main.app_errorhandler(400) def bad_request(e): return _render_error_template(400) @main.app_errorhandler(404) def page_not_found(e): return _render_error_template(404) @main.app_errorhandler(500) def exception(e): return _render_error_template(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_template(503) def _render_error_template(status_code): return render_template( _get_template(status_code), **main.config['BASE_TEMPLATE_DATA'] ), status_code def _get_template(status_code): if status_code == 404: return "errors/404.html" else: return "errors/500.html" ...
b7b27486d7066853dcf0fa325dd2d542167bb042
src/lib/fmt/fmt_escapecharxml.c
src/lib/fmt/fmt_escapecharxml.c
size_t fmt_escapecharxml(char* dest,uint32_t ch) { char a[FMT_LONG], b[FMT_XLONG]; const char* s; size_t i,j; switch (ch) { case '&': s="&amp;"; goto string; case '<': s="&lt;"; goto string; case '>': s="&gt;"; goto string; case '\'': s="&apos;"; goto string; case '"': s="&quot;"; goto string; default: a[i=fmt_ulong(a,ch)]=0; b[0]='x'; b[j=fmt_xlong(b+1,ch)+1]=0; s=a; if (i>j) { s=b; i=j; } if (dest) { dest[0]='&'; dest[1]='#'; byte_copy(dest+2,i,s); dest[i+2]=';'; } return i+3; } string: return fmt_str(dest,s); } #ifdef __GNUC__ size_t fmt_escapecharhtml(char* dest,uint32_t ch) __attribute__((__alias__("fmt_escapecharxml"))); #endif
size_t fmt_escapecharxml(char* dest,uint32_t ch) { char a[FMT_LONG], b[FMT_XLONG]; const char* s; size_t i,j; switch (ch) { case '&': s="&amp;"; goto string; case '<': s="&lt;"; goto string; case '>': s="&gt;"; goto string; case '\'': s="&apos;"; goto string; case '"': s="&quot;"; goto string; default: a[i=fmt_ulong(a,ch)]=0; b[0]='x'; b[j=fmt_xlong(b+1,ch)+1]=0; s=a; if (i>j) { s=b; i=j; } if (dest) { dest[0]='&'; dest[1]='#'; byte_copy(dest+2,i,s); dest[i+2]=';'; } return i+3; } string: return fmt_str(dest,s); } #if defined(__GNUC__) && !defined(__llvm__) size_t fmt_escapecharhtml(char* dest,uint32_t ch) __attribute__((__alias__("fmt_escapecharxml"))); #endif
Choose only gcc to execute a specific portion of code
fmt: Choose only gcc to execute a specific portion of code The specific portion of the code needs to be executed by a gcc compiler, for that reason is used the __GNUC__ macro. It appears, that the LLVM compiler, which uses the __llvm__ macro, uses as well the __GNUC__ macro (possible for compatibility???). This change check if the __llvm__ is check as well, and if it is the code is not executed. Issue: https://github.com/svagionitis/cross-platform-code/issues/1
C
mit
svagionitis/cross-platform-code,svagionitis/cross-platform-code
c
## Code Before: size_t fmt_escapecharxml(char* dest,uint32_t ch) { char a[FMT_LONG], b[FMT_XLONG]; const char* s; size_t i,j; switch (ch) { case '&': s="&amp;"; goto string; case '<': s="&lt;"; goto string; case '>': s="&gt;"; goto string; case '\'': s="&apos;"; goto string; case '"': s="&quot;"; goto string; default: a[i=fmt_ulong(a,ch)]=0; b[0]='x'; b[j=fmt_xlong(b+1,ch)+1]=0; s=a; if (i>j) { s=b; i=j; } if (dest) { dest[0]='&'; dest[1]='#'; byte_copy(dest+2,i,s); dest[i+2]=';'; } return i+3; } string: return fmt_str(dest,s); } #ifdef __GNUC__ size_t fmt_escapecharhtml(char* dest,uint32_t ch) __attribute__((__alias__("fmt_escapecharxml"))); #endif ## Instruction: fmt: Choose only gcc to execute a specific portion of code The specific portion of the code needs to be executed by a gcc compiler, for that reason is used the __GNUC__ macro. It appears, that the LLVM compiler, which uses the __llvm__ macro, uses as well the __GNUC__ macro (possible for compatibility???). This change check if the __llvm__ is check as well, and if it is the code is not executed. Issue: https://github.com/svagionitis/cross-platform-code/issues/1 ## Code After: size_t fmt_escapecharxml(char* dest,uint32_t ch) { char a[FMT_LONG], b[FMT_XLONG]; const char* s; size_t i,j; switch (ch) { case '&': s="&amp;"; goto string; case '<': s="&lt;"; goto string; case '>': s="&gt;"; goto string; case '\'': s="&apos;"; goto string; case '"': s="&quot;"; goto string; default: a[i=fmt_ulong(a,ch)]=0; b[0]='x'; b[j=fmt_xlong(b+1,ch)+1]=0; s=a; if (i>j) { s=b; i=j; } if (dest) { dest[0]='&'; dest[1]='#'; byte_copy(dest+2,i,s); dest[i+2]=';'; } return i+3; } string: return fmt_str(dest,s); } #if defined(__GNUC__) && !defined(__llvm__) size_t fmt_escapecharhtml(char* dest,uint32_t ch) __attribute__((__alias__("fmt_escapecharxml"))); #endif
... return fmt_str(dest,s); } #if defined(__GNUC__) && !defined(__llvm__) size_t fmt_escapecharhtml(char* dest,uint32_t ch) __attribute__((__alias__("fmt_escapecharxml"))); #endif ...
d078ec00d5553b0985d9c724a223c74b80b2c5ab
grains/grains.py
grains/grains.py
square = [x for x in range(1, 65)] grains = [2 ** x for x in range(0, 65)] board = zip(square, grains) print (board)
square = [x for x in range(1, 65)] grains = [2 ** x for x in range(0, 65)] board = dict(zip(square, grains)) print type(board) for k, v in board.iteritems(): print k, v
Convert zipped list to dictionary
Convert zipped list to dictionary
Python
mit
amalshehu/exercism-python
python
## Code Before: square = [x for x in range(1, 65)] grains = [2 ** x for x in range(0, 65)] board = zip(square, grains) print (board) ## Instruction: Convert zipped list to dictionary ## Code After: square = [x for x in range(1, 65)] grains = [2 ** x for x in range(0, 65)] board = dict(zip(square, grains)) print type(board) for k, v in board.iteritems(): print k, v
# ... existing code ... square = [x for x in range(1, 65)] grains = [2 ** x for x in range(0, 65)] board = dict(zip(square, grains)) print type(board) for k, v in board.iteritems(): print k, v # ... rest of the code ...
bd3cb20453d044882fc476e55e2aade8c5c81ea7
2/ConfNEP.py
2/ConfNEP.py
"""A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observations. Net ecosystem productivity (``nep``) is a CMIP5 standard output provided by the MsTMIP models, and is the inverse of net ecosystem exchange (``nee``), for which benchmark datasets are provided in ILAMB. """ def __init__(self, **keywords): super(ConfNEP, self).__init__(**keywords) def stageData(self, m): obs = Variable(filename=self.source, variable_name=self.variable) self._checkRegions(obs) obs.data *= -1.0 # Reverse sign of benchmark data. mod = m.extractTimeSeries(self.variable, alt_vars=self.alternate_vars) mod.data *= -1.0 # Reverse sign of modified model outputs. obs, mod = MakeComparable(obs, mod, clip_ref=True, logstring="[%s][%s]" % (self.longname, m.name)) return obs, mod
"""A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observations. Net ecosystem productivity (``nep``) is a CMIP5 standard output provided by the MsTMIP models, and is the inverse of net ecosystem exchange (``nee``), for which benchmark datasets are provided in ILAMB. """ def __init__(self, **keywords): super(ConfNEP, self).__init__(**keywords) def stageData(self, m): obs = Variable(filename=self.source, variable_name=self.variable) obs.data *= -1.0 # Reverse sign of benchmark data. mod = m.extractTimeSeries(self.variable, alt_vars=self.alternate_vars) mod.data *= -1.0 # Reverse sign of modified model outputs. obs, mod = MakeComparable(obs, mod, clip_ref=True, logstring="[%s][%s]" % (self.longname, m.name)) return obs, mod
Remove call to _checkRegions method
Remove call to _checkRegions method At one point it was a method of the super (I believe), but it's no longer there.
Python
mit
permamodel/ILAMB-experiments
python
## Code Before: """A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observations. Net ecosystem productivity (``nep``) is a CMIP5 standard output provided by the MsTMIP models, and is the inverse of net ecosystem exchange (``nee``), for which benchmark datasets are provided in ILAMB. """ def __init__(self, **keywords): super(ConfNEP, self).__init__(**keywords) def stageData(self, m): obs = Variable(filename=self.source, variable_name=self.variable) self._checkRegions(obs) obs.data *= -1.0 # Reverse sign of benchmark data. mod = m.extractTimeSeries(self.variable, alt_vars=self.alternate_vars) mod.data *= -1.0 # Reverse sign of modified model outputs. obs, mod = MakeComparable(obs, mod, clip_ref=True, logstring="[%s][%s]" % (self.longname, m.name)) return obs, mod ## Instruction: Remove call to _checkRegions method At one point it was a method of the super (I believe), but it's no longer there. ## Code After: """A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observations. Net ecosystem productivity (``nep``) is a CMIP5 standard output provided by the MsTMIP models, and is the inverse of net ecosystem exchange (``nee``), for which benchmark datasets are provided in ILAMB. """ def __init__(self, **keywords): super(ConfNEP, self).__init__(**keywords) def stageData(self, m): obs = Variable(filename=self.source, variable_name=self.variable) obs.data *= -1.0 # Reverse sign of benchmark data. mod = m.extractTimeSeries(self.variable, alt_vars=self.alternate_vars) mod.data *= -1.0 # Reverse sign of modified model outputs. obs, mod = MakeComparable(obs, mod, clip_ref=True, logstring="[%s][%s]" % (self.longname, m.name)) return obs, mod
// ... existing code ... def stageData(self, m): obs = Variable(filename=self.source, variable_name=self.variable) obs.data *= -1.0 # Reverse sign of benchmark data. mod = m.extractTimeSeries(self.variable, // ... rest of the code ...
ac30f52aff51dce892e79ce773e84f2458635d1c
digestive/entropy.py
digestive/entropy.py
from collections import Counter from math import log2 from digestive import Sink # TODO: stash intermediate histograms in multiple Counters? # TODO: output as a spark # TODO: output as plot class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter = Counter() def update(self, data): self.length += len(data) self.counter.update(data) def digest(self): # calculate binary entropy as -Σ(1…n) p_i × log₂(p_i) entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values()) return '{:.8f}'.format(entropy)
from collections import Counter from math import log2 from digestive import Sink class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter = Counter() def update(self, data): self.length += len(data) self.counter.update(data) def digest(self): # calculate binary entropy as -Σ(1…n) p_i × log₂(p_i) entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values()) return '{:.8f}'.format(entropy)
Remove TODO's converted to issues
Remove TODO's converted to issues
Python
isc
akaIDIOT/Digestive
python
## Code Before: from collections import Counter from math import log2 from digestive import Sink # TODO: stash intermediate histograms in multiple Counters? # TODO: output as a spark # TODO: output as plot class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter = Counter() def update(self, data): self.length += len(data) self.counter.update(data) def digest(self): # calculate binary entropy as -Σ(1…n) p_i × log₂(p_i) entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values()) return '{:.8f}'.format(entropy) ## Instruction: Remove TODO's converted to issues ## Code After: from collections import Counter from math import log2 from digestive import Sink class Entropy(Sink): def __init__(self): super().__init__('entropy') self.length = 0 self.counter = Counter() def update(self, data): self.length += len(data) self.counter.update(data) def digest(self): # calculate binary entropy as -Σ(1…n) p_i × log₂(p_i) entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values()) return '{:.8f}'.format(entropy)
# ... existing code ... from digestive import Sink class Entropy(Sink): def __init__(self): super().__init__('entropy') # ... rest of the code ...
488ec333acc080f989bc5e2517aa5d709874f14c
AgreementMaker-OSGi/AgreementMaker-Core/src/am/app/mappingEngine/qualityEvaluation/metrics/ufl/VarianceMatcherDisagreement.java
AgreementMaker-OSGi/AgreementMaker-Core/src/am/app/mappingEngine/qualityEvaluation/metrics/ufl/VarianceMatcherDisagreement.java
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance return computeVariance(signatureVector); } }
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance // because variance of similarity values can be a maximum of 0.5, we // multiply by 2 to get a metric from 0 to 1.0 return 2 * computeVariance(signatureVector); } }
Normalize the variance to 1.0 (from 0.5)
Normalize the variance to 1.0 (from 0.5)
Java
agpl-3.0
sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker
java
## Code Before: package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance return computeVariance(signatureVector); } } ## Instruction: Normalize the variance to 1.0 (from 0.5) ## Code After: package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance // because variance of similarity values can be a maximum of 0.5, we // multiply by 2 to get a metric from 0 to 1.0 return 2 * computeVariance(signatureVector); } }
... } // return the computed variance // because variance of similarity values can be a maximum of 0.5, we // multiply by 2 to get a metric from 0 to 1.0 return 2 * computeVariance(signatureVector); } } ...