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
7202559105591ebcdbff712784631464d97545da
app/src/main/java/net/squanchy/about/licenses/License.java
app/src/main/java/net/squanchy/about/licenses/License.java
package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } }
package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0 License", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0 licenses", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT License", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License 1.1", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } }
Tweak license labels for consistency
Tweak license labels for consistency
Java
apache-2.0
squanchy-dev/squanchy-android,squanchy-dev/squanchy-android,squanchy-dev/squanchy-android
java
## Code Before: package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } } ## Instruction: Tweak license labels for consistency ## Code After: package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0 License", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0 licenses", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT License", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License 1.1", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } }
# ... existing code ... import net.squanchy.R; enum License { APACHE_2("Apache 2.0 License", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0 licenses", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT License", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License 1.1", R.string.license_notice_open_font_license); private final String label; # ... rest of the code ...
a55f816072503241bd1ff4e953de12a7b48af4ac
backend/unimeet/helpers.py
backend/unimeet/helpers.py
from .models import School, User import re import string import random def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(40)) user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() print 'Email:', email, 'Password:', password, 'Token:', token # TODO: Send signup mail to user
from .models import School, User import re import string import random from mail import send_mail def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(40)) user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() send_mail(email, password, 'welcome')
Use send_mail in signup helper function
Use send_mail in signup helper function
Python
mit
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
python
## Code Before: from .models import School, User import re import string import random def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(40)) user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() print 'Email:', email, 'Password:', password, 'Token:', token # TODO: Send signup mail to user ## Instruction: Use send_mail in signup helper function ## Code After: from .models import School, User import re import string import random from mail import send_mail def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(40)) user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() send_mail(email, password, 'welcome')
... import re import string import random from mail import send_mail def get_school_list(): ... user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() send_mail(email, password, 'welcome') ...
fd4f7154130ed8bb66d4209366825ebf2d32b62f
base/src/main/java/uk/ac/ebi/atlas/bioentity/properties/PropertyLink.java
base/src/main/java/uk/ac/ebi/atlas/bioentity/properties/PropertyLink.java
package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; // Used in bioentity-information.jsp public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } }
package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } }
Remove comment, it’s a lie
Remove comment, it’s a lie
Java
apache-2.0
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
java
## Code Before: package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; // Used in bioentity-information.jsp public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } } ## Instruction: Remove comment, it’s a lie ## Code After: package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } }
... import com.google.gson.JsonObject; public class PropertyLink { private String text; ... result.addProperty("relevance", relevance); return result; } } ...
a2b1d10e042d135c3c014622ffeabd7e96a46f9f
tests/test_update_target.py
tests/test_update_target.py
import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ target_id = client.add_target( name='x', width=1, image=high_quality_image, ) client.update_target(target_id=target_id) result = client.get_target(target_id=target_id) expected_keys = { 'target_id', 'active_flag', 'name', 'width', 'tracking_rating', 'reco_rating', } assert result['target_record'].keys() == expected_keys def test_no_such_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ An ``UnknownTarget`` exception is raised when getting a target which does not exist. """ with pytest.raises(UnknownTarget): client.get_target(target_id='a')
import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ # target_id = client.add_target( # name='x', # width=1, # image=high_quality_image, # ) # # client.update_target(target_id=target_id) # result = client.get_target(target_id=target_id) # expected_keys = { # 'target_id', # 'active_flag', # 'name', # 'width', # 'tracking_rating', # 'reco_rating', # } # assert result['target_record'].keys() == expected_keys # # def test_no_such_target( # self, # client: VWS, # high_quality_image: io.BytesIO, # ) -> None: # """ # An ``UnknownTarget`` exception is raised when getting a target which # does not exist. # """ # with pytest.raises(UnknownTarget): # client.get_target(target_id='a')
Comment out part done code
Comment out part done code
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
python
## Code Before: import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ target_id = client.add_target( name='x', width=1, image=high_quality_image, ) client.update_target(target_id=target_id) result = client.get_target(target_id=target_id) expected_keys = { 'target_id', 'active_flag', 'name', 'width', 'tracking_rating', 'reco_rating', } assert result['target_record'].keys() == expected_keys def test_no_such_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ An ``UnknownTarget`` exception is raised when getting a target which does not exist. """ with pytest.raises(UnknownTarget): client.get_target(target_id='a') ## Instruction: Comment out part done code ## Code After: import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ # target_id = client.add_target( # name='x', # width=1, # image=high_quality_image, # ) # # client.update_target(target_id=target_id) # result = client.get_target(target_id=target_id) # expected_keys = { # 'target_id', # 'active_flag', # 'name', # 'width', # 'tracking_rating', # 'reco_rating', # } # assert result['target_record'].keys() == expected_keys # # def test_no_such_target( # self, # client: VWS, # high_quality_image: io.BytesIO, # ) -> None: # """ # An ``UnknownTarget`` exception is raised when getting a target which # does not exist. # """ # with pytest.raises(UnknownTarget): # client.get_target(target_id='a')
... """ Details of a target are returned by ``get_target``. """ # target_id = client.add_target( # name='x', # width=1, # image=high_quality_image, # ) # # client.update_target(target_id=target_id) # result = client.get_target(target_id=target_id) # expected_keys = { # 'target_id', # 'active_flag', # 'name', # 'width', # 'tracking_rating', # 'reco_rating', # } # assert result['target_record'].keys() == expected_keys # # def test_no_such_target( # self, # client: VWS, # high_quality_image: io.BytesIO, # ) -> None: # """ # An ``UnknownTarget`` exception is raised when getting a target which # does not exist. # """ # with pytest.raises(UnknownTarget): # client.get_target(target_id='a') ...
6996df37e2489b2beabea65feb597cebffcf2563
common/filesystem/src/main/java/roart/common/filesystem/FileSystemMessageResult.java
common/filesystem/src/main/java/roart/common/filesystem/FileSystemMessageResult.java
package roart.common.filesystem; import java.util.Map; import roart.common.inmemory.model.InmemoryMessage; import roart.common.model.FileObject; public class FileSystemMessageResult extends FileSystemResult { public Map<FileObject, InmemoryMessage> message; }
package roart.common.filesystem; import java.util.Map; import roart.common.inmemory.model.InmemoryMessage; import roart.common.model.FileObject; public class FileSystemMessageResult extends FileSystemResult { public Map<String, InmemoryMessage> message; }
Read file batch transfer (I38).
Read file batch transfer (I38).
Java
agpl-3.0
rroart/aether,rroart/aether,rroart/aether,rroart/aether,rroart/aether
java
## Code Before: package roart.common.filesystem; import java.util.Map; import roart.common.inmemory.model.InmemoryMessage; import roart.common.model.FileObject; public class FileSystemMessageResult extends FileSystemResult { public Map<FileObject, InmemoryMessage> message; } ## Instruction: Read file batch transfer (I38). ## Code After: package roart.common.filesystem; import java.util.Map; import roart.common.inmemory.model.InmemoryMessage; import roart.common.model.FileObject; public class FileSystemMessageResult extends FileSystemResult { public Map<String, InmemoryMessage> message; }
... import roart.common.model.FileObject; public class FileSystemMessageResult extends FileSystemResult { public Map<String, InmemoryMessage> message; } ...
1eb9830485ec82713d3e8d4d1e13ea1fdc1733c6
airtable.py
airtable.py
import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) return r.json()
import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) if r.status_code == requests.codes.ok: return r.json() else: print(r.json) return False
Add quick error messaging for easier debugging
Add quick error messaging for easier debugging
Python
mit
MeetMangrove/location-bot
python
## Code Before: import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) return r.json() ## Instruction: Add quick error messaging for easier debugging ## Code After: import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) if r.status_code == requests.codes.ok: return r.json() else: print(r.json) return False
// ... existing code ... h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) if r.status_code == requests.codes.ok: return r.json() else: print(r.json) return False // ... rest of the code ...
0cebce08025844ae1e0154b7332779be0567e9ab
ipywidgets/widgets/__init__.py
ipywidgets/widgets/__init__.py
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
Add ScrollableDropdown import to ipywidgets
Add ScrollableDropdown import to ipywidgets
Python
bsd-3-clause
ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets
python
## Code Before: from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout ## Instruction: Add ScrollableDropdown import to ipywidgets ## Code After: from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
// ... existing code ... from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller // ... rest of the code ...
13b602c50f3be62b2a3a8b267ba00b685fc0c7fe
python/ecep/portal/migrations/0011_auto_20160518_1211.py
python/ecep/portal/migrations/0011_auto_20160518_1211.py
from __future__ import unicode_literals from django.db import models, migrations def populate_enrollment_info(apps, schema_editor): """ Populate the Enrollment info based on static text """ Location = apps.get_model('portal', 'Location') for loc in Location.objects.all(): if loc.is_cps_based: loc.enrollment_en = """<p>Visit a child-friendly location near you:</p><ul><li><strong>Loop</strong> 42 W. Madison Street Hours: 9:00 AM - 5:00 PM</li><li><strong>Colman</strong> 4655 S. Dearborn Street Hours: 9:00 AM - 5:00 PM</li><li><strong>Hall Mall</strong> 4638 W. Diversey Avenue Hours 8:00 AM - 5:00 PM</li></ul><p>All sites are open until 7:00 PM on Wednesdays!</p><p>Many people find it helpful to make a plan to visit. You can make your plan <a href="/static/files/enrollment-plan-cps.pdf">here</a>.</p>""" loc.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0010_auto_20160518_1210'), ] operations = [ migrations.RunPython(populate_enrollment_info), ]
from __future__ import unicode_literals from django.db import models, migrations def populate_enrollment_info(apps, schema_editor): """ Populate the Enrollment info based on static text """ Location = apps.get_model('portal', 'Location') for loc in Location.objects.all(): if loc.is_cps_based: loc.enrollment_en = """<p>Chicago Public Schools early childhood school based preschool programs work to ensure children ages 3 and 4 years old, particularly those most in need, have access to high-quality programs. Schools are committed to creating an engaging, developmentally appropriate learning environment that supports and respects the unique potential of each individual child through best professional practices, parent engagement, and community involvement.</p>""" loc.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0010_auto_20160518_1210'), ] operations = [ migrations.RunPython(populate_enrollment_info), ]
Update data migration with new CPS description
Update data migration with new CPS description
Python
mit
smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning
python
## Code Before: from __future__ import unicode_literals from django.db import models, migrations def populate_enrollment_info(apps, schema_editor): """ Populate the Enrollment info based on static text """ Location = apps.get_model('portal', 'Location') for loc in Location.objects.all(): if loc.is_cps_based: loc.enrollment_en = """<p>Visit a child-friendly location near you:</p><ul><li><strong>Loop</strong> 42 W. Madison Street Hours: 9:00 AM - 5:00 PM</li><li><strong>Colman</strong> 4655 S. Dearborn Street Hours: 9:00 AM - 5:00 PM</li><li><strong>Hall Mall</strong> 4638 W. Diversey Avenue Hours 8:00 AM - 5:00 PM</li></ul><p>All sites are open until 7:00 PM on Wednesdays!</p><p>Many people find it helpful to make a plan to visit. You can make your plan <a href="/static/files/enrollment-plan-cps.pdf">here</a>.</p>""" loc.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0010_auto_20160518_1210'), ] operations = [ migrations.RunPython(populate_enrollment_info), ] ## Instruction: Update data migration with new CPS description ## Code After: from __future__ import unicode_literals from django.db import models, migrations def populate_enrollment_info(apps, schema_editor): """ Populate the Enrollment info based on static text """ Location = apps.get_model('portal', 'Location') for loc in Location.objects.all(): if loc.is_cps_based: loc.enrollment_en = """<p>Chicago Public Schools early childhood school based preschool programs work to ensure children ages 3 and 4 years old, particularly those most in need, have access to high-quality programs. Schools are committed to creating an engaging, developmentally appropriate learning environment that supports and respects the unique potential of each individual child through best professional practices, parent engagement, and community involvement.</p>""" loc.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0010_auto_20160518_1210'), ] operations = [ migrations.RunPython(populate_enrollment_info), ]
// ... existing code ... for loc in Location.objects.all(): if loc.is_cps_based: loc.enrollment_en = """<p>Chicago Public Schools early childhood school based preschool programs work to ensure children ages 3 and 4 years old, particularly those most in need, have access to high-quality programs. Schools are committed to creating an engaging, developmentally appropriate learning environment that supports and respects the unique potential of each individual child through best professional practices, parent engagement, and community involvement.</p>""" loc.save() // ... rest of the code ...
5d2649fc005e514452c8d83f103b4fd2c5b03519
tailor/output/printer.py
tailor/output/printer.py
import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg)
import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column + 1) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg)
Increment column to be printed by 1
Increment column to be printed by 1
Python
mit
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
python
## Code Before: import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg) ## Instruction: Increment column to be printed by 1 ## Code After: import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column + 1) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg)
// ... existing code ... def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column + 1) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg) // ... rest of the code ...
c90dbc5007b5627b264493c2d16af79cff9c2af0
joku/checks.py
joku/checks.py
from discord.ext.commands import CheckFailure def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True
from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
Add better custom has_permission check.
Add better custom has_permission check.
Python
mit
MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame
python
## Code Before: from discord.ext.commands import CheckFailure def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True ## Instruction: Add better custom has_permission check. ## Code After: from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
// ... existing code ... from discord.ext.commands import CheckFailure, check def is_owner(ctx): // ... modified code ... if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate) // ... rest of the code ...
ed69ace7f6065ec1b3dd2f2de3a0d5b56ac28366
climatemaps/data.py
climatemaps/data.py
import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 with open('./data/cloud/ccld6190.dat') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 ymax = 90.25 lonrange = numpy.arange(xmin, xmax, grid_size) latrange = numpy.arange(ymin, ymax, grid_size) Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0]))) print(len(lonrange)) print(len(latrange)) i = 0 for line in lines: line_n += 1 if line_n < 3: # skip header continue if i >= nrows: # read one month break value = '' values = [] counter = 1 j = 0 for char in line: value += char if counter % digits == 0: Z[i][j] = float(value) values.append(value) value = '' j += 1 counter += 1 i += 1 return latrange, lonrange, Z
import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 monthnr = 3 with open('./data/cloud/ccld6190.dat', 'r') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 ymax = 90.25 lonrange = numpy.arange(xmin, xmax, grid_size) latrange = numpy.arange(ymin, ymax, grid_size) Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0]))) print(len(lonrange)) print(len(latrange)) i = 0 rown = 0 for line in lines: line_n += 1 if line_n < 3: # skip header continue if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month rown += 1 continue value = '' counter = 1 j = 0 for char in line: value += char if counter % digits == 0: value = float(value) if value < 0: value = numpy.nan Z[i][j] = value value = '' j += 1 counter += 1 i += 1 rown += 1 return latrange, lonrange, Z
Create argument to select month to import
Create argument to select month to import
Python
mit
bartromgens/climatemaps,bartromgens/climatemaps,bartromgens/climatemaps
python
## Code Before: import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 with open('./data/cloud/ccld6190.dat') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 ymax = 90.25 lonrange = numpy.arange(xmin, xmax, grid_size) latrange = numpy.arange(ymin, ymax, grid_size) Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0]))) print(len(lonrange)) print(len(latrange)) i = 0 for line in lines: line_n += 1 if line_n < 3: # skip header continue if i >= nrows: # read one month break value = '' values = [] counter = 1 j = 0 for char in line: value += char if counter % digits == 0: Z[i][j] = float(value) values.append(value) value = '' j += 1 counter += 1 i += 1 return latrange, lonrange, Z ## Instruction: Create argument to select month to import ## Code After: import numpy def import_climate_data(): ncols = 720 nrows = 360 digits = 5 monthnr = 3 with open('./data/cloud/ccld6190.dat', 'r') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 xmin = 0.25 xmax = 360.25 ymin = -89.75 ymax = 90.25 lonrange = numpy.arange(xmin, xmax, grid_size) latrange = numpy.arange(ymin, ymax, grid_size) Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0]))) print(len(lonrange)) print(len(latrange)) i = 0 rown = 0 for line in lines: line_n += 1 if line_n < 3: # skip header continue if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month rown += 1 continue value = '' counter = 1 j = 0 for char in line: value += char if counter % digits == 0: value = float(value) if value < 0: value = numpy.nan Z[i][j] = value value = '' j += 1 counter += 1 i += 1 rown += 1 return latrange, lonrange, Z
... nrows = 360 digits = 5 monthnr = 3 with open('./data/cloud/ccld6190.dat', 'r') as filein: lines = filein.readlines() line_n = 0 grid_size = 0.50 ... print(len(latrange)) i = 0 rown = 0 for line in lines: line_n += 1 if line_n < 3: # skip header continue if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month rown += 1 continue value = '' counter = 1 j = 0 for char in line: value += char if counter % digits == 0: value = float(value) if value < 0: value = numpy.nan Z[i][j] = value value = '' j += 1 counter += 1 i += 1 rown += 1 return latrange, lonrange, Z ...
b49249fa3b927cf89409222a3935722ec4c6fe14
src/test/java/net/sf/jabref/model/entry/CanonicalBibEntryTest.java
src/test/java/net/sf/jabref/model/entry/CanonicalBibEntryTest.java
package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { /** * Simple test for the canonical format */ @Test public void canonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } }
package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { @Test public void simpleCanonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } @Test public void canonicalRepresentationWithNewlines() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("abstract", "line 1\nline 2"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n abstract = {line 1\nline 2}\n}", canonicalRepresentation); } }
Add multiline test for canonical representation
Add multiline test for canonical representation
Java
mit
Braunch/jabref,Braunch/jabref,tschechlovdev/jabref,obraliar/jabref,mredaelli/jabref,tobiasdiez/jabref,JabRef/jabref,mairdl/jabref,grimes2/jabref,Mr-DLib/jabref,Mr-DLib/jabref,shitikanth/jabref,shitikanth/jabref,tobiasdiez/jabref,mairdl/jabref,ayanai1/jabref,obraliar/jabref,mredaelli/jabref,Braunch/jabref,jhshinn/jabref,grimes2/jabref,oscargus/jabref,motokito/jabref,jhshinn/jabref,JabRef/jabref,bartsch-dev/jabref,jhshinn/jabref,shitikanth/jabref,zellerdev/jabref,tschechlovdev/jabref,shitikanth/jabref,shitikanth/jabref,mairdl/jabref,tobiasdiez/jabref,tschechlovdev/jabref,jhshinn/jabref,Mr-DLib/jabref,jhshinn/jabref,motokito/jabref,JabRef/jabref,grimes2/jabref,obraliar/jabref,mredaelli/jabref,oscargus/jabref,motokito/jabref,tschechlovdev/jabref,ayanai1/jabref,oscargus/jabref,grimes2/jabref,grimes2/jabref,Siedlerchr/jabref,bartsch-dev/jabref,sauliusg/jabref,Mr-DLib/jabref,bartsch-dev/jabref,sauliusg/jabref,sauliusg/jabref,oscargus/jabref,zellerdev/jabref,tschechlovdev/jabref,ayanai1/jabref,motokito/jabref,zellerdev/jabref,bartsch-dev/jabref,Mr-DLib/jabref,ayanai1/jabref,Braunch/jabref,Siedlerchr/jabref,JabRef/jabref,mredaelli/jabref,sauliusg/jabref,motokito/jabref,ayanai1/jabref,mairdl/jabref,zellerdev/jabref,zellerdev/jabref,oscargus/jabref,tobiasdiez/jabref,Braunch/jabref,mredaelli/jabref,obraliar/jabref,Siedlerchr/jabref,bartsch-dev/jabref,Siedlerchr/jabref,obraliar/jabref,mairdl/jabref
java
## Code Before: package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { /** * Simple test for the canonical format */ @Test public void canonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } } ## Instruction: Add multiline test for canonical representation ## Code After: package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { @Test public void simpleCanonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } @Test public void canonicalRepresentationWithNewlines() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("abstract", "line 1\nline 2"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n abstract = {line 1\nline 2}\n}", canonicalRepresentation); } }
... public class CanonicalBibEntryTest { @Test public void simpleCanonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); ... canonicalRepresentation); } @Test public void canonicalRepresentationWithNewlines() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("abstract", "line 1\nline 2"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n abstract = {line 1\nline 2}\n}", canonicalRepresentation); } } ...
d8da4526375946551fd3963b42f2bb13035abb2d
hijack_admin/tests/test_hijack_admin.py
hijack_admin/tests/test_hijack_admin.py
from hijack.tests.test_hijack import BaseHijackTests from hijack.tests.utils import SettingsOverride from hijack_admin import settings as hijack_admin_settings from hijack_admin.tests.test_app.models import RelatedModel class HijackAdminTests(BaseHijackTests): def setUp(self): super(HijackAdminTests, self).setUp() def tearDown(self): super(HijackAdminTests, self).tearDown() def test_hijack_button(self): response = self.client.get('/admin/auth/user/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_hijack_button_related(self): RelatedModel.objects.create(user=self.user) response = self.client.get('/admin/test_app/relatedmodel/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_settings(self): self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_BUTTON_TEMPLATE')) self.assertEqual(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE, 'hijack_admin/admin_button.html') self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_REGISTER_ADMIN')) self.assertEqual(hijack_admin_settings.HIJACK_REGISTER_ADMIN, True)
from hijack.tests.test_hijack import BaseHijackTests from hijack_admin import settings as hijack_admin_settings from hijack_admin.tests.test_app.models import RelatedModel class HijackAdminTests(BaseHijackTests): def setUp(self): super(HijackAdminTests, self).setUp() def tearDown(self): super(HijackAdminTests, self).tearDown() def test_hijack_button(self): response = self.client.get('/admin/auth/user/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_hijack_button_related(self): RelatedModel.objects.create(user=self.user) response = self.client.get('/admin/test_app/relatedmodel/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_settings(self): self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_BUTTON_TEMPLATE')) self.assertEqual(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE, 'hijack_admin/admin_button.html') self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_REGISTER_ADMIN')) self.assertEqual(hijack_admin_settings.HIJACK_REGISTER_ADMIN, True)
Remove unused import in tests
Remove unused import in tests
Python
mit
arteria/django-hijack-admin,arteria/django-hijack-admin,arteria/django-hijack-admin
python
## Code Before: from hijack.tests.test_hijack import BaseHijackTests from hijack.tests.utils import SettingsOverride from hijack_admin import settings as hijack_admin_settings from hijack_admin.tests.test_app.models import RelatedModel class HijackAdminTests(BaseHijackTests): def setUp(self): super(HijackAdminTests, self).setUp() def tearDown(self): super(HijackAdminTests, self).tearDown() def test_hijack_button(self): response = self.client.get('/admin/auth/user/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_hijack_button_related(self): RelatedModel.objects.create(user=self.user) response = self.client.get('/admin/test_app/relatedmodel/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_settings(self): self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_BUTTON_TEMPLATE')) self.assertEqual(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE, 'hijack_admin/admin_button.html') self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_REGISTER_ADMIN')) self.assertEqual(hijack_admin_settings.HIJACK_REGISTER_ADMIN, True) ## Instruction: Remove unused import in tests ## Code After: from hijack.tests.test_hijack import BaseHijackTests from hijack_admin import settings as hijack_admin_settings from hijack_admin.tests.test_app.models import RelatedModel class HijackAdminTests(BaseHijackTests): def setUp(self): super(HijackAdminTests, self).setUp() def tearDown(self): super(HijackAdminTests, self).tearDown() def test_hijack_button(self): response = self.client.get('/admin/auth/user/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_hijack_button_related(self): RelatedModel.objects.create(user=self.user) response = self.client.get('/admin/test_app/relatedmodel/') self.assertTrue('<a href="/hijack/{}/" class="button">'.format(self.user.id) in str(response.content)) def test_settings(self): self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_BUTTON_TEMPLATE')) self.assertEqual(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE, 'hijack_admin/admin_button.html') self.assertTrue(hasattr(hijack_admin_settings, 'HIJACK_REGISTER_ADMIN')) self.assertEqual(hijack_admin_settings.HIJACK_REGISTER_ADMIN, True)
... from hijack.tests.test_hijack import BaseHijackTests from hijack_admin import settings as hijack_admin_settings from hijack_admin.tests.test_app.models import RelatedModel ...
0e1a86e027b7c58adc7fa9082093a2e42113c2f3
WordPressCom-Stats-iOS/StatsGroup.h
WordPressCom-Stats-iOS/StatsGroup.h
@interface StatsGroup : NSObject @property (nonatomic, strong) NSArray *items; // StatsItem @property (nonatomic, assign) BOOL moreItemsExist; @property (nonatomic, copy) NSString *titlePrimary; @property (nonatomic, copy) NSString *titleSecondary; @property (nonatomic, strong) NSURL *iconUrl; @end
@interface StatsGroup : NSObject @property (nonatomic, strong) NSArray *items; // StatsItem @property (nonatomic, copy) NSString *titlePrimary; @property (nonatomic, copy) NSString *titleSecondary; @property (nonatomic, strong) NSURL *iconUrl; @end
Revert "Added moreItems boolean to data model for a group"
Revert "Added moreItems boolean to data model for a group" This reverts commit ddbdfa290670584080d841244b53d6d3ede11de3.
C
mit
wordpress-mobile/WordPressCom-Stats-iOS,wordpress-mobile/WordPressCom-Stats-iOS
c
## Code Before: @interface StatsGroup : NSObject @property (nonatomic, strong) NSArray *items; // StatsItem @property (nonatomic, assign) BOOL moreItemsExist; @property (nonatomic, copy) NSString *titlePrimary; @property (nonatomic, copy) NSString *titleSecondary; @property (nonatomic, strong) NSURL *iconUrl; @end ## Instruction: Revert "Added moreItems boolean to data model for a group" This reverts commit ddbdfa290670584080d841244b53d6d3ede11de3. ## Code After: @interface StatsGroup : NSObject @property (nonatomic, strong) NSArray *items; // StatsItem @property (nonatomic, copy) NSString *titlePrimary; @property (nonatomic, copy) NSString *titleSecondary; @property (nonatomic, strong) NSURL *iconUrl; @end
// ... existing code ... @interface StatsGroup : NSObject @property (nonatomic, strong) NSArray *items; // StatsItem @property (nonatomic, copy) NSString *titlePrimary; @property (nonatomic, copy) NSString *titleSecondary; @property (nonatomic, strong) NSURL *iconUrl; // ... rest of the code ...
679c2daceb7f4e9d193e345ee42b0334dd576c64
changes/web/index.py
changes/web/index.py
import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN']: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), })
import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN'] and False: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), })
Disable Sentry due to sync behavior
Disable Sentry due to sync behavior
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes
python
## Code Before: import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN']: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), }) ## Instruction: Disable Sentry due to sync behavior ## Code After: import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN'] and False: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), })
... if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN'] and False: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, ...
2664e9124af6b0d8f6b2eacd50f4d7e93b91e931
examples/GoBot/gobot.py
examples/GoBot/gobot.py
from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo import math import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
Fix linting errors in GoBot
Fix linting errors in GoBot
Python
apache-2.0
cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot
python
## Code Before: from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo import math import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run() ## Instruction: Fix linting errors in GoBot ## Code After: from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
// ... existing code ... from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") // ... rest of the code ...
afb4e0d036fd93ba5e2c02e5d935452ab1a22e4e
emission/core/wrapper/cleanedtrip.py
emission/core/wrapper/cleanedtrip.py
import emission.core.wrapper.trip as ecwt import emission.core.wrapper.wrapperbase as ecwb class Cleanedtrip(ecwt.Trip): props = ecwt.Trip.props props.update({"raw_trip": ecwb.WrapperBase.Access.WORM, "distance": ecwb.WrapperBase.Access.WORM, }) def _populateDependencies(self): super(Cleanedtrip, self)._populateDependencies()
import emission.core.wrapper.trip as ecwt import emission.core.wrapper.wrapperbase as ecwb class Cleanedtrip(ecwt.Trip): props = ecwt.Trip.props props.update({"raw_trip": ecwb.WrapperBase.Access.WORM }) def _populateDependencies(self): super(Cleanedtrip, self)._populateDependencies()
Remove the distance from the cleaned trip
Remove the distance from the cleaned trip Since it is already in the base class (trip) and has been there since the very first wrapper class commit. https://github.com/e-mission/e-mission-server/commit/c4251f5de5dc65f0ddd458dc909c111ddec67153
Python
bsd-3-clause
shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server
python
## Code Before: import emission.core.wrapper.trip as ecwt import emission.core.wrapper.wrapperbase as ecwb class Cleanedtrip(ecwt.Trip): props = ecwt.Trip.props props.update({"raw_trip": ecwb.WrapperBase.Access.WORM, "distance": ecwb.WrapperBase.Access.WORM, }) def _populateDependencies(self): super(Cleanedtrip, self)._populateDependencies() ## Instruction: Remove the distance from the cleaned trip Since it is already in the base class (trip) and has been there since the very first wrapper class commit. https://github.com/e-mission/e-mission-server/commit/c4251f5de5dc65f0ddd458dc909c111ddec67153 ## Code After: import emission.core.wrapper.trip as ecwt import emission.core.wrapper.wrapperbase as ecwb class Cleanedtrip(ecwt.Trip): props = ecwt.Trip.props props.update({"raw_trip": ecwb.WrapperBase.Access.WORM }) def _populateDependencies(self): super(Cleanedtrip, self)._populateDependencies()
... class Cleanedtrip(ecwt.Trip): props = ecwt.Trip.props props.update({"raw_trip": ecwb.WrapperBase.Access.WORM }) def _populateDependencies(self): ...
476a2314be0dafa3975b1f29a69ce4917a1a7425
src/main/java/de/pitkley/jenkins/plugins/dockerswarmslave/DockerSwarmSlaveRunListener.java
src/main/java/de/pitkley/jenkins/plugins/dockerswarmslave/DockerSwarmSlaveRunListener.java
package de.pitkley.jenkins.plugins.dockerswarmslave; import hudson.Extension; import hudson.model.Build; import hudson.model.Project; import hudson.model.Run; import hudson.model.listeners.RunListener; @Extension public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> { @Override public void onFinalized(Run<?, ?> run) { // Check that we have a build if (!Build.class.isAssignableFrom(run.getClass())) { return; } Build<?, ?> b = (Build) run; // Check that it is a project if (!Project.class.isAssignableFrom(b.getProject().getClass())) { return; } Project<?, ?> project = b.getProject(); // Was our build-wrapper active? DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper(project); if (buildWrapper == null) { return; } // Do we have a matching DockerSwarmSlave? DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project); if (dockerSwarmSlave == null) { return; } // Clean everything up dockerSwarmSlave.cleanup(); } }
package de.pitkley.jenkins.plugins.dockerswarmslave; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildableItemWithBuildWrappers; import hudson.model.Run; import hudson.model.listeners.RunListener; @Extension public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> { @Override public void onFinalized(Run<?, ?> run) { // Check that we have a build if (!AbstractBuild.class.isAssignableFrom(run.getClass())) { return; } AbstractBuild<?, ?> b = (AbstractBuild) run; // Check that it is a project if (!AbstractProject.class.isAssignableFrom(b.getProject().getClass())) { return; } AbstractProject<?, ?> project = b.getProject(); if (!BuildableItemWithBuildWrappers.class.isAssignableFrom(project.getClass())) { return; } // Was our build-wrapper active? DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper((BuildableItemWithBuildWrappers) project); if (buildWrapper == null) { return; } // Do we have a matching DockerSwarmSlave? DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project); if (dockerSwarmSlave == null) { return; } // Clean everything up dockerSwarmSlave.cleanup(); } }
Use abstract classes in the runlistener
Use abstract classes in the runlistener
Java
mit
pitkley/docker-swarm-slave
java
## Code Before: package de.pitkley.jenkins.plugins.dockerswarmslave; import hudson.Extension; import hudson.model.Build; import hudson.model.Project; import hudson.model.Run; import hudson.model.listeners.RunListener; @Extension public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> { @Override public void onFinalized(Run<?, ?> run) { // Check that we have a build if (!Build.class.isAssignableFrom(run.getClass())) { return; } Build<?, ?> b = (Build) run; // Check that it is a project if (!Project.class.isAssignableFrom(b.getProject().getClass())) { return; } Project<?, ?> project = b.getProject(); // Was our build-wrapper active? DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper(project); if (buildWrapper == null) { return; } // Do we have a matching DockerSwarmSlave? DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project); if (dockerSwarmSlave == null) { return; } // Clean everything up dockerSwarmSlave.cleanup(); } } ## Instruction: Use abstract classes in the runlistener ## Code After: package de.pitkley.jenkins.plugins.dockerswarmslave; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildableItemWithBuildWrappers; import hudson.model.Run; import hudson.model.listeners.RunListener; @Extension public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> { @Override public void onFinalized(Run<?, ?> run) { // Check that we have a build if (!AbstractBuild.class.isAssignableFrom(run.getClass())) { return; } AbstractBuild<?, ?> b = (AbstractBuild) run; // Check that it is a project if (!AbstractProject.class.isAssignableFrom(b.getProject().getClass())) { return; } AbstractProject<?, ?> project = b.getProject(); if (!BuildableItemWithBuildWrappers.class.isAssignableFrom(project.getClass())) { return; } // Was our build-wrapper active? DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper((BuildableItemWithBuildWrappers) project); if (buildWrapper == null) { return; } // Do we have a matching DockerSwarmSlave? DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project); if (dockerSwarmSlave == null) { return; } // Clean everything up dockerSwarmSlave.cleanup(); } }
// ... existing code ... package de.pitkley.jenkins.plugins.dockerswarmslave; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildableItemWithBuildWrappers; import hudson.model.Run; import hudson.model.listeners.RunListener; // ... modified code ... @Override public void onFinalized(Run<?, ?> run) { // Check that we have a build if (!AbstractBuild.class.isAssignableFrom(run.getClass())) { return; } AbstractBuild<?, ?> b = (AbstractBuild) run; // Check that it is a project if (!AbstractProject.class.isAssignableFrom(b.getProject().getClass())) { return; } AbstractProject<?, ?> project = b.getProject(); if (!BuildableItemWithBuildWrappers.class.isAssignableFrom(project.getClass())) { return; } // Was our build-wrapper active? DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper((BuildableItemWithBuildWrappers) project); if (buildWrapper == null) { return; } // ... rest of the code ...
44893be528063d25d0b2305c9d24be4605c49f3c
mcserver/config/core.py
mcserver/config/core.py
import json import os.path class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings
import json import os.path from mcserver import MCServerError class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ try: with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) except: raise MCServerError('Could not open settings file: {}'.format(self.settings_file)) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings
Check for the existance of the settings file and report if its not there
Check for the existance of the settings file and report if its not there
Python
mit
cadyyan/mcserver-tools,cadyyan/mcserver-tools
python
## Code Before: import json import os.path class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings ## Instruction: Check for the existance of the settings file and report if its not there ## Code After: import json import os.path from mcserver import MCServerError class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ try: with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) except: raise MCServerError('Could not open settings file: {}'.format(self.settings_file)) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings
# ... existing code ... import json import os.path from mcserver import MCServerError class CoreConfig(object): """ # ... modified code ... Load the settings from disk """ try: with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) except: raise MCServerError('Could not open settings file: {}'.format(self.settings_file)) def get(self, property, default = None): """ # ... rest of the code ...
936bdadb9e949d29a7742b088e0279680afa6c4a
copy_from_find_in_files_command.py
copy_from_find_in_files_command.py
import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = r'^\s*\d+(\:\s|\s{2})' without_dots = r'^\s*(\d+(\:\s|\s{2})|.+\n)' def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return re.sub(self.construct(), '', text, flags=re.MULTILINE) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots
import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = re.compile('^\s*\d+(\:\s|\s{2})', re.MULTILINE) without_dots = re.compile('^\s*(\d+(\:\s|\s{2})|.+\n)', re.MULTILINE) def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return self.construct().sub('', text) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots
Make the regex work on Python2.x
Make the regex work on Python2.x
Python
mit
kema221/sublime-copy-from-find-results,NicoSantangelo/sublime-copy-from-find-results,kema221/sublime-copy-from-find-results
python
## Code Before: import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = r'^\s*\d+(\:\s|\s{2})' without_dots = r'^\s*(\d+(\:\s|\s{2})|.+\n)' def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return re.sub(self.construct(), '', text, flags=re.MULTILINE) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots ## Instruction: Make the regex work on Python2.x ## Code After: import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = re.compile('^\s*\d+(\:\s|\s{2})', re.MULTILINE) without_dots = re.compile('^\s*(\d+(\:\s|\s{2})|.+\n)', re.MULTILINE) def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return self.construct().sub('', text) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots
# ... existing code ... class RegexStruct(): default = re.compile('^\s*\d+(\:\s|\s{2})', re.MULTILINE) without_dots = re.compile('^\s*(\d+(\:\s|\s{2})|.+\n)', re.MULTILINE) def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return self.construct().sub('', text) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots # ... rest of the code ...
3d1939e899fdbb7d71998f33221e687b61c291af
include/HubFramework/HUBHeaderMacros.h
include/HubFramework/HUBHeaderMacros.h
/// Macro that marks an initializer as designated, and also makes the default Foundation initializers unavailable #define HUB_DESIGNATED_INITIALIZER NS_DESIGNATED_INITIALIZER; \ /** Unavailable. Use the designated initializer instead */ \ + (instancetype)new NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (instancetype)init NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE;
/// Macro that marks an initializer as designated, and also makes the default Foundation initializers unavailable #define HUB_DESIGNATED_INITIALIZER NS_DESIGNATED_INITIALIZER; \ /** Unavailable. Use the designated initializer instead */ \ + (instancetype)new NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (instancetype)init NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; /// This macro was introduced in Xcode 8, so adding this here for now (if not defined) to support Xcode 7 as well #ifndef NS_EXTENSIBLE_STRING_ENUM #define NS_EXTENSIBLE_STRING_ENUM #endif
Define NS_EXTENSIBLE_STRING_ENUM if not defined
Define NS_EXTENSIBLE_STRING_ENUM if not defined This enables us to support building with Xcode 7.
C
apache-2.0
spotify/HubFramework,spotify/HubFramework,spotify/HubFramework,spotify/HubFramework
c
## Code Before: /// Macro that marks an initializer as designated, and also makes the default Foundation initializers unavailable #define HUB_DESIGNATED_INITIALIZER NS_DESIGNATED_INITIALIZER; \ /** Unavailable. Use the designated initializer instead */ \ + (instancetype)new NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (instancetype)init NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; ## Instruction: Define NS_EXTENSIBLE_STRING_ENUM if not defined This enables us to support building with Xcode 7. ## Code After: /// Macro that marks an initializer as designated, and also makes the default Foundation initializers unavailable #define HUB_DESIGNATED_INITIALIZER NS_DESIGNATED_INITIALIZER; \ /** Unavailable. Use the designated initializer instead */ \ + (instancetype)new NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (instancetype)init NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; /// This macro was introduced in Xcode 8, so adding this here for now (if not defined) to support Xcode 7 as well #ifndef NS_EXTENSIBLE_STRING_ENUM #define NS_EXTENSIBLE_STRING_ENUM #endif
# ... existing code ... - (instancetype)init NS_UNAVAILABLE; \ /** Unavailable. Use the designated initializer instead */ \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; /// This macro was introduced in Xcode 8, so adding this here for now (if not defined) to support Xcode 7 as well #ifndef NS_EXTENSIBLE_STRING_ENUM #define NS_EXTENSIBLE_STRING_ENUM #endif # ... rest of the code ...
2f80f786be8e0d235dcb98c4fa562bfe2b9e783f
jobs/spiders/visir.py
jobs/spiders/visir.py
import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0]).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item
import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0], dayfirst=False).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item
Fix parsing of dates for Visir.
Fix parsing of dates for Visir. Some dates are being wrongly parsed, so we need to specify some information about the order of things.
Python
apache-2.0
multiplechoice/workplace
python
## Code Before: import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0]).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item ## Instruction: Fix parsing of dates for Visir. Some dates are being wrongly parsed, so we need to specify some information about the order of things. ## Code After: import dateutil.parser import scrapy from jobs.items import JobsItem class VisirSpider(scrapy.Spider): name = "visir" start_urls = ['https://job.visir.is/search-results-jobs/'] def parse(self, response): for job in response.css('.thebox'): info = job.css('a')[1] item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0], dayfirst=False).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item yield request next_page = response.urljoin(response.css('.nextBtn a::attr(href)').extract_first()) if next_page != response.url: yield scrapy.Request(next_page, callback=self.parse) def parse_specific_job(self, response): item = response.meta['item'] item['company'] = response.css('.company-name::text').extract_first() item['title'] = response.css('h2::text').extract_first() yield item
// ... existing code ... item = JobsItem() item['spider'] = self.name item['url'] = url = info.css('a::attr(href)').extract_first() item['posted'] = dateutil.parser.parse(job.css('td::text').re(r'[\d.]+')[0], dayfirst=False).isoformat() request = scrapy.Request(url, callback=self.parse_specific_job) request.meta['item'] = item // ... rest of the code ...
2d102e049ceb4ac6d9892313e78b82fc91f9e84c
tests/test_filters.py
tests/test_filters.py
from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] np.testing.assert_almost_equal(rri_filt, expected, decimal=2)
from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] np.testing.assert_almost_equal(rri_filt, expected, decimal=2) def test_moving_average_order_5(self): fake_rri = np.array([810, 830, 860, 790, 804, 801, 800]) rri_filt = moving_average(fake_rri, order=5) expected = [810, 830, 818.79, 817.0, 811.0, 801, 800] np.testing.assert_almost_equal(rri_filt, expected, decimal=2)
Test moving average filter for 5th order
Test moving average filter for 5th order
Python
bsd-3-clause
rhenanbartels/hrv
python
## Code Before: from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] np.testing.assert_almost_equal(rri_filt, expected, decimal=2) ## Instruction: Test moving average filter for 5th order ## Code After: from unittest import TestCase import numpy as np from hrv.filters import moving_average class Filter(TestCase): def test_moving_average_order_3(self): fake_rri = np.array([810, 830, 860, 790, 804]) rri_filt = moving_average(fake_rri, order=3) expected = [810, 833.33, 826.66, 818, 804] np.testing.assert_almost_equal(rri_filt, expected, decimal=2) def test_moving_average_order_5(self): fake_rri = np.array([810, 830, 860, 790, 804, 801, 800]) rri_filt = moving_average(fake_rri, order=5) expected = [810, 830, 818.79, 817.0, 811.0, 801, 800] np.testing.assert_almost_equal(rri_filt, expected, decimal=2)
# ... existing code ... expected = [810, 833.33, 826.66, 818, 804] np.testing.assert_almost_equal(rri_filt, expected, decimal=2) def test_moving_average_order_5(self): fake_rri = np.array([810, 830, 860, 790, 804, 801, 800]) rri_filt = moving_average(fake_rri, order=5) expected = [810, 830, 818.79, 817.0, 811.0, 801, 800] np.testing.assert_almost_equal(rri_filt, expected, decimal=2) # ... rest of the code ...
1f1e6815be0965cd896968baf3b088bb660da98d
src/main/java/jenkins/advancedqueue/PriorityConfigurationPlaceholderTaskHelper.java
src/main/java/jenkins/advancedqueue/PriorityConfigurationPlaceholderTaskHelper.java
package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { private static boolean placeholderTaskUsed = Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; boolean isPlaceholderTask(Queue.Task task) { return placeholderTaskUsed && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return placeholderTaskUsed; } }
package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; } }
Fix inability dynamically install Pipeline
Fix inability dynamically install Pipeline
Java
mit
jenkinsci/priority-sorter-plugin,jenkinsci/priority-sorter-plugin,jenkinsci/priority-sorter-plugin
java
## Code Before: package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { private static boolean placeholderTaskUsed = Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; boolean isPlaceholderTask(Queue.Task task) { return placeholderTaskUsed && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return placeholderTaskUsed; } } ## Instruction: Fix inability dynamically install Pipeline ## Code After: package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; } }
# ... existing code ... class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { # ... modified code ... } static boolean isPlaceholderTaskUsed() { return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; } } # ... rest of the code ...
5d7e0a0e397339b7a587f3963eb9440c27d26715
src/main/kotlin/org/purescript/ide/formatting/PSBlock.kt
src/main/kotlin/org/purescript/ide/formatting/PSBlock.kt
package org.purescript.ide.formatting import com.intellij.formatting.* import com.intellij.formatting.Spacing.getReadOnlySpacing import com.intellij.lang.ASTNode import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.formatter.common.AbstractBlock class PSBlock( node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder ) : AbstractBlock(node, wrap, alignment) { override fun buildChildren(): MutableList<Block> { val blocks = arrayListOf<Block>() var child = myNode.firstChildNode while (child != null) { if (child.elementType !== WHITE_SPACE && child.textLength != 0) { val block: Block = PSBlock( child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), spacingBuilder ) blocks.add(block) } child = child.treeNext } return blocks } override fun isLeaf(): Boolean { return myNode.firstChildNode == null } override fun getSpacing(child1: Block?, child2: Block): Spacing? { return getReadOnlySpacing(); //return spacingBuilder.getSpacing(this, child1, child2); } }
package org.purescript.ide.formatting import com.intellij.formatting.* import com.intellij.formatting.Spacing.getReadOnlySpacing import com.intellij.lang.ASTNode import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.formatter.common.AbstractBlock class PSBlock( node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder ) : AbstractBlock(node, wrap, alignment) { override fun buildChildren(): MutableList<Block> { val blocks = arrayListOf<Block>() var child = myNode.firstChildNode while (child != null) { if (child.elementType !== WHITE_SPACE && child.textLength != 0) { val block: Block = PSBlock( child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), spacingBuilder ) blocks.add(block) } child = child.treeNext } return blocks } override fun isLeaf(): Boolean { return myNode.firstChildNode == null } override fun getIndent(): Indent? { return Indent.getNoneIndent() } override fun getSpacing(child1: Block?, child2: Block): Spacing? { return spacingBuilder.getSpacing(this, child1, child2); } }
Use spacing builder and don't have any indentation
Use spacing builder and don't have any indentation
Kotlin
bsd-3-clause
intellij-purescript/intellij-purescript,intellij-purescript/intellij-purescript
kotlin
## Code Before: package org.purescript.ide.formatting import com.intellij.formatting.* import com.intellij.formatting.Spacing.getReadOnlySpacing import com.intellij.lang.ASTNode import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.formatter.common.AbstractBlock class PSBlock( node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder ) : AbstractBlock(node, wrap, alignment) { override fun buildChildren(): MutableList<Block> { val blocks = arrayListOf<Block>() var child = myNode.firstChildNode while (child != null) { if (child.elementType !== WHITE_SPACE && child.textLength != 0) { val block: Block = PSBlock( child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), spacingBuilder ) blocks.add(block) } child = child.treeNext } return blocks } override fun isLeaf(): Boolean { return myNode.firstChildNode == null } override fun getSpacing(child1: Block?, child2: Block): Spacing? { return getReadOnlySpacing(); //return spacingBuilder.getSpacing(this, child1, child2); } } ## Instruction: Use spacing builder and don't have any indentation ## Code After: package org.purescript.ide.formatting import com.intellij.formatting.* import com.intellij.formatting.Spacing.getReadOnlySpacing import com.intellij.lang.ASTNode import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.formatter.common.AbstractBlock class PSBlock( node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder ) : AbstractBlock(node, wrap, alignment) { override fun buildChildren(): MutableList<Block> { val blocks = arrayListOf<Block>() var child = myNode.firstChildNode while (child != null) { if (child.elementType !== WHITE_SPACE && child.textLength != 0) { val block: Block = PSBlock( child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), spacingBuilder ) blocks.add(block) } child = child.treeNext } return blocks } override fun isLeaf(): Boolean { return myNode.firstChildNode == null } override fun getIndent(): Indent? { return Indent.getNoneIndent() } override fun getSpacing(child1: Block?, child2: Block): Spacing? { return spacingBuilder.getSpacing(this, child1, child2); } }
... return myNode.firstChildNode == null } override fun getIndent(): Indent? { return Indent.getNoneIndent() } override fun getSpacing(child1: Block?, child2: Block): Spacing? { return spacingBuilder.getSpacing(this, child1, child2); } } ...
3ec1e14127601c58a338bfb419a64d942da59a02
src/main/java/uk/ac/ic/wlgitbridge/writelatex/model/db/sql/update/create/CreateIndexURLIndexStore.java
src/main/java/uk/ac/ic/wlgitbridge/writelatex/model/db/sql/update/create/CreateIndexURLIndexStore.java
package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create; import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Winston on 21/02/15. */ public class CreateIndexURLIndexStore implements SQLUpdate { public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX `project_path_index` ON `url_index_store`(`project_name`, `path`);\n"; @Override public String getSQL() { return CREATE_INDEX_URL_INDEX_STORE; } @Override public void addParametersToStatement(PreparedStatement statement) throws SQLException { } }
package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create; import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Winston on 21/02/15. */ public class CreateIndexURLIndexStore implements SQLUpdate { public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX IF NOT EXISTS `project_path_index` ON `url_index_store`(`project_name`, `path`);\n"; @Override public String getSQL() { return CREATE_INDEX_URL_INDEX_STORE; } @Override public void addParametersToStatement(PreparedStatement statement) throws SQLException { } }
Add IF NOT EXISTS to index creation sql statement.
Add IF NOT EXISTS to index creation sql statement.
Java
mit
overleaf/writelatex-git-bridge,winstonli/writelatex-git-bridge,overleaf/writelatex-git-bridge,winstonli/writelatex-git-bridge
java
## Code Before: package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create; import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Winston on 21/02/15. */ public class CreateIndexURLIndexStore implements SQLUpdate { public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX `project_path_index` ON `url_index_store`(`project_name`, `path`);\n"; @Override public String getSQL() { return CREATE_INDEX_URL_INDEX_STORE; } @Override public void addParametersToStatement(PreparedStatement statement) throws SQLException { } } ## Instruction: Add IF NOT EXISTS to index creation sql statement. ## Code After: package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create; import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Winston on 21/02/15. */ public class CreateIndexURLIndexStore implements SQLUpdate { public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX IF NOT EXISTS `project_path_index` ON `url_index_store`(`project_name`, `path`);\n"; @Override public String getSQL() { return CREATE_INDEX_URL_INDEX_STORE; } @Override public void addParametersToStatement(PreparedStatement statement) throws SQLException { } }
# ... existing code ... */ public class CreateIndexURLIndexStore implements SQLUpdate { public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX IF NOT EXISTS `project_path_index` ON `url_index_store`(`project_name`, `path`);\n"; @Override public String getSQL() { # ... rest of the code ...
274e695cb0bf8eace0af0bf673f294ffef3dd5f4
src/main/java/org/rmatil/sync/persistence/core/dht/DhtPathElement.java
src/main/java/org/rmatil/sync/persistence/core/dht/DhtPathElement.java
package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.PublicKey; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used for to access and/or modify the path in the DHT */ public DhtPathElement(String contentKey, PublicKey domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access and/or modify the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } }
package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.Key; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used to access the path in the DHT */ public DhtPathElement(String contentKey, Key domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } }
Use a generic key instead of PublicKey
Use a generic key instead of PublicKey
Java
apache-2.0
p2p-sync/persistence
java
## Code Before: package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.PublicKey; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used for to access and/or modify the path in the DHT */ public DhtPathElement(String contentKey, PublicKey domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access and/or modify the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } } ## Instruction: Use a generic key instead of PublicKey ## Code After: package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.Key; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used to access the path in the DHT */ public DhtPathElement(String contentKey, Key domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } }
... import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.Key; /** * A path element representing data in the DHT ... /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used to access the path in the DHT */ public DhtPathElement(String contentKey, Key domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } ... /** * Returns the domain protection key which is used * to access the content in the DHT * * @return The domain protection key */ ...
b33408e590dc9fa5ae47d728893a5a007406207f
setup.py
setup.py
import sys from setuptools import setup if sys.argv[-1] == 'setup.py': print('To install, run \'python setup.py install\'') print() sys.path.insert(0, 'potterscript') import release if __name__ == "__main__": setup( name = release.name, version = release.__version__, author = release.__author__, author_email = release.__email__, description = release.__description__, url='https://github.com/OrkoHunter/PotterScript', keywords='Harry Potter Programming Language Potter Script', packages = ['potterscript'], license = 'MIT License', entry_points = { 'console_scripts': [ 'potterscript = potterscript.pottershell:main', ] }, install_requires = [], test_suite = 'nose.collector', tests_require = ['nose>=0.10.1'] )
import sys from setuptools import setup if sys.argv[-1] == 'setup.py': print('To install, run \'python setup.py install\'') print() if sys.version[0] < '3': print("Please install with Python 3. Aborting installation.") sys.exit(0) sys.path.insert(0, 'potterscript') import release if __name__ == "__main__": setup( name = release.name, version = release.__version__, author = release.__author__, author_email = release.__email__, description = release.__description__, url='https://github.com/OrkoHunter/PotterScript', keywords='Harry Potter Programming Language Potter Script', packages = ['potterscript'], license = 'MIT License', entry_points = { 'console_scripts': [ 'potterscript = potterscript.pottershell:main', ] }, install_requires = [], test_suite = 'nose.collector', tests_require = ['nose>=0.10.1'] )
Install only with python 3
Install only with python 3
Python
mit
OrkoHunter/PotterScript
python
## Code Before: import sys from setuptools import setup if sys.argv[-1] == 'setup.py': print('To install, run \'python setup.py install\'') print() sys.path.insert(0, 'potterscript') import release if __name__ == "__main__": setup( name = release.name, version = release.__version__, author = release.__author__, author_email = release.__email__, description = release.__description__, url='https://github.com/OrkoHunter/PotterScript', keywords='Harry Potter Programming Language Potter Script', packages = ['potterscript'], license = 'MIT License', entry_points = { 'console_scripts': [ 'potterscript = potterscript.pottershell:main', ] }, install_requires = [], test_suite = 'nose.collector', tests_require = ['nose>=0.10.1'] ) ## Instruction: Install only with python 3 ## Code After: import sys from setuptools import setup if sys.argv[-1] == 'setup.py': print('To install, run \'python setup.py install\'') print() if sys.version[0] < '3': print("Please install with Python 3. Aborting installation.") sys.exit(0) sys.path.insert(0, 'potterscript') import release if __name__ == "__main__": setup( name = release.name, version = release.__version__, author = release.__author__, author_email = release.__email__, description = release.__description__, url='https://github.com/OrkoHunter/PotterScript', keywords='Harry Potter Programming Language Potter Script', packages = ['potterscript'], license = 'MIT License', entry_points = { 'console_scripts': [ 'potterscript = potterscript.pottershell:main', ] }, install_requires = [], test_suite = 'nose.collector', tests_require = ['nose>=0.10.1'] )
// ... existing code ... if sys.argv[-1] == 'setup.py': print('To install, run \'python setup.py install\'') print() if sys.version[0] < '3': print("Please install with Python 3. Aborting installation.") sys.exit(0) sys.path.insert(0, 'potterscript') import release // ... rest of the code ...
3af52b4c0ff95af8344cacd16a2cee827d6301cc
source/main.c
source/main.c
int main(void) { return(0); }
struct winsize terminalSize; void initScreen(void) { initscr(); noecho(); nocbreak(); } void closeScreen(void) { endwin(); } void getScreenSize(void) { if (ioctl(0, TIOCGWINSZ, (char *) &terminalSize) < 0) { printf("The program canno't determine terminal size.\r\n\r\n"); exit(1); } } int main(void) { initScreen(); getScreenSize(); move(10,10); printw("Terminal size is %dx%d", terminalSize.ws_col, terminalSize.ws_row); getch(); closeScreen(); return(0); }
Add the initial NCurses support for the program.
Add the initial NCurses support for the program.
C
unlicense
pacmanalx/fastview,pacmanalx/fastview
c
## Code Before: int main(void) { return(0); } ## Instruction: Add the initial NCurses support for the program. ## Code After: struct winsize terminalSize; void initScreen(void) { initscr(); noecho(); nocbreak(); } void closeScreen(void) { endwin(); } void getScreenSize(void) { if (ioctl(0, TIOCGWINSZ, (char *) &terminalSize) < 0) { printf("The program canno't determine terminal size.\r\n\r\n"); exit(1); } } int main(void) { initScreen(); getScreenSize(); move(10,10); printw("Terminal size is %dx%d", terminalSize.ws_col, terminalSize.ws_row); getch(); closeScreen(); return(0); }
... struct winsize terminalSize; void initScreen(void) { initscr(); noecho(); nocbreak(); } void closeScreen(void) { endwin(); } void getScreenSize(void) { if (ioctl(0, TIOCGWINSZ, (char *) &terminalSize) < 0) { printf("The program canno't determine terminal size.\r\n\r\n"); exit(1); } } int main(void) { initScreen(); getScreenSize(); move(10,10); printw("Terminal size is %dx%d", terminalSize.ws_col, terminalSize.ws_row); getch(); closeScreen(); return(0); } ...
36d8243712b5be7f7f7449abcd9640024cee0f19
src/tpn/data_io.py
src/tpn/data_io.py
import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w') print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} track_obj['frames'] = np.asarray([box['frame'] for box in track]) track_obj['anchors'] = np.asarray([box['anchor'] for box in track]) track_obj['scores'] = np.asarray([box['scores'] for box in track]) track_obj['features'] = np.asarray([box['feature'] for box in track]) track_obj['boxes'] = np.asarray([box['bbox'] for box in track]) track_obj['rois'] = np.asarray([box['roi'] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close()
import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w') print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} for key in track[0]: track_obj[key] = np.asarray([box[key] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close()
Simplify save_track_proto_to_zip to save all keys in track_proto.
Simplify save_track_proto_to_zip to save all keys in track_proto.
Python
mit
myfavouritekk/TPN
python
## Code Before: import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w') print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} track_obj['frames'] = np.asarray([box['frame'] for box in track]) track_obj['anchors'] = np.asarray([box['anchor'] for box in track]) track_obj['scores'] = np.asarray([box['scores'] for box in track]) track_obj['features'] = np.asarray([box['feature'] for box in track]) track_obj['boxes'] = np.asarray([box['bbox'] for box in track]) track_obj['rois'] = np.asarray([box['roi'] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close() ## Instruction: Simplify save_track_proto_to_zip to save all keys in track_proto. ## Code After: import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w') print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} for key in track[0]: track_obj[key] = np.asarray([box[key] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close()
// ... existing code ... print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} for key in track[0]: track_obj[key] = np.asarray([box[key] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: // ... rest of the code ...
79278824c6433ef6634532a1b5192961acc248a4
libqimessaging/c/qimessaging/c/object_c.h
libqimessaging/c/qimessaging/c/object_c.h
/* ** ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #ifndef _QIMESSAGING_OBJECT_H_ #define _QIMESSAGING_OBJECT_H_ #include <qimessaging/c/api_c.h> #ifdef __cplusplus extern "C" { #endif typedef struct qi_object_t_s {} qi_object_t; //forward declaration typedef struct qi_message_t_s qi_message_t; typedef struct qi_future_t_s qi_future_t; QIMESSAGING_API typedef void (*qi_object_method_t)(const char *complete_signature, qi_message_t *msg, qi_message_t *ret, void *data); QIMESSAGING_API qi_object_t *qi_object_create(const char *name); QIMESSAGING_API void qi_object_destroy(qi_object_t *object); QIMESSAGING_API int qi_object_register_method(qi_object_t *object, const char *complete_signature, qi_object_method_t func, void *data); QIMESSAGING_API qi_future_t *qi_object_call(qi_object_t *object, const char *signature, qi_message_t *message); #ifdef __cplusplus } #endif #endif
/* ** ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #ifndef _QIMESSAGING_OBJECT_H_ #define _QIMESSAGING_OBJECT_H_ #include <qimessaging/c/api_c.h> #ifdef __cplusplus extern "C" { #endif typedef struct qi_object_t_s {} qi_object_t; //forward declaration typedef struct qi_message_t_s qi_message_t; typedef struct qi_future_t_s qi_future_t; typedef void (*qi_object_method_t)(const char *complete_signature, qi_message_t *msg, qi_message_t *ret, void *data); QIMESSAGING_API qi_object_t *qi_object_create(const char *name); QIMESSAGING_API void qi_object_destroy(qi_object_t *object); QIMESSAGING_API int qi_object_register_method(qi_object_t *object, const char *complete_signature, qi_object_method_t func, void *data); QIMESSAGING_API qi_future_t *qi_object_call(qi_object_t *object, const char *signature, qi_message_t *message); #ifdef __cplusplus } #endif #endif
Remove unnecessary API export on typedef
Remove unnecessary API export on typedef Change-Id: Id9b225ad5a7a645763f4377c7f949e9c9bd4f890 Reviewed-on: http://gerrit.aldebaran.lan:8080/4588 Reviewed-by: llec <[email protected]> Tested-by: llec <[email protected]>
C
bsd-3-clause
bsautron/libqi,aldebaran/libqi,aldebaran/libqi,aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi,aldebaran/libqi-java,vbarbaresi/libqi
c
## Code Before: /* ** ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #ifndef _QIMESSAGING_OBJECT_H_ #define _QIMESSAGING_OBJECT_H_ #include <qimessaging/c/api_c.h> #ifdef __cplusplus extern "C" { #endif typedef struct qi_object_t_s {} qi_object_t; //forward declaration typedef struct qi_message_t_s qi_message_t; typedef struct qi_future_t_s qi_future_t; QIMESSAGING_API typedef void (*qi_object_method_t)(const char *complete_signature, qi_message_t *msg, qi_message_t *ret, void *data); QIMESSAGING_API qi_object_t *qi_object_create(const char *name); QIMESSAGING_API void qi_object_destroy(qi_object_t *object); QIMESSAGING_API int qi_object_register_method(qi_object_t *object, const char *complete_signature, qi_object_method_t func, void *data); QIMESSAGING_API qi_future_t *qi_object_call(qi_object_t *object, const char *signature, qi_message_t *message); #ifdef __cplusplus } #endif #endif ## Instruction: Remove unnecessary API export on typedef Change-Id: Id9b225ad5a7a645763f4377c7f949e9c9bd4f890 Reviewed-on: http://gerrit.aldebaran.lan:8080/4588 Reviewed-by: llec <[email protected]> Tested-by: llec <[email protected]> ## Code After: /* ** ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2012 Aldebaran Robotics */ #ifndef _QIMESSAGING_OBJECT_H_ #define _QIMESSAGING_OBJECT_H_ #include <qimessaging/c/api_c.h> #ifdef __cplusplus extern "C" { #endif typedef struct qi_object_t_s {} qi_object_t; //forward declaration typedef struct qi_message_t_s qi_message_t; typedef struct qi_future_t_s qi_future_t; typedef void (*qi_object_method_t)(const char *complete_signature, qi_message_t *msg, qi_message_t *ret, void *data); QIMESSAGING_API qi_object_t *qi_object_create(const char *name); QIMESSAGING_API void qi_object_destroy(qi_object_t *object); QIMESSAGING_API int qi_object_register_method(qi_object_t *object, const char *complete_signature, qi_object_method_t func, void *data); QIMESSAGING_API qi_future_t *qi_object_call(qi_object_t *object, const char *signature, qi_message_t *message); #ifdef __cplusplus } #endif #endif
// ... existing code ... typedef struct qi_future_t_s qi_future_t; typedef void (*qi_object_method_t)(const char *complete_signature, qi_message_t *msg, qi_message_t *ret, void *data); QIMESSAGING_API qi_object_t *qi_object_create(const char *name); QIMESSAGING_API void qi_object_destroy(qi_object_t *object); // ... rest of the code ...
eaaa6c7c002c96e94ebc14773976e6a805e7da23
src/Robot.java
src/Robot.java
/** * Représente un robot */ public class Robot { private String name; private Point2D pos; private int energy; private int health; /** Crée un robot */ public Robot(String name) { this.name = name; this.pos = new Point2D(0,0); this.energy = 100; this.health = 100; } /** @param health new health value */ public void setHealth(int health) {this.health = health;} /** @param energy new energy value */ public void setEnergy(int energy) {this.energy = energy;} /** @param position new position*/ public void setPosition(int position) {this.position = position;} /** @return The level of health of the robot*/ public int getHealth() {return this.health;} /** @return the energy of the robot*/ public int getHealth() {return this.health;} }
/** * Représente un robot */ public class Robot { private String name; private Point2D position; private int energy; private int health; /** Crée un robot */ public Robot(String name) { this.name = name; this.position = new Point2D(0,0); this.energy = 100; this.health = 100; } /** @param health new health value */ public void setHealth(int health) {this.health = health;} /** @param energy new energy value */ public void setEnergy(int energy) {this.energy = energy;} /** @param position new position*/ public void setPosition(Point2D position) {this.position = position;} /** @return The level of health of the robot*/ public int getHealth() {return this.health;} /** @return the energy of the robot*/ public int getEnergy() {return this.energy;} /** @return the position of the robot*/ public Point2D getPosition() {return this.position;} }
Add getters, change variable names, fix error
Add getters, change variable names, fix error
Java
mit
lovasoa/cours-objet-ecn,lovasoa/cours-objet-ecn
java
## Code Before: /** * Représente un robot */ public class Robot { private String name; private Point2D pos; private int energy; private int health; /** Crée un robot */ public Robot(String name) { this.name = name; this.pos = new Point2D(0,0); this.energy = 100; this.health = 100; } /** @param health new health value */ public void setHealth(int health) {this.health = health;} /** @param energy new energy value */ public void setEnergy(int energy) {this.energy = energy;} /** @param position new position*/ public void setPosition(int position) {this.position = position;} /** @return The level of health of the robot*/ public int getHealth() {return this.health;} /** @return the energy of the robot*/ public int getHealth() {return this.health;} } ## Instruction: Add getters, change variable names, fix error ## Code After: /** * Représente un robot */ public class Robot { private String name; private Point2D position; private int energy; private int health; /** Crée un robot */ public Robot(String name) { this.name = name; this.position = new Point2D(0,0); this.energy = 100; this.health = 100; } /** @param health new health value */ public void setHealth(int health) {this.health = health;} /** @param energy new energy value */ public void setEnergy(int energy) {this.energy = energy;} /** @param position new position*/ public void setPosition(Point2D position) {this.position = position;} /** @return The level of health of the robot*/ public int getHealth() {return this.health;} /** @return the energy of the robot*/ public int getEnergy() {return this.energy;} /** @return the position of the robot*/ public Point2D getPosition() {return this.position;} }
// ... existing code ... */ public class Robot { private String name; private Point2D position; private int energy; private int health; // ... modified code ... /** Crée un robot */ public Robot(String name) { this.name = name; this.position = new Point2D(0,0); this.energy = 100; this.health = 100; } ... public void setEnergy(int energy) {this.energy = energy;} /** @param position new position*/ public void setPosition(Point2D position) {this.position = position;} /** @return The level of health of the robot*/ public int getHealth() {return this.health;} /** @return the energy of the robot*/ public int getEnergy() {return this.energy;} /** @return the position of the robot*/ public Point2D getPosition() {return this.position;} } // ... rest of the code ...
545db99cb432306d5a06c56bfe68c3a3d6380052
src/main/java/technology/tabula/json/TableSerializer.java
src/main/java/technology/tabula/json/TableSerializer.java
package technology.tabula.json; import java.lang.reflect.Type; import java.util.List; import technology.tabula.RectangularTextContainer; import technology.tabula.Table; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public final class TableSerializer implements JsonSerializer<Table> { public static final TableSerializer INSTANCE = new TableSerializer(); private TableSerializer() { // singleton } @Override public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.addProperty("extraction_method", src.getExtractionMethod()); result.addProperty("top", src.getTop()); result.addProperty("left", src.getLeft()); result.addProperty("width", src.getWidth()); result.addProperty("height", src.getHeight()); JsonArray data; result.add("data", data = new JsonArray()); for (List<RectangularTextContainer> srcRow : src.getRows()) { JsonArray row = new JsonArray(); for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk)); data.add(row); } return result; } }
package technology.tabula.json; import java.lang.reflect.Type; import java.util.List; import technology.tabula.RectangularTextContainer; import technology.tabula.Table; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public final class TableSerializer implements JsonSerializer<Table> { public static final TableSerializer INSTANCE = new TableSerializer(); private TableSerializer() { // singleton } @Override public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.addProperty("extraction_method", src.getExtractionMethod()); result.addProperty("top", src.getTop()); result.addProperty("left", src.getLeft()); result.addProperty("width", src.getWidth()); result.addProperty("height", src.getHeight()); result.addProperty("right", src.getRight()); result.addProperty("bottom", src.getBottom()); JsonArray data; result.add("data", data = new JsonArray()); for (List<RectangularTextContainer> srcRow : src.getRows()) { JsonArray row = new JsonArray(); for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk)); data.add(row); } return result; } }
Add right and bottom of area to JSON output
Add right and bottom of area to JSON output
Java
mit
tabulapdf/tabula-java
java
## Code Before: package technology.tabula.json; import java.lang.reflect.Type; import java.util.List; import technology.tabula.RectangularTextContainer; import technology.tabula.Table; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public final class TableSerializer implements JsonSerializer<Table> { public static final TableSerializer INSTANCE = new TableSerializer(); private TableSerializer() { // singleton } @Override public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.addProperty("extraction_method", src.getExtractionMethod()); result.addProperty("top", src.getTop()); result.addProperty("left", src.getLeft()); result.addProperty("width", src.getWidth()); result.addProperty("height", src.getHeight()); JsonArray data; result.add("data", data = new JsonArray()); for (List<RectangularTextContainer> srcRow : src.getRows()) { JsonArray row = new JsonArray(); for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk)); data.add(row); } return result; } } ## Instruction: Add right and bottom of area to JSON output ## Code After: package technology.tabula.json; import java.lang.reflect.Type; import java.util.List; import technology.tabula.RectangularTextContainer; import technology.tabula.Table; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public final class TableSerializer implements JsonSerializer<Table> { public static final TableSerializer INSTANCE = new TableSerializer(); private TableSerializer() { // singleton } @Override public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.addProperty("extraction_method", src.getExtractionMethod()); result.addProperty("top", src.getTop()); result.addProperty("left", src.getLeft()); result.addProperty("width", src.getWidth()); result.addProperty("height", src.getHeight()); result.addProperty("right", src.getRight()); result.addProperty("bottom", src.getBottom()); JsonArray data; result.add("data", data = new JsonArray()); for (List<RectangularTextContainer> srcRow : src.getRows()) { JsonArray row = new JsonArray(); for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk)); data.add(row); } return result; } }
... result.addProperty("left", src.getLeft()); result.addProperty("width", src.getWidth()); result.addProperty("height", src.getHeight()); result.addProperty("right", src.getRight()); result.addProperty("bottom", src.getBottom()); JsonArray data; result.add("data", data = new JsonArray()); ...
65691f0781253b68f67faa71b0e81d3ae1d0c363
setup.py
setup.py
from setuptools import setup setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='[email protected]', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', )
import sys from setuptools import setup pytest_runner = ['pytest-runner'] if 'ptr' in sys.argv else [] setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='[email protected]', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], tests_require=['pytest', 'mock'], setup_requires=[] + pytest_runner, description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', )
Allow tests to be run with pytest-runner.
Allow tests to be run with pytest-runner.
Python
mit
btubbs/sseclient
python
## Code Before: from setuptools import setup setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='[email protected]', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', ) ## Instruction: Allow tests to be run with pytest-runner. ## Code After: import sys from setuptools import setup pytest_runner = ['pytest-runner'] if 'ptr' in sys.argv else [] setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='[email protected]', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], tests_require=['pytest', 'mock'], setup_requires=[] + pytest_runner, description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', )
// ... existing code ... import sys from setuptools import setup pytest_runner = ['pytest-runner'] if 'ptr' in sys.argv else [] setup( name='sseclient', // ... modified code ... author_email='[email protected]', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], tests_require=['pytest', 'mock'], setup_requires=[] + pytest_runner, description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), // ... rest of the code ...
031e7e584a6566586c1ee7758a4f619bb161f4cd
utils/parse_worksheet.py
utils/parse_worksheet.py
def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass
def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass def parse_worksheet(): pass
Add code to fix failing test
Add code to fix failing test
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
python
## Code Before: def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass ## Instruction: Add code to fix failing test ## Code After: def __open_worksheet(): pass def __get_data(): pass def __write_data(): pass def parse_worksheet(): pass
// ... existing code ... def __write_data(): pass def parse_worksheet(): pass // ... rest of the code ...
87f44bb68af64f2654c68fb60bf93a34ac6095a6
pylearn2/scripts/dbm/dbm_metrics.py
pylearn2/scripts/dbm/dbm_metrics.py
import argparse if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=["ais"]) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = args.metric model_path = args.model_path
import argparse from pylearn2.utils import serial def compute_ais(model): pass if __name__ == '__main__': # Possible metrics metrics = {'ais': compute_ais} # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=metrics.keys()) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = metrics[args.metric] model = serial.load(args.model_path) metric(model)
Make the script recuperate the correct method
Make the script recuperate the correct method
Python
bsd-3-clause
fyffyt/pylearn2,daemonmaker/pylearn2,se4u/pylearn2,hyqneuron/pylearn2-maxsom,abergeron/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,w1kke/pylearn2,matrogers/pylearn2,TNick/pylearn2,msingh172/pylearn2,shiquanwang/pylearn2,pkainz/pylearn2,fishcorn/pylearn2,chrish42/pylearn,kose-y/pylearn2,Refefer/pylearn2,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,nouiz/pylearn2,pombredanne/pylearn2,pombredanne/pylearn2,skearnes/pylearn2,CIFASIS/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,hyqneuron/pylearn2-maxsom,ddboline/pylearn2,bartvm/pylearn2,ashhher3/pylearn2,alexjc/pylearn2,aalmah/pylearn2,ddboline/pylearn2,TNick/pylearn2,hyqneuron/pylearn2-maxsom,fulmicoton/pylearn2,msingh172/pylearn2,lancezlin/pylearn2,hantek/pylearn2,JesseLivezey/pylearn2,theoryno3/pylearn2,aalmah/pylearn2,CIFASIS/pylearn2,mclaughlin6464/pylearn2,mclaughlin6464/pylearn2,ashhher3/pylearn2,lisa-lab/pylearn2,aalmah/pylearn2,junbochen/pylearn2,woozzu/pylearn2,JesseLivezey/pylearn2,goodfeli/pylearn2,hantek/pylearn2,cosmoharrigan/pylearn2,aalmah/pylearn2,fishcorn/pylearn2,CIFASIS/pylearn2,lunyang/pylearn2,woozzu/pylearn2,ashhher3/pylearn2,junbochen/pylearn2,pkainz/pylearn2,ashhher3/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,shiquanwang/pylearn2,lisa-lab/pylearn2,KennethPierce/pylearnk,cosmoharrigan/pylearn2,abergeron/pylearn2,mkraemer67/pylearn2,chrish42/pylearn,kastnerkyle/pylearn2,pkainz/pylearn2,lancezlin/pylearn2,sandeepkbhat/pylearn2,se4u/pylearn2,kastnerkyle/pylearn2,JesseLivezey/plankton,TNick/pylearn2,kastnerkyle/pylearn2,caidongyun/pylearn2,junbochen/pylearn2,ddboline/pylearn2,goodfeli/pylearn2,caidongyun/pylearn2,w1kke/pylearn2,abergeron/pylearn2,nouiz/pylearn2,jamessergeant/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,fulmicoton/pylearn2,lamblin/pylearn2,fishcorn/pylearn2,jeremyfix/pylearn2,JesseLivezey/plankton,jeremyfix/pylearn2,mkraemer67/pylearn2,nouiz/pylearn2,jamessergeant/pylearn2,JesseLivezey/plankton,theoryno3/pylearn2,JesseLivezey/pylearn2,fulmicoton/pylearn2,skearnes/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,mkraemer67/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,KennethPierce/pylearnk,lamblin/pylearn2,alexjc/pylearn2,Refefer/pylearn2,theoryno3/pylearn2,kose-y/pylearn2,shiquanwang/pylearn2,daemonmaker/pylearn2,hyqneuron/pylearn2-maxsom,Refefer/pylearn2,cosmoharrigan/pylearn2,jamessergeant/pylearn2,woozzu/pylearn2,lunyang/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lunyang/pylearn2,caidongyun/pylearn2,hantek/pylearn2,matrogers/pylearn2,chrish42/pylearn,bartvm/pylearn2,jeremyfix/pylearn2,theoryno3/pylearn2,fyffyt/pylearn2,goodfeli/pylearn2,KennethPierce/pylearnk,junbochen/pylearn2,bartvm/pylearn2,msingh172/pylearn2,pombredanne/pylearn2,sandeepkbhat/pylearn2,hantek/pylearn2,alexjc/pylearn2,mclaughlin6464/pylearn2,JesseLivezey/pylearn2,kose-y/pylearn2,matrogers/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,msingh172/pylearn2,mkraemer67/pylearn2,se4u/pylearn2,TNick/pylearn2,KennethPierce/pylearnk,w1kke/pylearn2,kose-y/pylearn2,CIFASIS/pylearn2,JesseLivezey/plankton,pombredanne/pylearn2,kastnerkyle/pylearn2,goodfeli/pylearn2,w1kke/pylearn2,lisa-lab/pylearn2,pkainz/pylearn2,jeremyfix/pylearn2,fyffyt/pylearn2,sandeepkbhat/pylearn2,se4u/pylearn2,lamblin/pylearn2,Refefer/pylearn2,sandeepkbhat/pylearn2,alexjc/pylearn2,nouiz/pylearn2,daemonmaker/pylearn2,matrogers/pylearn2
python
## Code Before: import argparse if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=["ais"]) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = args.metric model_path = args.model_path ## Instruction: Make the script recuperate the correct method ## Code After: import argparse from pylearn2.utils import serial def compute_ais(model): pass if __name__ == '__main__': # Possible metrics metrics = {'ais': compute_ais} # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=metrics.keys()) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = metrics[args.metric] model = serial.load(args.model_path) metric(model)
# ... existing code ... import argparse from pylearn2.utils import serial def compute_ais(model): pass if __name__ == '__main__': # Possible metrics metrics = {'ais': compute_ais} # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=metrics.keys()) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = metrics[args.metric] model = serial.load(args.model_path) metric(model) # ... rest of the code ...
188ac85b8e8f82a06426467554d608d713d258ef
test/test_get_new.py
test/test_get_new.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os import sys import pytest @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text @needinternet def test_check_get_invalid_archive(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('what file? hahahaha', r'http://rlee287.github.io/pyautoupdate/testing2/', newfiles="project.tar.gz") launch._get_new() assert os.path.isfile("project.tar.gz.dump") os.remove("project.tar.gz.dump")
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text @needinternet def test_check_get_invalid_archive(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('what file? hahahaha', r'http://rlee287.github.io/pyautoupdate/testing2/', newfiles="project.tar.gz") launch._get_new() assert os.path.isfile("project.tar.gz.dump") os.remove("project.tar.gz.dump")
Remove unused imports from test_check_get_new
Remove unused imports from test_check_get_new
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
python
## Code Before: from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os import sys import pytest @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text @needinternet def test_check_get_invalid_archive(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('what file? hahahaha', r'http://rlee287.github.io/pyautoupdate/testing2/', newfiles="project.tar.gz") launch._get_new() assert os.path.isfile("project.tar.gz.dump") os.remove("project.tar.gz.dump") ## Instruction: Remove unused imports from test_check_get_new ## Code After: from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text @needinternet def test_check_get_invalid_archive(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('what file? hahahaha', r'http://rlee287.github.io/pyautoupdate/testing2/', newfiles="project.tar.gz") launch._get_new() assert os.path.isfile("project.tar.gz.dump") os.remove("project.tar.gz.dump")
// ... existing code ... from .pytest_makevers import fixture_update_dir import os @needinternet def test_check_get_new(fixture_update_dir): // ... rest of the code ...
aed4ddb9cd50baf318822830ba49d5b994e4e518
youmap/views.py
youmap/views.py
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.all()[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view()
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view()
Order map by modified_at desc in list
Order map by modified_at desc in list
Python
agpl-3.0
diraol/umap
python
## Code Before: from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.all()[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view() ## Instruction: Order map by modified_at desc in list ## Code After: from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view()
... list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { "maps": maps } ...
6856c469da365c7463017e4c064e1ed25c12dfdc
foyer/tests/test_performance.py
foyer/tests/test_performance.py
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
Allow for some missing silica bond parameters
Python
mit
mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer
python
## Code Before: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100) ## Instruction: Allow for some missing silica bond parameters ## Code After: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
// ... existing code ... def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) // ... rest of the code ...
c04a0bbe56e97a96df28f8505f6601df0c638f71
src/blackred/__init__.py
src/blackred/__init__.py
from .blackred import BlackRed
# flake8: noqa from .blackred import BlackRed
Make the flake8 test pass
Make the flake8 test pass The import in the `__init__.py` should not be reported by flake8. The warning itself is OK, but not for this file.
Python
apache-2.0
edelbluth/blackred,edelbluth/blackred
python
## Code Before: from .blackred import BlackRed ## Instruction: Make the flake8 test pass The import in the `__init__.py` should not be reported by flake8. The warning itself is OK, but not for this file. ## Code After: # flake8: noqa from .blackred import BlackRed
// ... existing code ... # flake8: noqa from .blackred import BlackRed // ... rest of the code ...
f7f20c50b82e3b8f8f2be4687e661348979fe6a6
script_helpers.py
script_helpers.py
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs='+', help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser
Allow for directories argument to be optional
Allow for directories argument to be optional
Python
bsd-3-clause
mwcraig/msumastro
python
## Code Before: """A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs='+', help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser ## Instruction: Allow for directories argument to be optional ## Code After: """A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser
... action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. ... """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") ...
d52b47eaad73f818974b7feec83fa3b15ddb5aac
form_utils_bootstrap3/tests/__init__.py
form_utils_bootstrap3/tests/__init__.py
import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup()
import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) if django.VERSION >= (1, 8): settings_dict['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [] } ] settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup()
Fix tests for Django trunk
Fix tests for Django trunk
Python
mit
federicobond/django-form-utils-bootstrap3
python
## Code Before: import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup() ## Instruction: Fix tests for Django trunk ## Code After: import os import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'bootstrap3', 'form_utils', ], DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'), MEDIA_URL='/media/', STATIC_URL='/static/', MIDDLEWARE_CLASSES=[], BOOTSTRAP3={ 'form_renderers': { 'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer' } } ) if django.VERSION >= (1, 8): settings_dict['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [] } ] settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup()
// ... existing code ... } ) if django.VERSION >= (1, 8): settings_dict['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [] } ] settings.configure(**settings_dict) // ... rest of the code ...
3b7da8cd1e2f77d73cc19533fc657ba10a80c8cd
include/tgbot/export.h
include/tgbot/export.h
#ifdef TGBOT_DLL #if defined _WIN32 || defined __CYGWIN__ #define TGBOT_HELPER_DLL_IMPORT __declspec(dllimport) #define TGBOT_HELPER_DLL_EXPORT __declspec(dllexport) #else #if __GNUC__ >= 4 #define TGBOT_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #define TGBOT_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #else #define TGBOT_HELPER_DLL_IMPORT #define TGBOT_HELPER_DLL_EXPORT #endif #endif #ifdef TgBot_EXPORTS #define TGBOT_API TGBOT_HELPER_DLL_EXPORT #else #define FOX_API TGBOT_HELPER_DLL_IMPORT #endif #else #define TGBOT_API #endif #endif #endif //TGBOT_EXPORT_H
#ifdef TGBOT_DLL #if defined _WIN32 || defined __CYGWIN__ #define TGBOT_HELPER_DLL_EXPORT __declspec(dllexport) #define TGBOT_HELPER_DLL_IMPORT __declspec(dllimport) #else #if __GNUC__ >= 4 #define TGBOT_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #define TGBOT_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #else #define TGBOT_HELPER_DLL_EXPORT #define TGBOT_HELPER_DLL_IMPORT #endif #endif #ifdef TgBot_EXPORTS #define TGBOT_API TGBOT_HELPER_DLL_EXPORT #else #define TGBOT_API TGBOT_HELPER_DLL_IMPORT #endif #else #define TGBOT_API #endif #endif #endif //TGBOT_EXPORT_H
Fix mistake FOX and reorder EXPORT/IMPORT
Fix mistake FOX and reorder EXPORT/IMPORT
C
mit
reo7sp/tgbot-cpp,reo7sp/tgbot-cpp,reo7sp/tgbot-cpp
c
## Code Before: #ifdef TGBOT_DLL #if defined _WIN32 || defined __CYGWIN__ #define TGBOT_HELPER_DLL_IMPORT __declspec(dllimport) #define TGBOT_HELPER_DLL_EXPORT __declspec(dllexport) #else #if __GNUC__ >= 4 #define TGBOT_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #define TGBOT_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #else #define TGBOT_HELPER_DLL_IMPORT #define TGBOT_HELPER_DLL_EXPORT #endif #endif #ifdef TgBot_EXPORTS #define TGBOT_API TGBOT_HELPER_DLL_EXPORT #else #define FOX_API TGBOT_HELPER_DLL_IMPORT #endif #else #define TGBOT_API #endif #endif #endif //TGBOT_EXPORT_H ## Instruction: Fix mistake FOX and reorder EXPORT/IMPORT ## Code After: #ifdef TGBOT_DLL #if defined _WIN32 || defined __CYGWIN__ #define TGBOT_HELPER_DLL_EXPORT __declspec(dllexport) #define TGBOT_HELPER_DLL_IMPORT __declspec(dllimport) #else #if __GNUC__ >= 4 #define TGBOT_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #define TGBOT_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #else #define TGBOT_HELPER_DLL_EXPORT #define TGBOT_HELPER_DLL_IMPORT #endif #endif #ifdef TgBot_EXPORTS #define TGBOT_API TGBOT_HELPER_DLL_EXPORT #else #define TGBOT_API TGBOT_HELPER_DLL_IMPORT #endif #else #define TGBOT_API #endif #endif #endif //TGBOT_EXPORT_H
... #ifdef TGBOT_DLL #if defined _WIN32 || defined __CYGWIN__ #define TGBOT_HELPER_DLL_EXPORT __declspec(dllexport) #define TGBOT_HELPER_DLL_IMPORT __declspec(dllimport) #else #if __GNUC__ >= 4 #define TGBOT_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #define TGBOT_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #else #define TGBOT_HELPER_DLL_EXPORT #define TGBOT_HELPER_DLL_IMPORT #endif #endif #ifdef TgBot_EXPORTS #define TGBOT_API TGBOT_HELPER_DLL_EXPORT #else #define TGBOT_API TGBOT_HELPER_DLL_IMPORT #endif #else #define TGBOT_API ...
77f99f4862ded1b8493b5895e4f9d88a3bbf722b
source/globals/fieldtests.py
source/globals/fieldtests.py
import wx ## Tests if a wx control/instance is enabled # # Function for compatibility between wx versions # \param enabled # \b \e bool : Check if enabled or disabled def FieldEnabled(field, enabled=True): if wx.MAJOR_VERSION > 2: return field.IsThisEnabled() == enabled else: return field.IsEnabled() == enabled ## Tests multiple fields # # \return # \b \e bool : True if all fields are enabled def FieldsEnabled(field_list): if isinstance(field_list, (tuple, list)): return FieldEnabled(field_list) for F in field_list: if not FieldEnabled(F): return False return True
import wx ## Tests if a wx control/instance is enabled/disabled # # Function for compatibility between wx versions # \param field # \b \e wx.Window : the wx control to check # \param enabled # \b \e bool : Check if enabled or disabled # \return # \b \e bool : True if field's enabled status is same as 'enabled' def FieldEnabled(field, enabled=True): if wx.MAJOR_VERSION > 2: return field.IsThisEnabled() == enabled else: return field.IsEnabled() == enabled ## Tests if a wx control/instance is disabled # # \param field # \b \e wx.Window : The wx field to check # \return # \b \e : True if field is disabled def FieldDisabled(field): return FieldEnabled(field, False) ## Tests multiple fields # # \return # \b \e bool : True if all fields are enabled def FieldsEnabled(field_list): if isinstance(field_list, (tuple, list)): return FieldEnabled(field_list) for F in field_list: if not FieldEnabled(F): return False return True
Add function FieldDisabled to test for disabled controls
Add function FieldDisabled to test for disabled controls
Python
mit
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
python
## Code Before: import wx ## Tests if a wx control/instance is enabled # # Function for compatibility between wx versions # \param enabled # \b \e bool : Check if enabled or disabled def FieldEnabled(field, enabled=True): if wx.MAJOR_VERSION > 2: return field.IsThisEnabled() == enabled else: return field.IsEnabled() == enabled ## Tests multiple fields # # \return # \b \e bool : True if all fields are enabled def FieldsEnabled(field_list): if isinstance(field_list, (tuple, list)): return FieldEnabled(field_list) for F in field_list: if not FieldEnabled(F): return False return True ## Instruction: Add function FieldDisabled to test for disabled controls ## Code After: import wx ## Tests if a wx control/instance is enabled/disabled # # Function for compatibility between wx versions # \param field # \b \e wx.Window : the wx control to check # \param enabled # \b \e bool : Check if enabled or disabled # \return # \b \e bool : True if field's enabled status is same as 'enabled' def FieldEnabled(field, enabled=True): if wx.MAJOR_VERSION > 2: return field.IsThisEnabled() == enabled else: return field.IsEnabled() == enabled ## Tests if a wx control/instance is disabled # # \param field # \b \e wx.Window : The wx field to check # \return # \b \e : True if field is disabled def FieldDisabled(field): return FieldEnabled(field, False) ## Tests multiple fields # # \return # \b \e bool : True if all fields are enabled def FieldsEnabled(field_list): if isinstance(field_list, (tuple, list)): return FieldEnabled(field_list) for F in field_list: if not FieldEnabled(F): return False return True
# ... existing code ... import wx ## Tests if a wx control/instance is enabled/disabled # # Function for compatibility between wx versions # \param field # \b \e wx.Window : the wx control to check # \param enabled # \b \e bool : Check if enabled or disabled # \return # \b \e bool : True if field's enabled status is same as 'enabled' def FieldEnabled(field, enabled=True): if wx.MAJOR_VERSION > 2: return field.IsThisEnabled() == enabled # ... modified code ... else: return field.IsEnabled() == enabled ## Tests if a wx control/instance is disabled # # \param field # \b \e wx.Window : The wx field to check # \return # \b \e : True if field is disabled def FieldDisabled(field): return FieldEnabled(field, False) ## Tests multiple fields # ... rest of the code ...
23c59a06b001f447802f8a118203baca17ee2c5f
c/temperature.c
c/temperature.c
// k&r farenheit to celcius table int main() { int fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%d\t%d\t\n", fahr, celsius); fahr = fahr + step; } return 0; }
// k&r farenheit to celcius table int main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; // first print table header printf("%s %s\n", "Fahr", "Cels"); // then calculate values and print them to table fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } return 0; }
Use floats instead of ints, print table header
Use floats instead of ints, print table header
C
mit
oldhill/halloween,oldhill/halloween,oldhill/halloween,oldhill/halloween
c
## Code Before: // k&r farenheit to celcius table int main() { int fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%d\t%d\t\n", fahr, celsius); fahr = fahr + step; } return 0; } ## Instruction: Use floats instead of ints, print table header ## Code After: // k&r farenheit to celcius table int main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; // first print table header printf("%s %s\n", "Fahr", "Cels"); // then calculate values and print them to table fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } return 0; }
... int main() { float fahr, celsius; int lower, upper, step; lower = 0; ... upper = 300; step = 20; // first print table header printf("%s %s\n", "Fahr", "Cels"); // then calculate values and print them to table fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } ...
45f8af99e90f211e76d1da497ef546d960153472
app/src/main/java/com/github/mkjensen/tv/util/CrashlyticsTimberTree.java
app/src/main/java/com/github/mkjensen/tv/util/CrashlyticsTimberTree.java
/* * Copyright 2017 Martin Kamp Jensen * * 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 com.github.mkjensen.tv.util; import com.crashlytics.android.Crashlytics; import timber.log.Timber; public class CrashlyticsTimberTree extends Timber.Tree { private static final String PRIORITY_KEY = "priority"; private static final String TAG_KEY = "tag"; private static final String MESSAGE_KEY = "message"; @Override protected void log(int priority, String tag, String message, Throwable throwable) { if (priority < android.util.Log.WARN) { return; } Crashlytics.setInt(PRIORITY_KEY, priority); Crashlytics.setString(TAG_KEY, tag); Crashlytics.setString(MESSAGE_KEY, message); if (throwable == null) { Crashlytics.logException(new Exception(message)); } else { Crashlytics.logException(throwable); } } }
/* * Copyright 2017 Martin Kamp Jensen * * 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 com.github.mkjensen.tv.util; import android.support.annotation.NonNull; import com.crashlytics.android.Crashlytics; import timber.log.Timber; public class CrashlyticsTimberTree extends Timber.Tree { private static final String PRIORITY_KEY = "priority"; private static final String TAG_KEY = "tag"; private static final String MESSAGE_KEY = "message"; @Override protected void log(int priority, String tag, @NonNull String message, Throwable throwable) { if (priority < android.util.Log.WARN) { return; } Crashlytics.setInt(PRIORITY_KEY, priority); Crashlytics.setString(TAG_KEY, tag); Crashlytics.setString(MESSAGE_KEY, message); if (throwable == null) { Crashlytics.logException(new Exception(message)); } else { Crashlytics.logException(throwable); } } }
Add @NonNull to message parameter of overridden method log
Add @NonNull to message parameter of overridden method log
Java
apache-2.0
mkjensen/tv
java
## Code Before: /* * Copyright 2017 Martin Kamp Jensen * * 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 com.github.mkjensen.tv.util; import com.crashlytics.android.Crashlytics; import timber.log.Timber; public class CrashlyticsTimberTree extends Timber.Tree { private static final String PRIORITY_KEY = "priority"; private static final String TAG_KEY = "tag"; private static final String MESSAGE_KEY = "message"; @Override protected void log(int priority, String tag, String message, Throwable throwable) { if (priority < android.util.Log.WARN) { return; } Crashlytics.setInt(PRIORITY_KEY, priority); Crashlytics.setString(TAG_KEY, tag); Crashlytics.setString(MESSAGE_KEY, message); if (throwable == null) { Crashlytics.logException(new Exception(message)); } else { Crashlytics.logException(throwable); } } } ## Instruction: Add @NonNull to message parameter of overridden method log ## Code After: /* * Copyright 2017 Martin Kamp Jensen * * 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 com.github.mkjensen.tv.util; import android.support.annotation.NonNull; import com.crashlytics.android.Crashlytics; import timber.log.Timber; public class CrashlyticsTimberTree extends Timber.Tree { private static final String PRIORITY_KEY = "priority"; private static final String TAG_KEY = "tag"; private static final String MESSAGE_KEY = "message"; @Override protected void log(int priority, String tag, @NonNull String message, Throwable throwable) { if (priority < android.util.Log.WARN) { return; } Crashlytics.setInt(PRIORITY_KEY, priority); Crashlytics.setString(TAG_KEY, tag); Crashlytics.setString(MESSAGE_KEY, message); if (throwable == null) { Crashlytics.logException(new Exception(message)); } else { Crashlytics.logException(throwable); } } }
... package com.github.mkjensen.tv.util; import android.support.annotation.NonNull; import com.crashlytics.android.Crashlytics; import timber.log.Timber; ... private static final String MESSAGE_KEY = "message"; @Override protected void log(int priority, String tag, @NonNull String message, Throwable throwable) { if (priority < android.util.Log.WARN) { return; ...
613c01517288ef7d3170dd7ab4dc2d3541a77168
chainerrl/misc/is_return_code_zero.py
chainerrl/misc/is_return_code_zero.py
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import subprocess def is_return_code_zero(args): """Return true iff the given command's return code is zero. All the messages to stdout or stderr are suppressed. """ FNULL = open(os.devnull, 'w') try: subprocess.check_call(args, stdout=FNULL, stderr=FNULL) except subprocess.CalledProcessError: # The given command returned an error return False except OSError: # The given command was not found return False return True
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import subprocess def is_return_code_zero(args): """Return true iff the given command's return code is zero. All the messages to stdout or stderr are suppressed. """ with open(os.devnull, 'wb') as FNULL: try: subprocess.check_call(args, stdout=FNULL, stderr=FNULL) except subprocess.CalledProcessError: # The given command returned an error return False except OSError: # The given command was not found return False return True
Fix ResourceWarning: unclosed file of devnull
Fix ResourceWarning: unclosed file of devnull
Python
mit
toslunar/chainerrl,toslunar/chainerrl
python
## Code Before: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import subprocess def is_return_code_zero(args): """Return true iff the given command's return code is zero. All the messages to stdout or stderr are suppressed. """ FNULL = open(os.devnull, 'w') try: subprocess.check_call(args, stdout=FNULL, stderr=FNULL) except subprocess.CalledProcessError: # The given command returned an error return False except OSError: # The given command was not found return False return True ## Instruction: Fix ResourceWarning: unclosed file of devnull ## Code After: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import subprocess def is_return_code_zero(args): """Return true iff the given command's return code is zero. All the messages to stdout or stderr are suppressed. """ with open(os.devnull, 'wb') as FNULL: try: subprocess.check_call(args, stdout=FNULL, stderr=FNULL) except subprocess.CalledProcessError: # The given command returned an error return False except OSError: # The given command was not found return False return True
# ... existing code ... All the messages to stdout or stderr are suppressed. """ with open(os.devnull, 'wb') as FNULL: try: subprocess.check_call(args, stdout=FNULL, stderr=FNULL) except subprocess.CalledProcessError: # The given command returned an error return False except OSError: # The given command was not found return False return True # ... rest of the code ...
77ee44b0af8a80babf0a88ddd4f53f2f4ad10d2d
tests/test_event.py
tests/test_event.py
import unittest from evesp.event import Event class TestEvent(unittest.TestCase): def setUp(self): self.evt = Event(foo='bar') def test_event_creation(self): self.assertEqual(self.evt.foo, 'bar') self.assertRaises(AttributeError, getattr, self.evt, 'non_existing') def test_event_pickle_serialization(self): ser_evt = self.evt.serialize() deser_evt = Event.deserialize(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') def test_event_json_serialization(self): ser_evt = self.evt.to_json() deser_evt = Event.from_json(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') if __name__ == "__main__": unittest.main() # vim:sw=4:ts=4:et:
import unittest from evesp.event import Event class TestEvent(unittest.TestCase): def setUp(self): self.evt = Event(foo='bar') def test_event_creation(self): self.assertEqual(self.evt.foo, 'bar') def test_non_existing_event(self): self.assertRaises(AttributeError, getattr, self.evt, 'non_existing') def test_event_pickle_serialization(self): ser_evt = self.evt.serialize() deser_evt = Event.deserialize(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') def test_event_json_serialization(self): ser_evt = self.evt.to_json() deser_evt = Event.from_json(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') if __name__ == "__main__": unittest.main() # vim:sw=4:ts=4:et:
Split one test into two tests
Split one test into two tests
Python
apache-2.0
BlackLight/evesp
python
## Code Before: import unittest from evesp.event import Event class TestEvent(unittest.TestCase): def setUp(self): self.evt = Event(foo='bar') def test_event_creation(self): self.assertEqual(self.evt.foo, 'bar') self.assertRaises(AttributeError, getattr, self.evt, 'non_existing') def test_event_pickle_serialization(self): ser_evt = self.evt.serialize() deser_evt = Event.deserialize(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') def test_event_json_serialization(self): ser_evt = self.evt.to_json() deser_evt = Event.from_json(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') if __name__ == "__main__": unittest.main() # vim:sw=4:ts=4:et: ## Instruction: Split one test into two tests ## Code After: import unittest from evesp.event import Event class TestEvent(unittest.TestCase): def setUp(self): self.evt = Event(foo='bar') def test_event_creation(self): self.assertEqual(self.evt.foo, 'bar') def test_non_existing_event(self): self.assertRaises(AttributeError, getattr, self.evt, 'non_existing') def test_event_pickle_serialization(self): ser_evt = self.evt.serialize() deser_evt = Event.deserialize(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') def test_event_json_serialization(self): ser_evt = self.evt.to_json() deser_evt = Event.from_json(ser_evt) self.assertEqual(deser_evt.foo, 'bar') self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing') if __name__ == "__main__": unittest.main() # vim:sw=4:ts=4:et:
... def test_event_creation(self): self.assertEqual(self.evt.foo, 'bar') def test_non_existing_event(self): self.assertRaises(AttributeError, getattr, self.evt, 'non_existing') def test_event_pickle_serialization(self): ...
ccb2718f8cac8ce138229a70174b84e74bf50b1e
test/source/se/ericthelin/fractions/GreatestCommonDivisorTest.java
test/source/se/ericthelin/fractions/GreatestCommonDivisorTest.java
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } }
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } }
Check that GreatestCommonDivisor accepts negative second argument
Check that GreatestCommonDivisor accepts negative second argument
Java
mit
eric-thelin/fractions
java
## Code Before: package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } } ## Instruction: Check that GreatestCommonDivisor accepts negative second argument ## Code After: package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } }
... public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } } ...
0b845f6beaec8f7ce8e4cd473ed50fe1202b5139
seabird/qc.py
seabird/qc.py
import logging from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: #self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger)
import logging from os.path import basename from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger)
Add filename in attrs if fails to load it.
Add filename in attrs if fails to load it. Filename in attrs helps to debug.
Python
bsd-3-clause
castelao/seabird
python
## Code Before: import logging from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: #self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger) ## Instruction: Add filename in attrs if fails to load it. Filename in attrs helps to debug. ## Code After: import logging from os.path import basename from cotede.qc import ProfileQC from . import fCNV from .exceptions import CNVError class fProfileQC(ProfileQC): """ Apply ProfileQC from CoTeDe straight from a file. """ def __init__(self, inputfile, cfg=None, saveauxiliary=True, verbose=True, logger=None): """ """ self.logger = logging.getLogger(logger or 'seabird.qc.fProfileQC') self.name = 'fProfileQC' try: # Not the best way, but will work for now. I should pass # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise super(fProfileQC, self).__init__(profile, cfg=cfg, saveauxiliary=saveauxiliary, verbose=verbose, logger=logger)
... import logging from os.path import basename from cotede.qc import ProfileQC from . import fCNV ... # the reference for the logger being used. profile = fCNV(inputfile, logger=None) except CNVError as e: self.attributes['filename'] = basename(inputfile) logging.error(e.msg) raise ...
9b35326243c3e6d991bba8dfc948600262ebc557
test/_helpers.py
test/_helpers.py
import datetime import mock from functools import wraps from twisted.internet.defer import Deferred class NewDate(datetime.date): @classmethod def today(cls): return cls(2012, 12, 10) class NewDateTime(datetime.datetime): @classmethod def now(cls): return cls(2012, 12, 10, 00, 00, 00, 00, None) class DeferredHelper(object): def __init__(self, data=None): self.data = data self.deferred = Deferred() self.addCallback = self.deferred.addCallback self.addCallbacks = self.deferred.addCallbacks self.addErrback = self.deferred.addErrback def callback(self, result=None): if result is None: result = self.data self.deferred.callback(result) def errback(self, failure=None): if failure is None: failure = self.data self.deferred.errback(failure) def __call__(self, *args): self.args = args return self def mock_is_admin(f): @wraps(f) def wrapper(*args, **kwargs): with mock.patch("lala.pluginmanager.is_admin") as mocked: mocked.return_value = True return f(*args, **kwargs) return wrapper
import datetime import mock from functools import wraps from twisted.internet.defer import Deferred class NewDate(datetime.date): @classmethod def today(cls): return cls(2012, 12, 10) class NewDateTime(datetime.datetime): @classmethod def now(cls): return cls(2012, 12, 10, 00, 00, 00, 00, None) class DeferredHelper(Deferred): def __init__(self, data=None): Deferred.__init__(self) self.data = data def callback(self, result=None): if result is None: result = self.data return Deferred.callback(self, result) def errback(self, failure=None): if failure is None: failure = self.data return Deferred.errback(self, failure) def __call__(self, *args): self.args = args return self def mock_is_admin(f): @wraps(f) def wrapper(*args, **kwargs): with mock.patch("lala.pluginmanager.is_admin") as mocked: mocked.return_value = True return f(*args, **kwargs) return wrapper
Make DeferredHelper even more like a Deferred by subclassing
Make DeferredHelper even more like a Deferred by subclassing
Python
mit
mineo/lala,mineo/lala
python
## Code Before: import datetime import mock from functools import wraps from twisted.internet.defer import Deferred class NewDate(datetime.date): @classmethod def today(cls): return cls(2012, 12, 10) class NewDateTime(datetime.datetime): @classmethod def now(cls): return cls(2012, 12, 10, 00, 00, 00, 00, None) class DeferredHelper(object): def __init__(self, data=None): self.data = data self.deferred = Deferred() self.addCallback = self.deferred.addCallback self.addCallbacks = self.deferred.addCallbacks self.addErrback = self.deferred.addErrback def callback(self, result=None): if result is None: result = self.data self.deferred.callback(result) def errback(self, failure=None): if failure is None: failure = self.data self.deferred.errback(failure) def __call__(self, *args): self.args = args return self def mock_is_admin(f): @wraps(f) def wrapper(*args, **kwargs): with mock.patch("lala.pluginmanager.is_admin") as mocked: mocked.return_value = True return f(*args, **kwargs) return wrapper ## Instruction: Make DeferredHelper even more like a Deferred by subclassing ## Code After: import datetime import mock from functools import wraps from twisted.internet.defer import Deferred class NewDate(datetime.date): @classmethod def today(cls): return cls(2012, 12, 10) class NewDateTime(datetime.datetime): @classmethod def now(cls): return cls(2012, 12, 10, 00, 00, 00, 00, None) class DeferredHelper(Deferred): def __init__(self, data=None): Deferred.__init__(self) self.data = data def callback(self, result=None): if result is None: result = self.data return Deferred.callback(self, result) def errback(self, failure=None): if failure is None: failure = self.data return Deferred.errback(self, failure) def __call__(self, *args): self.args = args return self def mock_is_admin(f): @wraps(f) def wrapper(*args, **kwargs): with mock.patch("lala.pluginmanager.is_admin") as mocked: mocked.return_value = True return f(*args, **kwargs) return wrapper
// ... existing code ... return cls(2012, 12, 10, 00, 00, 00, 00, None) class DeferredHelper(Deferred): def __init__(self, data=None): Deferred.__init__(self) self.data = data def callback(self, result=None): if result is None: result = self.data return Deferred.callback(self, result) def errback(self, failure=None): if failure is None: failure = self.data return Deferred.errback(self, failure) def __call__(self, *args): self.args = args // ... rest of the code ...
d2fb1f22be6c6434873f2bcafb6b8a9b714acde9
website/archiver/decorators.py
website/archiver/decorators.py
import functools from framework.exceptions import HTTPError from website.project.decorators import _inject_nodes from website.archiver import ARCHIVER_UNCAUGHT_ERROR from website.archiver import utils def fail_archive_on_error(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except HTTPError as e: _inject_nodes(kwargs) registration = kwargs['node'] utils.handle_archive_fail( ARCHIVER_UNCAUGHT_ERROR, registration.registered_from, registration, registration.registered_user, str(e) ) return wrapped
import functools from framework.exceptions import HTTPError from website.project.decorators import _inject_nodes from website.archiver import ARCHIVER_UNCAUGHT_ERROR from website.archiver import signals def fail_archive_on_error(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except HTTPError as e: _inject_nodes(kwargs) registration = kwargs['node'] signals.send.archive_fail( registration, ARCHIVER_UNCAUGHT_ERROR, [str(e)] ) return wrapped
Use fail signal in fail_archive_on_error decorator
Use fail signal in fail_archive_on_error decorator
Python
apache-2.0
amyshi188/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,mluke93/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,jeffreyliu3230/osf.io,chrisseto/osf.io,acshi/osf.io,mattclark/osf.io,billyhunt/osf.io,caneruguz/osf.io,cosenal/osf.io,SSJohns/osf.io,njantrania/osf.io,mattclark/osf.io,alexschiller/osf.io,samchrisinger/osf.io,HarryRybacki/osf.io,MerlinZhang/osf.io,mluo613/osf.io,TomBaxter/osf.io,mattclark/osf.io,kch8qx/osf.io,baylee-d/osf.io,chennan47/osf.io,asanfilippo7/osf.io,asanfilippo7/osf.io,amyshi188/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,brandonPurvis/osf.io,acshi/osf.io,bdyetton/prettychart,danielneis/osf.io,brianjgeiger/osf.io,kch8qx/osf.io,emetsger/osf.io,reinaH/osf.io,ticklemepierce/osf.io,felliott/osf.io,hmoco/osf.io,SSJohns/osf.io,danielneis/osf.io,wearpants/osf.io,HalcyonChimera/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,cldershem/osf.io,adlius/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,sloria/osf.io,Johnetordoff/osf.io,doublebits/osf.io,MerlinZhang/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,Nesiehr/osf.io,billyhunt/osf.io,crcresearch/osf.io,njantrania/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,mfraezz/osf.io,hmoco/osf.io,jinluyuan/osf.io,monikagrabowska/osf.io,danielneis/osf.io,aaxelb/osf.io,Nesiehr/osf.io,caseyrygt/osf.io,kwierman/osf.io,cldershem/osf.io,brandonPurvis/osf.io,cwisecarver/osf.io,fabianvf/osf.io,amyshi188/osf.io,petermalcolm/osf.io,adlius/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,laurenrevere/osf.io,rdhyee/osf.io,samanehsan/osf.io,haoyuchen1992/osf.io,asanfilippo7/osf.io,dplorimer/osf,leb2dg/osf.io,mfraezz/osf.io,abought/osf.io,amyshi188/osf.io,doublebits/osf.io,sbt9uc/osf.io,lyndsysimon/osf.io,dplorimer/osf,caneruguz/osf.io,laurenrevere/osf.io,ticklemepierce/osf.io,lyndsysimon/osf.io,DanielSBrown/osf.io,jmcarp/osf.io,baylee-d/osf.io,GageGaskins/osf.io,chennan47/osf.io,fabianvf/osf.io,cldershem/osf.io,jmcarp/osf.io,jnayak1/osf.io,binoculars/osf.io,zamattiac/osf.io,acshi/osf.io,crcresearch/osf.io,jinluyuan/osf.io,jnayak1/osf.io,binoculars/osf.io,Ghalko/osf.io,jinluyuan/osf.io,cosenal/osf.io,RomanZWang/osf.io,wearpants/osf.io,cslzchen/osf.io,ticklemepierce/osf.io,wearpants/osf.io,samchrisinger/osf.io,SSJohns/osf.io,jeffreyliu3230/osf.io,abought/osf.io,zachjanicki/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,bdyetton/prettychart,MerlinZhang/osf.io,pattisdr/osf.io,chennan47/osf.io,bdyetton/prettychart,caseyrygt/osf.io,samanehsan/osf.io,pattisdr/osf.io,reinaH/osf.io,sloria/osf.io,caseyrollins/osf.io,zamattiac/osf.io,bdyetton/prettychart,caseyrollins/osf.io,TomHeatwole/osf.io,jeffreyliu3230/osf.io,cldershem/osf.io,mluo613/osf.io,KAsante95/osf.io,lyndsysimon/osf.io,zamattiac/osf.io,ZobairAlijan/osf.io,petermalcolm/osf.io,billyhunt/osf.io,chrisseto/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,Ghalko/osf.io,petermalcolm/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,ckc6cz/osf.io,njantrania/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,ckc6cz/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,cwisecarver/osf.io,billyhunt/osf.io,GageGaskins/osf.io,dplorimer/osf,arpitar/osf.io,dplorimer/osf,baylee-d/osf.io,adlius/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,doublebits/osf.io,kwierman/osf.io,adlius/osf.io,aaxelb/osf.io,jnayak1/osf.io,haoyuchen1992/osf.io,KAsante95/osf.io,cwisecarver/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,MerlinZhang/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,ticklemepierce/osf.io,pattisdr/osf.io,erinspace/osf.io,arpitar/osf.io,icereval/osf.io,felliott/osf.io,KAsante95/osf.io,danielneis/osf.io,leb2dg/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,mluo613/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,zamattiac/osf.io,HarryRybacki/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,njantrania/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,cosenal/osf.io,sbt9uc/osf.io,RomanZWang/osf.io,hmoco/osf.io,reinaH/osf.io,Ghalko/osf.io,icereval/osf.io,cslzchen/osf.io,arpitar/osf.io,reinaH/osf.io,zachjanicki/osf.io,jolene-esposito/osf.io,fabianvf/osf.io,alexschiller/osf.io,GageGaskins/osf.io,cslzchen/osf.io,brandonPurvis/osf.io,samchrisinger/osf.io,rdhyee/osf.io,Ghalko/osf.io,Johnetordoff/osf.io,mluo613/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,caseyrygt/osf.io,erinspace/osf.io,kwierman/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,HarryRybacki/osf.io,KAsante95/osf.io,leb2dg/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,kwierman/osf.io,caseyrollins/osf.io,sbt9uc/osf.io,samanehsan/osf.io,wearpants/osf.io,abought/osf.io,ckc6cz/osf.io,crcresearch/osf.io,chrisseto/osf.io,lyndsysimon/osf.io,jolene-esposito/osf.io,fabianvf/osf.io,binoculars/osf.io,kch8qx/osf.io,icereval/osf.io,mluke93/osf.io,Johnetordoff/osf.io,jmcarp/osf.io,mluo613/osf.io,acshi/osf.io,asanfilippo7/osf.io,saradbowman/osf.io,Nesiehr/osf.io,kch8qx/osf.io,mluke93/osf.io,mfraezz/osf.io,TomBaxter/osf.io,samanehsan/osf.io,mluke93/osf.io,arpitar/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,cslzchen/osf.io,sbt9uc/osf.io,ZobairAlijan/osf.io,haoyuchen1992/osf.io,jinluyuan/osf.io,alexschiller/osf.io,jnayak1/osf.io,cosenal/osf.io,sloria/osf.io,HarryRybacki/osf.io,ckc6cz/osf.io,doublebits/osf.io,saradbowman/osf.io,abought/osf.io,doublebits/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,emetsger/osf.io,emetsger/osf.io,acshi/osf.io,aaxelb/osf.io
python
## Code Before: import functools from framework.exceptions import HTTPError from website.project.decorators import _inject_nodes from website.archiver import ARCHIVER_UNCAUGHT_ERROR from website.archiver import utils def fail_archive_on_error(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except HTTPError as e: _inject_nodes(kwargs) registration = kwargs['node'] utils.handle_archive_fail( ARCHIVER_UNCAUGHT_ERROR, registration.registered_from, registration, registration.registered_user, str(e) ) return wrapped ## Instruction: Use fail signal in fail_archive_on_error decorator ## Code After: import functools from framework.exceptions import HTTPError from website.project.decorators import _inject_nodes from website.archiver import ARCHIVER_UNCAUGHT_ERROR from website.archiver import signals def fail_archive_on_error(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except HTTPError as e: _inject_nodes(kwargs) registration = kwargs['node'] signals.send.archive_fail( registration, ARCHIVER_UNCAUGHT_ERROR, [str(e)] ) return wrapped
# ... existing code ... from website.project.decorators import _inject_nodes from website.archiver import ARCHIVER_UNCAUGHT_ERROR from website.archiver import signals def fail_archive_on_error(func): # ... modified code ... except HTTPError as e: _inject_nodes(kwargs) registration = kwargs['node'] signals.send.archive_fail( registration, ARCHIVER_UNCAUGHT_ERROR, [str(e)] ) return wrapped # ... rest of the code ...
123ffcabb6fa783b1524a55dd3dce52ad33a13db
nitrogen/local.py
nitrogen/local.py
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
Fix Local class to work with older werkzeug.
Fix Local class to work with older werkzeug.
Python
bsd-3-clause
mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen
python
## Code Before: import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name)) ## Instruction: Fix Local class to work with older werkzeug. ## Code After: import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
... import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() ... @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) ...
29f91d362689a53e04557588e47f1ac3e8d0fadc
server/lib/pricing.py
server/lib/pricing.py
def price(printTime, filamentUsed, filament=None): return round((printTime/60/60)*filament['price'])
def price(printTime, filamentUsed, filament=None): return round((printTime/60/60)*200)
Set constant price for all filaments
Set constant price for all filaments
Python
agpl-3.0
MakersLab/custom-print
python
## Code Before: def price(printTime, filamentUsed, filament=None): return round((printTime/60/60)*filament['price']) ## Instruction: Set constant price for all filaments ## Code After: def price(printTime, filamentUsed, filament=None): return round((printTime/60/60)*200)
... def price(printTime, filamentUsed, filament=None): return round((printTime/60/60)*200) ...
6de7d5059d6d5fd2569f108e83fff0ae979aad89
train_twitter_data.py
train_twitter_data.py
from sklearn.datasets import load_files from sklearn.feature_extraction.text import CountVectorizer categories = ['neg', 'pos'] twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42) count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(twitter_train.data) print(X_train_counts.shape)
from sklearn.datasets import load_files from sklearn.feature_extraction.text import CountVectorizer categories = ['neg', 'pos'] twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42) #Ignoring decode errors may harm our results, but at least it works now count_vect = CountVectorizer(decode_error='ignore') X_train_counts = count_vect.fit_transform(twitter_train.data) print(X_train_counts.shape)
Make vectorizer Ignore decode errors
Make vectorizer Ignore decode errors This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.
Python
apache-2.0
ngrudzinski/sentiment_analysis_437
python
## Code Before: from sklearn.datasets import load_files from sklearn.feature_extraction.text import CountVectorizer categories = ['neg', 'pos'] twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42) count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(twitter_train.data) print(X_train_counts.shape) ## Instruction: Make vectorizer Ignore decode errors This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible. ## Code After: from sklearn.datasets import load_files from sklearn.feature_extraction.text import CountVectorizer categories = ['neg', 'pos'] twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42) #Ignoring decode errors may harm our results, but at least it works now count_vect = CountVectorizer(decode_error='ignore') X_train_counts = count_vect.fit_transform(twitter_train.data) print(X_train_counts.shape)
# ... existing code ... twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42) #Ignoring decode errors may harm our results, but at least it works now count_vect = CountVectorizer(decode_error='ignore') X_train_counts = count_vect.fit_transform(twitter_train.data) print(X_train_counts.shape) # ... rest of the code ...
0e947377724bd32da28b1707a33c9d79b9f53386
javalin/src/main/java/io/javalin/http/sse/SseClient.kt
javalin/src/main/java/io/javalin/http/sse/SseClient.kt
package io.javalin.http.sse import io.javalin.http.Context import io.javalin.plugin.json.jsonMapper import java.io.Closeable import java.io.InputStream class SseClient internal constructor( private val closeSse: CloseSseFunction, @JvmField val ctx: Context ) : Closeable { private val emitter = Emitter(ctx.req.asyncContext) private var closeCallback = Runnable {} fun onClose(closeCallback: Runnable) { this.closeCallback = closeCallback } override fun close() = closeSse.close() fun sendEvent(data: Any) = sendEvent("message", data) @JvmOverloads fun sendEvent(event: String, data: Any, id: String? = null) { when (data) { is InputStream -> emitter.emit(event, data, id) is String -> emitter.emit(event, data.byteInputStream(), id) else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id) } if (emitter.isClosed()) { // can't detect if closed before we try emitting? closeCallback.run() } } fun sendComment(comment: String) { emitter.emit(comment) if (emitter.isClosed()) { closeCallback.run() } } }
package io.javalin.http.sse import io.javalin.http.Context import io.javalin.plugin.json.jsonMapper import java.io.Closeable import java.io.InputStream class SseClient internal constructor( private val closeSse: CloseSseFunction, @JvmField val ctx: Context ) : Closeable { private val emitter = Emitter(ctx.req.asyncContext) private var closeCallback = Runnable {} fun onClose(closeCallback: Runnable) { this.closeCallback = closeCallback } override fun close() { closeSse.close() closeCallback.run() } fun sendEvent(data: Any) = sendEvent("message", data) @JvmOverloads fun sendEvent(event: String, data: Any, id: String? = null) { when (data) { is InputStream -> emitter.emit(event, data, id) is String -> emitter.emit(event, data.byteInputStream(), id) else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id) } if (emitter.isClosed()) { // can't detect if closed before we try emitting? this.close() } } fun sendComment(comment: String) { emitter.emit(comment) if (emitter.isClosed()) { this.close() } } }
Make sure connection is closed properly
[sse] Make sure connection is closed properly
Kotlin
apache-2.0
tipsy/javalin,tipsy/javalin,tipsy/javalin,tipsy/javalin
kotlin
## Code Before: package io.javalin.http.sse import io.javalin.http.Context import io.javalin.plugin.json.jsonMapper import java.io.Closeable import java.io.InputStream class SseClient internal constructor( private val closeSse: CloseSseFunction, @JvmField val ctx: Context ) : Closeable { private val emitter = Emitter(ctx.req.asyncContext) private var closeCallback = Runnable {} fun onClose(closeCallback: Runnable) { this.closeCallback = closeCallback } override fun close() = closeSse.close() fun sendEvent(data: Any) = sendEvent("message", data) @JvmOverloads fun sendEvent(event: String, data: Any, id: String? = null) { when (data) { is InputStream -> emitter.emit(event, data, id) is String -> emitter.emit(event, data.byteInputStream(), id) else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id) } if (emitter.isClosed()) { // can't detect if closed before we try emitting? closeCallback.run() } } fun sendComment(comment: String) { emitter.emit(comment) if (emitter.isClosed()) { closeCallback.run() } } } ## Instruction: [sse] Make sure connection is closed properly ## Code After: package io.javalin.http.sse import io.javalin.http.Context import io.javalin.plugin.json.jsonMapper import java.io.Closeable import java.io.InputStream class SseClient internal constructor( private val closeSse: CloseSseFunction, @JvmField val ctx: Context ) : Closeable { private val emitter = Emitter(ctx.req.asyncContext) private var closeCallback = Runnable {} fun onClose(closeCallback: Runnable) { this.closeCallback = closeCallback } override fun close() { closeSse.close() closeCallback.run() } fun sendEvent(data: Any) = sendEvent("message", data) @JvmOverloads fun sendEvent(event: String, data: Any, id: String? = null) { when (data) { is InputStream -> emitter.emit(event, data, id) is String -> emitter.emit(event, data.byteInputStream(), id) else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id) } if (emitter.isClosed()) { // can't detect if closed before we try emitting? this.close() } } fun sendComment(comment: String) { emitter.emit(comment) if (emitter.isClosed()) { this.close() } } }
# ... existing code ... this.closeCallback = closeCallback } override fun close() { closeSse.close() closeCallback.run() } fun sendEvent(data: Any) = sendEvent("message", data) # ... modified code ... else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id) } if (emitter.isClosed()) { // can't detect if closed before we try emitting? this.close() } } ... fun sendComment(comment: String) { emitter.emit(comment) if (emitter.isClosed()) { this.close() } } # ... rest of the code ...
d4c8cfffb7f290bb6d8b7c973f75d9d103eb952d
src/main/java/in/ac/amu/zhcet/configuration/SentryConfiguration.java
src/main/java/in/ac/amu/zhcet/configuration/SentryConfiguration.java
package in.ac.amu.zhcet.configuration; import in.ac.amu.zhcet.data.model.user.UserAuth; import in.ac.amu.zhcet.service.UserService; import io.sentry.Sentry; import io.sentry.event.helper.EventBuilderHelper; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Slf4j @Component public class SentryConfiguration { @Data private static class User { private String userId; private String name; private String departmentName; private String email; private String[] roles; private String type; } @Autowired public SentryConfiguration(UserService userService, ModelMapper modelMapper) { EventBuilderHelper myEventBuilderHelper = eventBuilder -> { UserAuth loggedInUser = userService.getLoggedInUser(); if (loggedInUser != null) { eventBuilder.withExtra("user", modelMapper.map(loggedInUser, User.class)); } else { eventBuilder.withExtra("user", "UNAUTHORIZED"); } }; Sentry.getStoredClient().addBuilderHelper(myEventBuilderHelper); } }
package in.ac.amu.zhcet.configuration; import in.ac.amu.zhcet.data.model.user.UserAuth; import in.ac.amu.zhcet.service.UserService; import io.sentry.Sentry; import io.sentry.SentryClient; import io.sentry.event.helper.ContextBuilderHelper; import io.sentry.event.helper.EventBuilderHelper; import io.sentry.event.helper.ForwardedAddressResolver; import io.sentry.event.helper.HttpEventBuilderHelper; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Slf4j @Component public class SentryConfiguration { @Data private static class User { private String userId; private String name; private String departmentName; private String email; private String[] roles; private String type; } @Autowired public SentryConfiguration(UserService userService, ModelMapper modelMapper) { EventBuilderHelper myEventBuilderHelper = eventBuilder -> { UserAuth loggedInUser = userService.getLoggedInUser(); if (loggedInUser != null) { eventBuilder.withExtra("user", modelMapper.map(loggedInUser, User.class)); } else { eventBuilder.withExtra("user", "UNAUTHORIZED"); } }; SentryClient sentryClient = Sentry.getStoredClient(); sentryClient.addBuilderHelper(myEventBuilderHelper); sentryClient.addBuilderHelper(new HttpEventBuilderHelper(new ForwardedAddressResolver())); sentryClient.addBuilderHelper(new ContextBuilderHelper(sentryClient)); } }
Add forward address resolver to sentry
fix: Add forward address resolver to sentry
Java
apache-2.0
zhcet-amu/zhcet-web,zhcet-amu/zhcet-web,zhcet-amu/zhcet-web,zhcet-amu/zhcet-web,zhcet-amu/zhcet-web
java
## Code Before: package in.ac.amu.zhcet.configuration; import in.ac.amu.zhcet.data.model.user.UserAuth; import in.ac.amu.zhcet.service.UserService; import io.sentry.Sentry; import io.sentry.event.helper.EventBuilderHelper; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Slf4j @Component public class SentryConfiguration { @Data private static class User { private String userId; private String name; private String departmentName; private String email; private String[] roles; private String type; } @Autowired public SentryConfiguration(UserService userService, ModelMapper modelMapper) { EventBuilderHelper myEventBuilderHelper = eventBuilder -> { UserAuth loggedInUser = userService.getLoggedInUser(); if (loggedInUser != null) { eventBuilder.withExtra("user", modelMapper.map(loggedInUser, User.class)); } else { eventBuilder.withExtra("user", "UNAUTHORIZED"); } }; Sentry.getStoredClient().addBuilderHelper(myEventBuilderHelper); } } ## Instruction: fix: Add forward address resolver to sentry ## Code After: package in.ac.amu.zhcet.configuration; import in.ac.amu.zhcet.data.model.user.UserAuth; import in.ac.amu.zhcet.service.UserService; import io.sentry.Sentry; import io.sentry.SentryClient; import io.sentry.event.helper.ContextBuilderHelper; import io.sentry.event.helper.EventBuilderHelper; import io.sentry.event.helper.ForwardedAddressResolver; import io.sentry.event.helper.HttpEventBuilderHelper; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Slf4j @Component public class SentryConfiguration { @Data private static class User { private String userId; private String name; private String departmentName; private String email; private String[] roles; private String type; } @Autowired public SentryConfiguration(UserService userService, ModelMapper modelMapper) { EventBuilderHelper myEventBuilderHelper = eventBuilder -> { UserAuth loggedInUser = userService.getLoggedInUser(); if (loggedInUser != null) { eventBuilder.withExtra("user", modelMapper.map(loggedInUser, User.class)); } else { eventBuilder.withExtra("user", "UNAUTHORIZED"); } }; SentryClient sentryClient = Sentry.getStoredClient(); sentryClient.addBuilderHelper(myEventBuilderHelper); sentryClient.addBuilderHelper(new HttpEventBuilderHelper(new ForwardedAddressResolver())); sentryClient.addBuilderHelper(new ContextBuilderHelper(sentryClient)); } }
... import in.ac.amu.zhcet.data.model.user.UserAuth; import in.ac.amu.zhcet.service.UserService; import io.sentry.Sentry; import io.sentry.SentryClient; import io.sentry.event.helper.ContextBuilderHelper; import io.sentry.event.helper.EventBuilderHelper; import io.sentry.event.helper.ForwardedAddressResolver; import io.sentry.event.helper.HttpEventBuilderHelper; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; ... } }; SentryClient sentryClient = Sentry.getStoredClient(); sentryClient.addBuilderHelper(myEventBuilderHelper); sentryClient.addBuilderHelper(new HttpEventBuilderHelper(new ForwardedAddressResolver())); sentryClient.addBuilderHelper(new ContextBuilderHelper(sentryClient)); } } ...
5e47f95bcc147a9735083f32a15df362bb6dcacd
pcs/packets/__init__.py
pcs/packets/__init__.py
__revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $" all = ['ethernet', 'loopback', 'ipv4', 'ipv6', 'icmpv4', 'tcp', 'udp', 'data']
__revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $" all = ['ethernet', 'loopback', 'ipv4', 'ipv6', 'icmpv4', 'igmpv2', 'igmpv3', 'tcp', 'udp', 'data']
Connect IGMP to the build.
Connect IGMP to the build.
Python
bsd-3-clause
gvnn3/PCS,gvnn3/PCS
python
## Code Before: __revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $" all = ['ethernet', 'loopback', 'ipv4', 'ipv6', 'icmpv4', 'tcp', 'udp', 'data'] ## Instruction: Connect IGMP to the build. ## Code After: __revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $" all = ['ethernet', 'loopback', 'ipv4', 'ipv6', 'icmpv4', 'igmpv2', 'igmpv3', 'tcp', 'udp', 'data']
// ... existing code ... 'ipv4', 'ipv6', 'icmpv4', 'igmpv2', 'igmpv3', 'tcp', 'udp', 'data'] // ... rest of the code ...
0740d16b60a3ecc26e72c51ea85257b2c0d03d18
setup.py
setup.py
from __future__ import absolute_import from setuptools import setup long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg """ setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "[email protected]", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, use_scm_version=True, setup_requires=["setuptools_scm"], classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
from __future__ import absolute_import from setuptools import setup long_description="""http://github.com/nanonyme/simplepreprocessor""" setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "[email protected]", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, use_scm_version=True, setup_requires=["setuptools_scm"], classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
Make long description not point to Travis since can't guarantee tag
Make long description not point to Travis since can't guarantee tag
Python
mit
nanonyme/simplecpreprocessor
python
## Code Before: from __future__ import absolute_import from setuptools import setup long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg """ setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "[email protected]", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, use_scm_version=True, setup_requires=["setuptools_scm"], classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], ) ## Instruction: Make long description not point to Travis since can't guarantee tag ## Code After: from __future__ import absolute_import from setuptools import setup long_description="""http://github.com/nanonyme/simplepreprocessor""" setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "[email protected]", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, use_scm_version=True, setup_requires=["setuptools_scm"], classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
# ... existing code ... from __future__ import absolute_import from setuptools import setup long_description="""http://github.com/nanonyme/simplepreprocessor""" setup( name = "simplecpreprocessor", # ... rest of the code ...
2e8a1262e0168c973a3d195b6838ef9e80f5d43e
simple-rest-facade/src/main/java/de/tse/simplerestfacade/ResultConverterResponseHandler.java
simple-rest-facade/src/main/java/de/tse/simplerestfacade/ResultConverterResponseHandler.java
package de.tse.simplerestfacade; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import de.tse.simplerestfacade.marshalling.Unmarshaller; public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> { private final Unmarshaller unmarshaller; private final Class<T> returnType; public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) { this.unmarshaller = unmarshaller; this.returnType = returnType; } @Override public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { validateStatusCode(response); final String content = EntityUtils.toString(response.getEntity()); return unmarshaller.unmarshall(content, returnType); } private void validateStatusCode(final HttpResponse response) { final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new RestClientException(statusLine.toString()); } } }
package de.tse.simplerestfacade; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import de.tse.simplerestfacade.marshalling.Unmarshaller; public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> { private final Unmarshaller unmarshaller; private final Class<T> returnType; public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) { this.unmarshaller = unmarshaller; this.returnType = returnType; } @Override public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { validateStatusCode(response); Object result = null; if (response.getEntity() != null) { final String content = EntityUtils.toString(response.getEntity()); result = unmarshaller.unmarshall(content, returnType); } return result; } private void validateStatusCode(final HttpResponse response) { final StatusLine statusLine = response.getStatusLine(); if (!requestWasSuccessful(statusLine.getStatusCode())) { throw new RestClientException(statusLine.toString()); } } private boolean requestWasSuccessful(final int statusCode) { return statusCode >= HttpStatus.SC_OK || statusCode < HttpStatus.SC_MULTIPLE_CHOICES; } }
Throw Exception only if StatusCode is out of 2xx Range; Unmarshal Response only, if ResponseEntity exist.
Throw Exception only if StatusCode is out of 2xx Range; Unmarshal Response only, if ResponseEntity exist.
Java
mit
tinosteinort/simple-rest-facade
java
## Code Before: package de.tse.simplerestfacade; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import de.tse.simplerestfacade.marshalling.Unmarshaller; public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> { private final Unmarshaller unmarshaller; private final Class<T> returnType; public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) { this.unmarshaller = unmarshaller; this.returnType = returnType; } @Override public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { validateStatusCode(response); final String content = EntityUtils.toString(response.getEntity()); return unmarshaller.unmarshall(content, returnType); } private void validateStatusCode(final HttpResponse response) { final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new RestClientException(statusLine.toString()); } } } ## Instruction: Throw Exception only if StatusCode is out of 2xx Range; Unmarshal Response only, if ResponseEntity exist. ## Code After: package de.tse.simplerestfacade; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import de.tse.simplerestfacade.marshalling.Unmarshaller; public class ResultConverterResponseHandler<T> implements ResponseHandler<Object> { private final Unmarshaller unmarshaller; private final Class<T> returnType; public ResultConverterResponseHandler(final Unmarshaller unmarshaller, final Class<T> returnType) { this.unmarshaller = unmarshaller; this.returnType = returnType; } @Override public Object handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { validateStatusCode(response); Object result = null; if (response.getEntity() != null) { final String content = EntityUtils.toString(response.getEntity()); result = unmarshaller.unmarshall(content, returnType); } return result; } private void validateStatusCode(final HttpResponse response) { final StatusLine statusLine = response.getStatusLine(); if (!requestWasSuccessful(statusLine.getStatusCode())) { throw new RestClientException(statusLine.toString()); } } private boolean requestWasSuccessful(final int statusCode) { return statusCode >= HttpStatus.SC_OK || statusCode < HttpStatus.SC_MULTIPLE_CHOICES; } }
... validateStatusCode(response); Object result = null; if (response.getEntity() != null) { final String content = EntityUtils.toString(response.getEntity()); result = unmarshaller.unmarshall(content, returnType); } return result; } private void validateStatusCode(final HttpResponse response) { final StatusLine statusLine = response.getStatusLine(); if (!requestWasSuccessful(statusLine.getStatusCode())) { throw new RestClientException(statusLine.toString()); } } private boolean requestWasSuccessful(final int statusCode) { return statusCode >= HttpStatus.SC_OK || statusCode < HttpStatus.SC_MULTIPLE_CHOICES; } } ...
28a670a11f884e8aecf10276e0fe237c4fc878b5
common/src/main/java/io/fluxcapacitor/common/api/search/IndexDocuments.java
common/src/main/java/io/fluxcapacitor/common/api/search/IndexDocuments.java
/* * Copyright (c) 2016-2021 Flux Capacitor. * * 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 io.fluxcapacitor.common.api.search; import com.fasterxml.jackson.annotation.JsonIgnore; import io.fluxcapacitor.common.Guarantee; import io.fluxcapacitor.common.api.Request; import lombok.EqualsAndHashCode; import lombok.Value; import java.util.List; @EqualsAndHashCode(callSuper = true) @Value public class IndexDocuments extends Request { List<SerializedDocument> documents; boolean ifNotExists; Guarantee guarantee; @JsonIgnore public int getSize() { return documents.size(); } @Override public String toString() { return "IndexDocuments of length " + documents.size(); } @Override public Object toMetric() { return null; } }
/* * Copyright (c) 2016-2021 Flux Capacitor. * * 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 io.fluxcapacitor.common.api.search; import com.fasterxml.jackson.annotation.JsonIgnore; import io.fluxcapacitor.common.Guarantee; import io.fluxcapacitor.common.api.Request; import lombok.EqualsAndHashCode; import lombok.Value; import java.util.List; import java.util.stream.Collectors; @EqualsAndHashCode(callSuper = true) @Value public class IndexDocuments extends Request { List<SerializedDocument> documents; boolean ifNotExists; Guarantee guarantee; @JsonIgnore public int getSize() { return documents.size(); } @Override public String toString() { return "IndexDocuments of length " + documents.size(); } @Override public Metric toMetric() { return new Metric(getSize(), ifNotExists, guarantee, documents.stream().map(SerializedDocument::getId).collect(Collectors.toList())); } @Value public static class Metric { int size; boolean ifNotExists; Guarantee guarantee; List<String> ids; } }
Add metrics for indexing documents
Add metrics for indexing documents
Java
apache-2.0
flux-capacitor-io/flux-capacitor-client,flux-capacitor-io/flux-capacitor-client,flux-capacitor-io/flux-capacitor-client,flux-capacitor-io/flux-capacitor-client
java
## Code Before: /* * Copyright (c) 2016-2021 Flux Capacitor. * * 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 io.fluxcapacitor.common.api.search; import com.fasterxml.jackson.annotation.JsonIgnore; import io.fluxcapacitor.common.Guarantee; import io.fluxcapacitor.common.api.Request; import lombok.EqualsAndHashCode; import lombok.Value; import java.util.List; @EqualsAndHashCode(callSuper = true) @Value public class IndexDocuments extends Request { List<SerializedDocument> documents; boolean ifNotExists; Guarantee guarantee; @JsonIgnore public int getSize() { return documents.size(); } @Override public String toString() { return "IndexDocuments of length " + documents.size(); } @Override public Object toMetric() { return null; } } ## Instruction: Add metrics for indexing documents ## Code After: /* * Copyright (c) 2016-2021 Flux Capacitor. * * 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 io.fluxcapacitor.common.api.search; import com.fasterxml.jackson.annotation.JsonIgnore; import io.fluxcapacitor.common.Guarantee; import io.fluxcapacitor.common.api.Request; import lombok.EqualsAndHashCode; import lombok.Value; import java.util.List; import java.util.stream.Collectors; @EqualsAndHashCode(callSuper = true) @Value public class IndexDocuments extends Request { List<SerializedDocument> documents; boolean ifNotExists; Guarantee guarantee; @JsonIgnore public int getSize() { return documents.size(); } @Override public String toString() { return "IndexDocuments of length " + documents.size(); } @Override public Metric toMetric() { return new Metric(getSize(), ifNotExists, guarantee, documents.stream().map(SerializedDocument::getId).collect(Collectors.toList())); } @Value public static class Metric { int size; boolean ifNotExists; Guarantee guarantee; List<String> ids; } }
... import lombok.Value; import java.util.List; import java.util.stream.Collectors; @EqualsAndHashCode(callSuper = true) @Value ... } @Override public Metric toMetric() { return new Metric(getSize(), ifNotExists, guarantee, documents.stream().map(SerializedDocument::getId).collect(Collectors.toList())); } @Value public static class Metric { int size; boolean ifNotExists; Guarantee guarantee; List<String> ids; } } ...
f1e5e2cc7fd35e0446f105d619dc01d3ba837865
byceps/blueprints/admin/party/forms.py
byceps/blueprints/admin/party/forms.py
from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class UpdateForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) archived = BooleanField('archiviert') class CreateForm(UpdateForm): id = StringField('ID', validators=[Length(min=1, max=40)])
from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class _BaseForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) class CreateForm(_BaseForm): id = StringField('ID', validators=[Length(min=1, max=40)]) class UpdateForm(_BaseForm): archived = BooleanField('archiviert')
Introduce base party form, limit `archived` flag to update form
Introduce base party form, limit `archived` flag to update form
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps
python
## Code Before: from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class UpdateForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) archived = BooleanField('archiviert') class CreateForm(UpdateForm): id = StringField('ID', validators=[Length(min=1, max=40)]) ## Instruction: Introduce base party form, limit `archived` flag to update form ## Code After: from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class _BaseForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) class CreateForm(_BaseForm): id = StringField('ID', validators=[Length(min=1, max=40)]) class UpdateForm(_BaseForm): archived = BooleanField('archiviert')
... from ....util.l10n import LocalizedForm class _BaseForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) class CreateForm(_BaseForm): id = StringField('ID', validators=[Length(min=1, max=40)]) class UpdateForm(_BaseForm): archived = BooleanField('archiviert') ...
43fa842244da9d75496ba3ba02517870daca8849
provision/08-create-keystone-stuff.py
provision/08-create-keystone-stuff.py
import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open('json/create-idp.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('json/create-mapping.json') as fh: response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('json/create-protocol.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read()) response.raise_for_status()
import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open('/opt/himlar/json/create-idp.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-mapping.json') as fh: response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-protocol.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read()) response.raise_for_status()
Fix paths to json files
Fix paths to json files
Python
apache-2.0
norcams/himlar-connect,norcams/himlar-connect
python
## Code Before: import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open('json/create-idp.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('json/create-mapping.json') as fh: response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('json/create-protocol.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read()) response.raise_for_status() ## Instruction: Fix paths to json files ## Code After: import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open('/opt/himlar/json/create-idp.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-mapping.json') as fh: response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-protocol.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read()) response.raise_for_status()
# ... existing code ... 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open('/opt/himlar/json/create-idp.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-mapping.json') as fh: response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read()) response.raise_for_status() with open('/opt/himlar/json/create-protocol.json') as fh: response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read()) response.raise_for_status() # ... rest of the code ...
9fd4c69ac1dc4644c35687423dd4fe3e2f73fe63
mistral/tests/unit/engine/actions/test_fake_action.py
mistral/tests/unit/engine/actions/test_fake_action.py
from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_send_email_real(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected)
from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_fake_action(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected)
Correct fake action test name
Correct fake action test name Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9
Python
apache-2.0
openstack/mistral,StackStorm/mistral,TimurNurlygayanov/mistral,dennybaa/mistral,openstack/mistral,StackStorm/mistral,dennybaa/mistral
python
## Code Before: from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_send_email_real(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected) ## Instruction: Correct fake action test name Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9 ## Code After: from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_fake_action(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected)
// ... existing code ... from mistral.engine.actions import actions from mistral.engine.actions import action_types from mistral.tests import base class FakeActionTest(base.BaseTest): def test_fake_action(self): expected = "my output" action = actions.EchoAction(action_types.ECHO, "test", output=expected) self.assertEqual(action.run(), expected) // ... rest of the code ...
43434cc8efa52b56a64d52076b3760131456c34c
.bin/broadcast_any_song.py
.bin/broadcast_any_song.py
NC_HOST="gamma" NC_PORT=1234 CHANNEL=94.3 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT))
NC_HOST="gamma" NC_PORT=1234 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT))
Remove CHANNEL. Why is it even there?
Remove CHANNEL. Why is it even there?
Python
mit
ryanmjacobs/ryans_dotfiles,ryanmjacobs/ryans_dotfiles
python
## Code Before: NC_HOST="gamma" NC_PORT=1234 CHANNEL=94.3 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT)) ## Instruction: Remove CHANNEL. Why is it even there? ## Code After: NC_HOST="gamma" NC_PORT=1234 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT))
# ... existing code ... NC_HOST="gamma" NC_PORT=1234 import os # to execute shell commands import sys # arguments # ... rest of the code ...
8dad899d78f4b1c9473dad81998533d9c304f6e0
sample-kotlin/src/main/kotlin/com/hannesdorfmann/mosby/sample/kotlin/HeroesPresenter.kt
sample-kotlin/src/main/kotlin/com/hannesdorfmann/mosby/sample/kotlin/HeroesPresenter.kt
package com.hannesdorfmann.mosby.sample.kotlin import android.util.Log import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask /** * Presenter that loads list of heroes * * @author Hannes Dorfmann */ public class HeroesPresenter : MvpBasePresenter<HeroesView> () { val TAG = "HeroesPresenter" private var loaderTask: AsyncHeroesTask ? = null fun loadHeroes(pullToRefresh: Boolean) { Log.d(TAG, "loadHeroes({$pullToRefresh})") cancelIfRunning(); // Show Loading getView()?.showLoading(pullToRefresh) // execute loading loaderTask = AsyncHeroesTask( pullToRefresh, { heroes, pullToRefresh -> getView()?.setData(heroes) getView()?.showContent() }, { exception, pullToRefresh -> getView()?.showError(exception, pullToRefresh) } ) loaderTask?.execute() } fun cancelIfRunning() { // Cancel any previous one loaderTask?.cancel(true); } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) val builder = StringBuilder("detachView({$retainInstance})") if (!retainInstance) { cancelIfRunning() builder.append(" --> cancel async task") } Log.d(TAG, builder.toString()) } }
package com.hannesdorfmann.mosby.sample.kotlin import android.util.Log import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask /** * Presenter that loads list of heroes * * @author Hannes Dorfmann */ public class HeroesPresenter : MvpBasePresenter<HeroesView> () { val TAG = "HeroesPresenter" private var loaderTask: AsyncHeroesTask ? = null fun loadHeroes(pullToRefresh: Boolean) { Log.d(TAG, "loadHeroes({$pullToRefresh})") cancelIfRunning(); // Show Loading view?.showLoading(pullToRefresh) // execute loading loaderTask = AsyncHeroesTask( pullToRefresh, { heroes, pullToRefresh -> view?.setData(heroes) view?.showContent() }, { exception, pullToRefresh -> view?.showError(exception, pullToRefresh) } ) loaderTask?.execute() } fun cancelIfRunning() { // Cancel any previous one loaderTask?.cancel(true); } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) val builder = StringBuilder("detachView({$retainInstance})") if (!retainInstance) { cancelIfRunning() builder.append(" --> cancel async task") } Log.d(TAG, builder.toString()) } }
Use kotlin properties instead of getter method
Use kotlin properties instead of getter method
Kotlin
apache-2.0
vjames19/mosby,vjames19/mosby,lenguyenthanh/mosby,vjames19/mosby,sockeqwe/mosby,hanshou361248909/mosby,lenguyenthanh/mosby,sockeqwe/mosby,hanshou361248909/mosby
kotlin
## Code Before: package com.hannesdorfmann.mosby.sample.kotlin import android.util.Log import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask /** * Presenter that loads list of heroes * * @author Hannes Dorfmann */ public class HeroesPresenter : MvpBasePresenter<HeroesView> () { val TAG = "HeroesPresenter" private var loaderTask: AsyncHeroesTask ? = null fun loadHeroes(pullToRefresh: Boolean) { Log.d(TAG, "loadHeroes({$pullToRefresh})") cancelIfRunning(); // Show Loading getView()?.showLoading(pullToRefresh) // execute loading loaderTask = AsyncHeroesTask( pullToRefresh, { heroes, pullToRefresh -> getView()?.setData(heroes) getView()?.showContent() }, { exception, pullToRefresh -> getView()?.showError(exception, pullToRefresh) } ) loaderTask?.execute() } fun cancelIfRunning() { // Cancel any previous one loaderTask?.cancel(true); } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) val builder = StringBuilder("detachView({$retainInstance})") if (!retainInstance) { cancelIfRunning() builder.append(" --> cancel async task") } Log.d(TAG, builder.toString()) } } ## Instruction: Use kotlin properties instead of getter method ## Code After: package com.hannesdorfmann.mosby.sample.kotlin import android.util.Log import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask /** * Presenter that loads list of heroes * * @author Hannes Dorfmann */ public class HeroesPresenter : MvpBasePresenter<HeroesView> () { val TAG = "HeroesPresenter" private var loaderTask: AsyncHeroesTask ? = null fun loadHeroes(pullToRefresh: Boolean) { Log.d(TAG, "loadHeroes({$pullToRefresh})") cancelIfRunning(); // Show Loading view?.showLoading(pullToRefresh) // execute loading loaderTask = AsyncHeroesTask( pullToRefresh, { heroes, pullToRefresh -> view?.setData(heroes) view?.showContent() }, { exception, pullToRefresh -> view?.showError(exception, pullToRefresh) } ) loaderTask?.execute() } fun cancelIfRunning() { // Cancel any previous one loaderTask?.cancel(true); } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) val builder = StringBuilder("detachView({$retainInstance})") if (!retainInstance) { cancelIfRunning() builder.append(" --> cancel async task") } Log.d(TAG, builder.toString()) } }
... cancelIfRunning(); // Show Loading view?.showLoading(pullToRefresh) // execute loading loaderTask = AsyncHeroesTask( pullToRefresh, { heroes, pullToRefresh -> view?.setData(heroes) view?.showContent() }, { exception, pullToRefresh -> view?.showError(exception, pullToRefresh) } ) ...
cdaf1c4a9a99a7f089470e8ceaaa226124a42cf0
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print "Step3 of session %s" % session_time
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time))
Fix an example of python task
Fix an example of python task The original python print method doesn't work on python3. print(format) method works on python2 and python 3.
Python
apache-2.0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag
python
## Code Before: class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print "Step3 of session %s" % session_time ## Instruction: Fix an example of python task The original python print method doesn't work on python3. print(format) method works on python2 and python 3. ## Code After: class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time))
# ... existing code ... pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time)) # ... rest of the code ...
e69559b81e9b52eb0834df67b0197aa0f734db3c
wafer/talks/admin.py
wafer/talks/admin.py
from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') admin.site.register(Talk, TalkAdmin)
from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') list_editable = ('status',) admin.site.register(Talk, TalkAdmin)
Make talk status editale from the talk list overview
Make talk status editale from the talk list overview
Python
isc
CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer
python
## Code Before: from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') admin.site.register(Talk, TalkAdmin) ## Instruction: Make talk status editale from the talk list overview ## Code After: from django.contrib import admin from wafer.talks.models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') list_editable = ('status',) admin.site.register(Talk, TalkAdmin)
# ... existing code ... class TalkAdmin(admin.ModelAdmin): list_display = ('corresponding_author', 'title', 'status') list_editable = ('status',) admin.site.register(Talk, TalkAdmin) # ... rest of the code ...
316a6583036ca18cfdf1a95a122aa2367237fa2c
get/views.py
get/views.py
from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.all() context = {'links': list(links)} return render_to_response('get/listing.tpl', context)
from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.order_by('-pk') context = {'links': list(links)} return render_to_response('get/listing.tpl', context)
Order download links by pk.
get: Order download links by pk.
Python
bsd-3-clause
ProgVal/Supybot-website
python
## Code Before: from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.all() context = {'links': list(links)} return render_to_response('get/listing.tpl', context) ## Instruction: get: Order download links by pk. ## Code After: from django.shortcuts import render_to_response from django.shortcuts import redirect from models import DownloadLink def index(request): links = DownloadLink.objects.order_by('-pk') context = {'links': list(links)} return render_to_response('get/listing.tpl', context)
// ... existing code ... from models import DownloadLink def index(request): links = DownloadLink.objects.order_by('-pk') context = {'links': list(links)} return render_to_response('get/listing.tpl', context) // ... rest of the code ...
f4c5bb0a77108f340533736c52f01c861146a6b6
byceps/util/money.py
byceps/util/money.py
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
python
## Code Before: from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) ## Instruction: Remove usage of `monetary` keyword argument again as it is not available on Python 3.6 ## Code After: from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
# ... existing code ... symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True) return f'{formatted_number} €' # ... rest of the code ...
33f2636e1de536a633cec9332362252b0b614817
serpent/templates/SerpentGamePlugin/files/serpent_game.py
serpent/templates/SerpentGamePlugin/files/serpent_game.py
from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.input_controller import InputControllers from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["input_controller"] = InputControllers.PYAUTOGUI kwargs["window_name"] = "WINDOW_NAME" kwargs["app_id"] = "APP_ID" kwargs["app_args"] = None kwargs["executable_path"] = "EXECUTABLE_PATH" kwargs["url"] = "URL" kwargs["browser"] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { "SAMPLE_REGION": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { "SAMPLE_PRESET": { "extract": { "gradient_size": 1, "closing_size": 1 }, "perform": { "scale": 10, "order": 1, "horizontal_closing": 1, "vertical_closing": 1 } } } return presets
from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["window_name"] = "WINDOW_NAME" kwargs["app_id"] = "APP_ID" kwargs["app_args"] = None kwargs["executable_path"] = "EXECUTABLE_PATH" kwargs["url"] = "URL" kwargs["browser"] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { "SAMPLE_REGION": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { "SAMPLE_PRESET": { "extract": { "gradient_size": 1, "closing_size": 1 }, "perform": { "scale": 10, "order": 1, "horizontal_closing": 1, "vertical_closing": 1 } } } return presets
Remove kwargs["input_controller"] from the Game plugin template
Remove kwargs["input_controller"] from the Game plugin template
Python
mit
SerpentAI/SerpentAI
python
## Code Before: from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.input_controller import InputControllers from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["input_controller"] = InputControllers.PYAUTOGUI kwargs["window_name"] = "WINDOW_NAME" kwargs["app_id"] = "APP_ID" kwargs["app_args"] = None kwargs["executable_path"] = "EXECUTABLE_PATH" kwargs["url"] = "URL" kwargs["browser"] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { "SAMPLE_REGION": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { "SAMPLE_PRESET": { "extract": { "gradient_size": 1, "closing_size": 1 }, "perform": { "scale": 10, "order": 1, "horizontal_closing": 1, "vertical_closing": 1 } } } return presets ## Instruction: Remove kwargs["input_controller"] from the Game plugin template ## Code After: from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["window_name"] = "WINDOW_NAME" kwargs["app_id"] = "APP_ID" kwargs["app_args"] = None kwargs["executable_path"] = "EXECUTABLE_PATH" kwargs["url"] = "URL" kwargs["browser"] = WebBrowser.DEFAULT super().__init__(**kwargs) self.api_class = MyGameAPI self.api_instance = None @property def screen_regions(self): regions = { "SAMPLE_REGION": (0, 0, 0, 0) } return regions @property def ocr_presets(self): presets = { "SAMPLE_PRESET": { "extract": { "gradient_size": 1, "closing_size": 1 }, "perform": { "scale": 10, "order": 1, "horizontal_closing": 1, "vertical_closing": 1 } } } return presets
... from serpent.utilities import Singleton from serpent.game_launchers.web_browser_game_launcher import WebBrowser ... def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["window_name"] = "WINDOW_NAME" ...
61c53b5c19cbe54179b018f885622a2878718251
src/main/java/digital/loom/rhizome/authentication/CookieReadingAuth0AuthenticationFilter.java
src/main/java/digital/loom/rhizome/authentication/CookieReadingAuth0AuthenticationFilter.java
package digital.loom.rhizome.authentication; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils; import com.auth0.spring.security.api.Auth0AuthenticationFilter; import com.google.common.base.MoreObjects; public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter { @Override protected String getToken( HttpServletRequest httpRequest ) { String authorizationCookie = null; Cookie[] cookies = httpRequest.getCookies(); if ( cookies != null ) { for ( Cookie cookie : httpRequest.getCookies() ) { if ( StringUtils.equals( cookie.getName(), "authorization" ) ) { authorizationCookie = cookie.getValue(); break; } } } final String authorizationHeader = httpRequest.getHeader( "authorization" ); final String[] parts = MoreObjects.firstNonNull( authorizationHeader, authorizationCookie ).split( " " ); if ( parts.length != 2 ) { // "Unauthorized: Format is Authorization: Bearer [token]" return null; } final String scheme = parts[ 0 ]; final String credentials = parts[ 1 ]; final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE ); return pattern.matcher( scheme ).matches() ? credentials : null; } }
package digital.loom.rhizome.authentication; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils; import com.auth0.spring.security.api.Auth0AuthenticationFilter; import com.google.common.base.MoreObjects; public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter { @Override protected String getToken( HttpServletRequest httpRequest ) { String authorizationCookie = null; Cookie[] cookies = httpRequest.getCookies(); if ( cookies != null ) { for ( Cookie cookie : httpRequest.getCookies() ) { if ( StringUtils.equals( cookie.getName(), "authorization" ) ) { authorizationCookie = cookie.getValue(); break; } } } final String authorizationInfo = MoreObjects.firstNonNull( httpRequest.getHeader( "authorization" ), authorizationCookie ); if( authorizationInfo == null ) { return null; } final String[] parts = authorizationInfo.split( " " ); if ( parts.length != 2 ) { // "Unauthorized: Format is Authorization: Bearer [token]" return null; } final String scheme = parts[ 0 ]; final String credentials = parts[ 1 ]; final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE ); return pattern.matcher( scheme ).matches() ? credentials : null; } }
Fix NPE if no auth info provided
Fix NPE if no auth info provided
Java
apache-2.0
kryptnostic/rhizome,kryptnostic/rhizome
java
## Code Before: package digital.loom.rhizome.authentication; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils; import com.auth0.spring.security.api.Auth0AuthenticationFilter; import com.google.common.base.MoreObjects; public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter { @Override protected String getToken( HttpServletRequest httpRequest ) { String authorizationCookie = null; Cookie[] cookies = httpRequest.getCookies(); if ( cookies != null ) { for ( Cookie cookie : httpRequest.getCookies() ) { if ( StringUtils.equals( cookie.getName(), "authorization" ) ) { authorizationCookie = cookie.getValue(); break; } } } final String authorizationHeader = httpRequest.getHeader( "authorization" ); final String[] parts = MoreObjects.firstNonNull( authorizationHeader, authorizationCookie ).split( " " ); if ( parts.length != 2 ) { // "Unauthorized: Format is Authorization: Bearer [token]" return null; } final String scheme = parts[ 0 ]; final String credentials = parts[ 1 ]; final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE ); return pattern.matcher( scheme ).matches() ? credentials : null; } } ## Instruction: Fix NPE if no auth info provided ## Code After: package digital.loom.rhizome.authentication; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils; import com.auth0.spring.security.api.Auth0AuthenticationFilter; import com.google.common.base.MoreObjects; public class CookieReadingAuth0AuthenticationFilter extends Auth0AuthenticationFilter { @Override protected String getToken( HttpServletRequest httpRequest ) { String authorizationCookie = null; Cookie[] cookies = httpRequest.getCookies(); if ( cookies != null ) { for ( Cookie cookie : httpRequest.getCookies() ) { if ( StringUtils.equals( cookie.getName(), "authorization" ) ) { authorizationCookie = cookie.getValue(); break; } } } final String authorizationInfo = MoreObjects.firstNonNull( httpRequest.getHeader( "authorization" ), authorizationCookie ); if( authorizationInfo == null ) { return null; } final String[] parts = authorizationInfo.split( " " ); if ( parts.length != 2 ) { // "Unauthorized: Format is Authorization: Bearer [token]" return null; } final String scheme = parts[ 0 ]; final String credentials = parts[ 1 ]; final Pattern pattern = Pattern.compile( "^Bearer$", Pattern.CASE_INSENSITIVE ); return pattern.matcher( scheme ).matches() ? credentials : null; } }
// ... existing code ... } } final String authorizationInfo = MoreObjects.firstNonNull( httpRequest.getHeader( "authorization" ), authorizationCookie ); if( authorizationInfo == null ) { return null; } final String[] parts = authorizationInfo.split( " " ); if ( parts.length != 2 ) { // "Unauthorized: Format is Authorization: Bearer [token]" return null; // ... rest of the code ...
caee45194ec668e0c15c9cc9dd35e498b3ce7f93
src/master/main.c
src/master/main.c
int main(int argc, char *argv[]) { int socket_fd; config_t *config; if (argc < 5) { usage(); return 0; } /* Error on processing arguments */ if ((config = process_args(argc, argv)) == NULL) return 1; socket_fd = create_client_socket(IP, MULTI_PORT); if (socket_fd < 0) return 1; send_file(socket_fd, config->file->input_file); printf("File sent waiting for response\n"); recv_file(socket_fd, config->file->output_file); destroy_config(&config); close(socket_fd); return 0; }
int main(int argc, char *argv[]) { int socket_fd; config_t *config; if (argc < 5) { usage(); return 0; } /* Error on processing arguments */ if ((config = process_args(argc, argv)) == NULL) return 1; socket_fd = create_client_socket(IP, MULTI_PORT); if (socket_fd < 0) return 1; printf("Preprocessing file %s\n", config->file->input_file); preprocess(config->file); printf("Preprocessing done\n"); printf("Sending file to server for compilation\n"); send_file(socket_fd, config->file->output_file); printf("File sent waiting for response\n"); recv_file(socket_fd, config->file->output_file); printf("File received\n"); destroy_config(&config); close(socket_fd); return 0; }
Add correct work of client
Add correct work of client
C
mit
Nakrez/multi
c
## Code Before: int main(int argc, char *argv[]) { int socket_fd; config_t *config; if (argc < 5) { usage(); return 0; } /* Error on processing arguments */ if ((config = process_args(argc, argv)) == NULL) return 1; socket_fd = create_client_socket(IP, MULTI_PORT); if (socket_fd < 0) return 1; send_file(socket_fd, config->file->input_file); printf("File sent waiting for response\n"); recv_file(socket_fd, config->file->output_file); destroy_config(&config); close(socket_fd); return 0; } ## Instruction: Add correct work of client ## Code After: int main(int argc, char *argv[]) { int socket_fd; config_t *config; if (argc < 5) { usage(); return 0; } /* Error on processing arguments */ if ((config = process_args(argc, argv)) == NULL) return 1; socket_fd = create_client_socket(IP, MULTI_PORT); if (socket_fd < 0) return 1; printf("Preprocessing file %s\n", config->file->input_file); preprocess(config->file); printf("Preprocessing done\n"); printf("Sending file to server for compilation\n"); send_file(socket_fd, config->file->output_file); printf("File sent waiting for response\n"); recv_file(socket_fd, config->file->output_file); printf("File received\n"); destroy_config(&config); close(socket_fd); return 0; }
// ... existing code ... if (socket_fd < 0) return 1; printf("Preprocessing file %s\n", config->file->input_file); preprocess(config->file); printf("Preprocessing done\n"); printf("Sending file to server for compilation\n"); send_file(socket_fd, config->file->output_file); printf("File sent waiting for response\n"); recv_file(socket_fd, config->file->output_file); printf("File received\n"); destroy_config(&config); close(socket_fd); // ... rest of the code ...
a3907d35c690fdbba46e1dde49c9a8d8b39a6823
org.eclipse.dawnsci.plotting.api/src/org/eclipse/dawnsci/plotting/api/trace/ICompositeTrace.java
org.eclipse.dawnsci.plotting.api/src/org/eclipse/dawnsci/plotting/api/trace/ICompositeTrace.java
package org.eclipse.dawnsci.plotting.api.trace; import java.util.List; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; /** * A trace for adding together multiple other traces and plotting * them as if they were images. * * The initial version is for multiple IImageTrace but future versions * might include an IImageTrace covered by a vector trace. * * @author Matthew Gerring * */ public interface ICompositeTrace extends ITrace { /** * Add a subimage to the stacked image trace. The name of the * image must be unique inside the IStackedImageTrace * * @param index or -1 to simply add the image on to the end. * @param image */ public void add(ITrace image, int index) throws IllegalArgumentException; /** * Add a subimage to the stacked image trace. * @param image * @param axes */ public void removeImage(String name); /** * @return the axes which enclose all data */ public List<IDataset> getAxes(); }
package org.eclipse.dawnsci.plotting.api.trace; import java.util.List; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; /** * A trace for adding together multiple other traces and plotting * them as if they were images. * * The initial version is for multiple IImageTrace but future versions * might include an IImageTrace covered by a vector trace. * * @author Matthew Gerring * */ public interface ICompositeTrace extends ITrace { /** * Add a subimage to the stacked image trace. The name of the * image must be unique inside the IStackedImageTrace * * @param index or -1 to simply add the image on to the end. * @param image */ public void add(ITrace image, int index) throws IllegalArgumentException; /** * Add a subimage to the stacked image trace. * @param image * @param axes */ public void removeImage(String name); /** * @return the axes which enclose all data */ public List<IDataset> getAxes(); /** * Set the colormap for the non-rgb datasets in the composite * * @param name */ public void setPalette(String name); }
Change palette in composite trace
Change palette in composite trace
Java
epl-1.0
willrogers/dawnsci,jamesmudd/dawnsci,colinpalmer/dawnsci,willrogers/dawnsci,DawnScience/dawnsci,jonahkichwacoders/dawnsci,eclipse/dawnsci,belkassaby/dawnsci,jamesmudd/dawnsci,Anthchirp/dawnsci,PeterC-DLS/org.eclipse.dataset,jamesmudd/dawnsci,PeterC-DLS/org.eclipse.dataset,xen-0/dawnsci,colinpalmer/dawnsci,jonahkichwacoders/dawnsci,Anthchirp/dawnsci
java
## Code Before: package org.eclipse.dawnsci.plotting.api.trace; import java.util.List; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; /** * A trace for adding together multiple other traces and plotting * them as if they were images. * * The initial version is for multiple IImageTrace but future versions * might include an IImageTrace covered by a vector trace. * * @author Matthew Gerring * */ public interface ICompositeTrace extends ITrace { /** * Add a subimage to the stacked image trace. The name of the * image must be unique inside the IStackedImageTrace * * @param index or -1 to simply add the image on to the end. * @param image */ public void add(ITrace image, int index) throws IllegalArgumentException; /** * Add a subimage to the stacked image trace. * @param image * @param axes */ public void removeImage(String name); /** * @return the axes which enclose all data */ public List<IDataset> getAxes(); } ## Instruction: Change palette in composite trace ## Code After: package org.eclipse.dawnsci.plotting.api.trace; import java.util.List; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; /** * A trace for adding together multiple other traces and plotting * them as if they were images. * * The initial version is for multiple IImageTrace but future versions * might include an IImageTrace covered by a vector trace. * * @author Matthew Gerring * */ public interface ICompositeTrace extends ITrace { /** * Add a subimage to the stacked image trace. The name of the * image must be unique inside the IStackedImageTrace * * @param index or -1 to simply add the image on to the end. * @param image */ public void add(ITrace image, int index) throws IllegalArgumentException; /** * Add a subimage to the stacked image trace. * @param image * @param axes */ public void removeImage(String name); /** * @return the axes which enclose all data */ public List<IDataset> getAxes(); /** * Set the colormap for the non-rgb datasets in the composite * * @param name */ public void setPalette(String name); }
... * @return the axes which enclose all data */ public List<IDataset> getAxes(); /** * Set the colormap for the non-rgb datasets in the composite * * @param name */ public void setPalette(String name); } ...
556545432af2b6d7d2c04e97fb86be308069d03a
plugins/backtothefuture.py
plugins/backtothefuture.py
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
Fix some bugs with date parsing, as well as zero pad month and day in URL
Fix some bugs with date parsing, as well as zero pad month and day in URL
Python
mit
akatrevorjay/slask,kesre/slask,joshshadowfax/slask
python
## Code Before: """!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0]) ## Instruction: Fix some bugs with date parsing, as well as zero pad month and day in URL ## Code After: """!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
... """!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): ...
d8e5dce3489817a5065c045688b03f9e85c0b9a4
tests/data_structures/commons/binary_search_tree_unit_test.py
tests/data_structures/commons/binary_search_tree_unit_test.py
import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) if __name__ == '__main__': unittest.main()
import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': unittest.main()
Increase the unit test coverage for the binary search tree
Increase the unit test coverage for the binary search tree
Python
bsd-3-clause
chen0040/pyalgs
python
## Code Before: import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) if __name__ == '__main__': unittest.main() ## Instruction: Increase the unit test coverage for the binary search tree ## Code After: import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': unittest.main()
// ... existing code ... bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) // ... modified code ... self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': unittest.main() // ... rest of the code ...
ba00043836754b981edc79ae42859493938dc92e
droidbox/src/main/java/com/github/jackparisi/droidbox/utility/ScreenUtils.kt
droidbox/src/main/java/com/github/jackparisi/droidbox/utility/ScreenUtils.kt
package com.github.jackparisi.droidbox.utility import android.content.Context import android.util.TypedValue /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ fun dpToPx(dp: Float, context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics)
package com.github.jackparisi.droidbox.utility import android.content.Context import android.util.TypedValue /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ /** * * Convert the float value for dp to pixel * * @param dp The value in dp * @param context The context object for access to displayMetrics * @return The converted value in pixels */ fun dpToPx(dp: Float, context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics)
Add docs for screen utils
Add docs for screen utils
Kotlin
apache-2.0
JackParisi/DroidBox
kotlin
## Code Before: package com.github.jackparisi.droidbox.utility import android.content.Context import android.util.TypedValue /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ fun dpToPx(dp: Float, context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics) ## Instruction: Add docs for screen utils ## Code After: package com.github.jackparisi.droidbox.utility import android.content.Context import android.util.TypedValue /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ /** * * Convert the float value for dp to pixel * * @param dp The value in dp * @param context The context object for access to displayMetrics * @return The converted value in pixels */ fun dpToPx(dp: Float, context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics)
... * https://github.com/JackParisi */ /** * * Convert the float value for dp to pixel * * @param dp The value in dp * @param context The context object for access to displayMetrics * @return The converted value in pixels */ fun dpToPx(dp: Float, context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics) ...
01a8fcb70ea75d854aaf16547b837d861750c160
tilequeue/queue/file.py
tilequeue/queue/file.py
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
Use readline() instead of next() to detect changes.
Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.
Python
mit
tilezen/tilequeue,mapzen/tilequeue
python
## Code Before: from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() ## Instruction: Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart. ## Code After: from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
... with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords ... def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() ...
ee28fdc66fbb0f91821ff18ff219791bf5de8f4d
corehq/apps/fixtures/tasks.py
corehq/apps/fixtures/tasks.py
from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
Change fixture upload task to json serializer
Change fixture upload task to json serializer
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
python
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100) ## Instruction: Change fixture upload task to json serializer ## Code After: from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
# ... existing code ... from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) # ... rest of the code ...
b60f9f22703d97cfaeaa69e36fe283d1ef5d2f5d
download_data.py
download_data.py
import bz2 import urllib.request OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = urllib.request.urlopen(url) decompressor = bz2.BZ2Decompressor() with open(dest_file, 'wb') as dest_file: while True: data = source.read(CHUNK) if not data: break dest_file.write(decompressor.decompress(data)) if __name__ == '__main__': download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
import bz2 import urllib.request import os import os.path DATA_DIR = 'data' OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = urllib.request.urlopen(url) decompressor = bz2.BZ2Decompressor() with open(dest_file, 'wb') as dest_file: while True: data = source.read(CHUNK) if not data: break dest_file.write(decompressor.decompress(data)) if __name__ == '__main__': if not os.path.isdir(DATA_DIR): os.mkdir(DATA_DIR) download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
Create dir before data downloading
Create dir before data downloading
Python
mit
Nizametdinov/cnn-pos-tagger
python
## Code Before: import bz2 import urllib.request OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = urllib.request.urlopen(url) decompressor = bz2.BZ2Decompressor() with open(dest_file, 'wb') as dest_file: while True: data = source.read(CHUNK) if not data: break dest_file.write(decompressor.decompress(data)) if __name__ == '__main__': download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE) ## Instruction: Create dir before data downloading ## Code After: import bz2 import urllib.request import os import os.path DATA_DIR = 'data' OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = urllib.request.urlopen(url) decompressor = bz2.BZ2Decompressor() with open(dest_file, 'wb') as dest_file: while True: data = source.read(CHUNK) if not data: break dest_file.write(decompressor.decompress(data)) if __name__ == '__main__': if not os.path.isdir(DATA_DIR): os.mkdir(DATA_DIR) download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
# ... existing code ... import bz2 import urllib.request import os import os.path DATA_DIR = 'data' OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 # ... modified code ... if __name__ == '__main__': if not os.path.isdir(DATA_DIR): os.mkdir(DATA_DIR) download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE) # ... rest of the code ...
a294ea80e95e8469031997ad40fbb3fa5e5eb658
security-utils/src/main/java/com/yahoo/security/tls/MixedMode.java
security-utils/src/main/java/com/yahoo/security/tls/MixedMode.java
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.security.tls; import java.util.Arrays; /** * @author bjorncs */ public enum MixedMode { PLAINTEXT_CLIENT_MIXED_SERVER("plaintext_client_mixed_server"), TLS_CLIENT_MIXED_SERVER("tls_client_mixed_server"); final String configValue; MixedMode(String configValue) { this.configValue = configValue; } public String configValue() { return configValue; } static MixedMode fromConfigValue(String configValue) { return Arrays.stream(values()) .filter(v -> v.configValue.equals(configValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue)); } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.security.tls; import java.util.Arrays; /** * @author bjorncs */ public enum MixedMode { PLAINTEXT_CLIENT_MIXED_SERVER("plaintext_client_mixed_server"), TLS_CLIENT_MIXED_SERVER("tls_client_mixed_server"), DISABLED("tls_client_tls_server"); final String configValue; MixedMode(String configValue) { this.configValue = configValue; } public String configValue() { return configValue; } /** * @return Default value when mixed mode is not explicitly specified */ public static MixedMode defaultValue() { return DISABLED; } static MixedMode fromConfigValue(String configValue) { return Arrays.stream(values()) .filter(v -> v.configValue.equals(configValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue)); } }
Add 'tls_client_tls_server' as tls mixed mode option
Add 'tls_client_tls_server' as tls mixed mode option Also introduce default value for mixed mode.
Java
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
java
## Code Before: // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.security.tls; import java.util.Arrays; /** * @author bjorncs */ public enum MixedMode { PLAINTEXT_CLIENT_MIXED_SERVER("plaintext_client_mixed_server"), TLS_CLIENT_MIXED_SERVER("tls_client_mixed_server"); final String configValue; MixedMode(String configValue) { this.configValue = configValue; } public String configValue() { return configValue; } static MixedMode fromConfigValue(String configValue) { return Arrays.stream(values()) .filter(v -> v.configValue.equals(configValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue)); } } ## Instruction: Add 'tls_client_tls_server' as tls mixed mode option Also introduce default value for mixed mode. ## Code After: // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.security.tls; import java.util.Arrays; /** * @author bjorncs */ public enum MixedMode { PLAINTEXT_CLIENT_MIXED_SERVER("plaintext_client_mixed_server"), TLS_CLIENT_MIXED_SERVER("tls_client_mixed_server"), DISABLED("tls_client_tls_server"); final String configValue; MixedMode(String configValue) { this.configValue = configValue; } public String configValue() { return configValue; } /** * @return Default value when mixed mode is not explicitly specified */ public static MixedMode defaultValue() { return DISABLED; } static MixedMode fromConfigValue(String configValue) { return Arrays.stream(values()) .filter(v -> v.configValue.equals(configValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue)); } }
# ... existing code ... */ public enum MixedMode { PLAINTEXT_CLIENT_MIXED_SERVER("plaintext_client_mixed_server"), TLS_CLIENT_MIXED_SERVER("tls_client_mixed_server"), DISABLED("tls_client_tls_server"); final String configValue; # ... modified code ... return configValue; } /** * @return Default value when mixed mode is not explicitly specified */ public static MixedMode defaultValue() { return DISABLED; } static MixedMode fromConfigValue(String configValue) { return Arrays.stream(values()) .filter(v -> v.configValue.equals(configValue)) # ... rest of the code ...
d07109e07e4d9fab488dfbbcf56fdfe18baa56ab
lib/python/plow/test/test_static.py
lib/python/plow/test/test_static.py
import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.findJobs() if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests) unittest.TextTestRunner(verbosity=2).run(suite)
import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.getJobs() def testGetGroupedJobs(self): result = [ {"id": 1, "parent":0, "name": "High"}, {"id": 2, "parent":1, "name": "Foo"} ] for p in result: print p if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests) unittest.TextTestRunner(verbosity=2).run(suite)
Set the column count value based on size of header list.
Set the column count value based on size of header list.
Python
apache-2.0
Br3nda/plow,Br3nda/plow,chadmv/plow,Br3nda/plow,chadmv/plow,chadmv/plow,Br3nda/plow,Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow
python
## Code Before: import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.findJobs() if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests) unittest.TextTestRunner(verbosity=2).run(suite) ## Instruction: Set the column count value based on size of header list. ## Code After: import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.getJobs() def testGetGroupedJobs(self): result = [ {"id": 1, "parent":0, "name": "High"}, {"id": 2, "parent":1, "name": "Foo"} ] for p in result: print p if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests) unittest.TextTestRunner(verbosity=2).run(suite)
# ... existing code ... class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.getJobs() def testGetGroupedJobs(self): result = [ {"id": 1, "parent":0, "name": "High"}, {"id": 2, "parent":1, "name": "Foo"} ] for p in result: print p if __name__ == "__main__": # ... rest of the code ...
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565
interrupt.py
interrupt.py
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
Handle sigterm as well as sigint.
Handle sigterm as well as sigint.
Python
mit
rickbassham/videoencode,rickbassham/videoencode
python
## Code Before: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e ## Instruction: Handle sigterm as well as sigint. ## Code After: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
# ... existing code ... e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e # ... rest of the code ...
e4fcebfe4e87b57ae8505437f54c69f3afd59c04
python/tests.py
python/tests.py
import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """ Function for testing that the opacity is fetched correctly. """ # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test()
import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """ Function for testing that the opacity is fetched correctly. """ # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column rho /= 1.e3; rho *= 1./1e6 # Convert to SI units [kg m^-3] ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test()
Fix test to take care of units.
TODO: Fix test to take care of units.
Python
mit
PaulMag/AST3310-Prj01,PaulMag/AST3310-Prj01
python
## Code Before: import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """ Function for testing that the opacity is fetched correctly. """ # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test() ## Instruction: TODO: Fix test to take care of units. ## Code After: import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """ Function for testing that the opacity is fetched correctly. """ # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column rho /= 1.e3; rho *= 1./1e6 # Convert to SI units [kg m^-3] ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test()
# ... existing code ... # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column rho /= 1.e3; rho *= 1./1e6 # Convert to SI units [kg m^-3] ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: # ... rest of the code ...
4ec6dde3a662778f898375bdda879904509ad33d
src/NavRouting/SdkModel/NavRoutingLocationFinder.h
src/NavRouting/SdkModel/NavRoutingLocationFinder.h
namespace ExampleApp { namespace NavRouting { namespace SdkModel { class NavRoutingLocationFinder : public INavRoutingLocationFinder { private: Eegeo::Location::ILocationService& m_locationService; Eegeo::Resources::Interiors::InteriorsModelRepository& m_interiorsModelRepository; Eegeo::UI::NativeAlerts::IAlertBoxFactory& m_alertBoxFactory; Eegeo::UI::NativeAlerts::TSingleOptionAlertBoxDismissedHandler<NavRoutingLocationFinder> m_failAlertHandler; void OnFailAlertBoxDismissed(); public: NavRoutingLocationFinder( Eegeo::Location::ILocationService& locationService, Eegeo::Resources::Interiors::InteriorsModelRepository& interiorsModelRepository, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory); bool TryGetCurrentLocation(NavRoutingLocationModel &outLocation); bool TryGetLocationFromSearchResultModel( const Search::SdkModel::SearchResultModel& searchResultModel, NavRoutingLocationModel &outLocation); }; } } }
namespace ExampleApp { namespace NavRouting { namespace SdkModel { class NavRoutingLocationFinder : public INavRoutingLocationFinder, private Eegeo::NonCopyable { private: Eegeo::Location::ILocationService& m_locationService; Eegeo::Resources::Interiors::InteriorsModelRepository& m_interiorsModelRepository; Eegeo::UI::NativeAlerts::IAlertBoxFactory& m_alertBoxFactory; Eegeo::UI::NativeAlerts::TSingleOptionAlertBoxDismissedHandler<NavRoutingLocationFinder> m_failAlertHandler; void OnFailAlertBoxDismissed(); public: NavRoutingLocationFinder( Eegeo::Location::ILocationService& locationService, Eegeo::Resources::Interiors::InteriorsModelRepository& interiorsModelRepository, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory); virtual ~NavRoutingLocationFinder() {}; bool TryGetCurrentLocation(NavRoutingLocationModel &outLocation); bool TryGetLocationFromSearchResultModel( const Search::SdkModel::SearchResultModel& searchResultModel, NavRoutingLocationModel &outLocation); }; } } }
Fix missing virtual dtor on new type Buddy Michael Chan
Fix missing virtual dtor on new type Buddy Michael Chan
C
bsd-2-clause
eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app
c
## Code Before: namespace ExampleApp { namespace NavRouting { namespace SdkModel { class NavRoutingLocationFinder : public INavRoutingLocationFinder { private: Eegeo::Location::ILocationService& m_locationService; Eegeo::Resources::Interiors::InteriorsModelRepository& m_interiorsModelRepository; Eegeo::UI::NativeAlerts::IAlertBoxFactory& m_alertBoxFactory; Eegeo::UI::NativeAlerts::TSingleOptionAlertBoxDismissedHandler<NavRoutingLocationFinder> m_failAlertHandler; void OnFailAlertBoxDismissed(); public: NavRoutingLocationFinder( Eegeo::Location::ILocationService& locationService, Eegeo::Resources::Interiors::InteriorsModelRepository& interiorsModelRepository, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory); bool TryGetCurrentLocation(NavRoutingLocationModel &outLocation); bool TryGetLocationFromSearchResultModel( const Search::SdkModel::SearchResultModel& searchResultModel, NavRoutingLocationModel &outLocation); }; } } } ## Instruction: Fix missing virtual dtor on new type Buddy Michael Chan ## Code After: namespace ExampleApp { namespace NavRouting { namespace SdkModel { class NavRoutingLocationFinder : public INavRoutingLocationFinder, private Eegeo::NonCopyable { private: Eegeo::Location::ILocationService& m_locationService; Eegeo::Resources::Interiors::InteriorsModelRepository& m_interiorsModelRepository; Eegeo::UI::NativeAlerts::IAlertBoxFactory& m_alertBoxFactory; Eegeo::UI::NativeAlerts::TSingleOptionAlertBoxDismissedHandler<NavRoutingLocationFinder> m_failAlertHandler; void OnFailAlertBoxDismissed(); public: NavRoutingLocationFinder( Eegeo::Location::ILocationService& locationService, Eegeo::Resources::Interiors::InteriorsModelRepository& interiorsModelRepository, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory); virtual ~NavRoutingLocationFinder() {}; bool TryGetCurrentLocation(NavRoutingLocationModel &outLocation); bool TryGetLocationFromSearchResultModel( const Search::SdkModel::SearchResultModel& searchResultModel, NavRoutingLocationModel &outLocation); }; } } }
// ... existing code ... { namespace SdkModel { class NavRoutingLocationFinder : public INavRoutingLocationFinder, private Eegeo::NonCopyable { private: Eegeo::Location::ILocationService& m_locationService; // ... modified code ... Eegeo::Location::ILocationService& locationService, Eegeo::Resources::Interiors::InteriorsModelRepository& interiorsModelRepository, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory); virtual ~NavRoutingLocationFinder() {}; bool TryGetCurrentLocation(NavRoutingLocationModel &outLocation); bool TryGetLocationFromSearchResultModel( const Search::SdkModel::SearchResultModel& searchResultModel, // ... rest of the code ...
db43b3b3079842fb2baf6d181ef39374acf0053c
.gitlab/linters/check-makefiles.py
.gitlab/linters/check-makefiles.py
from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') ] if __name__ == '__main__': run_linters(linters, subdir='testsuite')
from linter import run_linters, RegexpLinter """ Warn for use of `--interactive` inside Makefiles (#11468). Encourage the use of `$(TEST_HC_OPTS_INTERACTIVE)` instead of `$(TEST_HC_OPTS) --interactive -ignore-dot-ghci -v0`. It's too easy to forget one of those flags when adding a new test. """ interactive_linter = \ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') test_hc_quotes_linter = \ RegexpLinter('\t\\$\\(TEST_HC\\)', message = "Warning: $(TEST_HC) should be quoted in Makefiles.", ).add_path_filter(lambda path: path.name == 'Makefile') linters = [ interactive_linter, test_hc_quotes_linter, ] if __name__ == '__main__': run_linters(linters, subdir='testsuite')
Add linter to catch unquoted use of $(TEST_HC)
linters: Add linter to catch unquoted use of $(TEST_HC) This is a common bug that creeps into Makefiles (e.g. see T12674).
Python
bsd-3-clause
sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc
python
## Code Before: from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') ] if __name__ == '__main__': run_linters(linters, subdir='testsuite') ## Instruction: linters: Add linter to catch unquoted use of $(TEST_HC) This is a common bug that creeps into Makefiles (e.g. see T12674). ## Code After: from linter import run_linters, RegexpLinter """ Warn for use of `--interactive` inside Makefiles (#11468). Encourage the use of `$(TEST_HC_OPTS_INTERACTIVE)` instead of `$(TEST_HC_OPTS) --interactive -ignore-dot-ghci -v0`. It's too easy to forget one of those flags when adding a new test. """ interactive_linter = \ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') test_hc_quotes_linter = \ RegexpLinter('\t\\$\\(TEST_HC\\)', message = "Warning: $(TEST_HC) should be quoted in Makefiles.", ).add_path_filter(lambda path: path.name == 'Makefile') linters = [ interactive_linter, test_hc_quotes_linter, ] if __name__ == '__main__': run_linters(linters, subdir='testsuite')
# ... existing code ... from linter import run_linters, RegexpLinter """ Warn for use of `--interactive` inside Makefiles (#11468). Encourage the use of `$(TEST_HC_OPTS_INTERACTIVE)` instead of `$(TEST_HC_OPTS) --interactive -ignore-dot-ghci -v0`. It's too easy to forget one of those flags when adding a new test. """ interactive_linter = \ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') test_hc_quotes_linter = \ RegexpLinter('\t\\$\\(TEST_HC\\)', message = "Warning: $(TEST_HC) should be quoted in Makefiles.", ).add_path_filter(lambda path: path.name == 'Makefile') linters = [ interactive_linter, test_hc_quotes_linter, ] if __name__ == '__main__': # ... rest of the code ...
dcfe23d95478ad612e53d1a8c53c041091b1e2b1
FrontEnd/src/test/java/rabbit/RabbitMqConfigTest.java
FrontEnd/src/test/java/rabbit/RabbitMqConfigTest.java
package rabbit; import org.junit.Test; import static org.junit.Assert.assertTrue; public class RabbitMqConfigTest { /** * Retrieve host. */ @Test public void retrieveHost() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String host = rmqConf.getHost(); assertTrue(host.length() > 0); } /** * Retrieve queue name. */ @Test public void retrieveQueue() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String queue = rmqConf.getQueue(); assertTrue(queue.length() > 0); } }
package rabbit; import org.junit.Test; import static org.junit.Assert.assertTrue; public class RabbitMqConfigTest { /** * Retrieve host. */ @Test public void retrieveHost() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String host = rmqConf.getHost(); assertTrue(host.length() > 0); } /** * Retrieve queue name. */ @Test public void retrieveQueue() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String queue = rmqConf.getQueue(); assertTrue(queue.length() > 0); } /* * Retrieve username */ @Test public void retrieveUser() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String user = rmqConf.getUsername(); assertTrue(user.length() > 0); } /** * Retrieve password. */ @Test public void retrievePassword() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String password = rmqConf.getPassword(); assertTrue(password.length() > 0); } }
Add unit test for config data for rabbitmq.
Add unit test for config data for rabbitmq.
Java
apache-2.0
IrimieBogdan/DistributedMonitoring,IrimieBogdan/DistributedMonitoring,IrimieBogdan/DistributedMonitoring
java
## Code Before: package rabbit; import org.junit.Test; import static org.junit.Assert.assertTrue; public class RabbitMqConfigTest { /** * Retrieve host. */ @Test public void retrieveHost() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String host = rmqConf.getHost(); assertTrue(host.length() > 0); } /** * Retrieve queue name. */ @Test public void retrieveQueue() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String queue = rmqConf.getQueue(); assertTrue(queue.length() > 0); } } ## Instruction: Add unit test for config data for rabbitmq. ## Code After: package rabbit; import org.junit.Test; import static org.junit.Assert.assertTrue; public class RabbitMqConfigTest { /** * Retrieve host. */ @Test public void retrieveHost() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String host = rmqConf.getHost(); assertTrue(host.length() > 0); } /** * Retrieve queue name. */ @Test public void retrieveQueue() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String queue = rmqConf.getQueue(); assertTrue(queue.length() > 0); } /* * Retrieve username */ @Test public void retrieveUser() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String user = rmqConf.getUsername(); assertTrue(user.length() > 0); } /** * Retrieve password. */ @Test public void retrievePassword() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String password = rmqConf.getPassword(); assertTrue(password.length() > 0); } }
# ... existing code ... assertTrue(queue.length() > 0); } /* * Retrieve username */ @Test public void retrieveUser() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String user = rmqConf.getUsername(); assertTrue(user.length() > 0); } /** * Retrieve password. */ @Test public void retrievePassword() { RabbitMqConfig rmqConf = new RabbitMqConfig(); String password = rmqConf.getPassword(); assertTrue(password.length() > 0); } } # ... rest of the code ...
df045cb2e5e53c497aa101719c528b1f17c03a1f
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) from app import views, models
from werkzeug.contrib.fixers import ProxyFix from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') app.wsgi_app = ProxyFix(app.wsgi_app) login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) from app import views, models
Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17
Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17
Python
mit
ngoduykhanh/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,0x97/PowerDNS-Admin,ngoduykhanh/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,0x97/PowerDNS-Admin,0x97/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,0x97/PowerDNS-Admin,ngoduykhanh/PowerDNS-Admin,ngoduykhanh/PowerDNS-Admin
python
## Code Before: from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) from app import views, models ## Instruction: Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17 ## Code After: from werkzeug.contrib.fixers import ProxyFix from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') app.wsgi_app = ProxyFix(app.wsgi_app) login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) from app import views, models
# ... existing code ... from werkzeug.contrib.fixers import ProxyFix from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy # ... modified code ... app = Flask(__name__) app.config.from_object('config') app.wsgi_app = ProxyFix(app.wsgi_app) login_manager = LoginManager() login_manager.init_app(app) db = SQLAlchemy(app) # ... rest of the code ...
6c3c379d414a0c9bfde81ff8daa0e1d40aa7a658
setup.py
setup.py
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'traits', ] )
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'argparse', 'traits', ] )
Add argparse to install_requires for Python 2.6
Add argparse to install_requires for Python 2.6
Python
bsd-3-clause
tkf/traitscli,tkf/traitscli
python
## Code Before: from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'traits', ] ) ## Instruction: Add argparse to install_requires for Python 2.6 ## Code After: from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'argparse', 'traits', ] )
# ... existing code ... # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'argparse', 'traits', ] ) # ... rest of the code ...
24f69b587ce38c581f9ee68e22978963b266f010
html_to_telegraph.py
html_to_telegraph.py
from lxml import html def _recursive_convert(element): # All strings outside tags should be ignored if not isinstance(element, html.HtmlElement): return fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': element.text}) if element.attrib: fragment_root_element.update({ 'a': dict(element.attrib) }) for child in element: content.append(_recursive_convert(child)) # Append Text node after element, if exists if child.tail: content.append({'t': child.tail}) if len(content): fragment_root_element.update({ 'c': content }) return fragment_root_element def convert_html_to_telegraph_format(html_string): return [ _recursive_convert(fragment) for fragment in html.fragments_fromstring(html_string) ]
from lxml import html import json def _recursive_convert(element): # All strings outside tags should be ignored fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': element.text}) if element.attrib: fragment_root_element.update({ 'a': dict(element.attrib) }) for child in element: content.append(_recursive_convert(child)) # Append Text node after element, if exists if child.tail: content.append({'t': child.tail}) if len(content): fragment_root_element.update({ 'c': content }) return fragment_root_element def convert_html_to_telegraph_format(html_string): content = [] for fragment in html.fragments_fromstring(html_string): if not isinstance(fragment, html.HtmlElement): continue content.append(_recursive_convert(fragment)) return json.dumps(content, ensure_ascii=False)
Return string instead of list
Return string instead of list
Python
mit
mercuree/html-telegraph-poster
python
## Code Before: from lxml import html def _recursive_convert(element): # All strings outside tags should be ignored if not isinstance(element, html.HtmlElement): return fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': element.text}) if element.attrib: fragment_root_element.update({ 'a': dict(element.attrib) }) for child in element: content.append(_recursive_convert(child)) # Append Text node after element, if exists if child.tail: content.append({'t': child.tail}) if len(content): fragment_root_element.update({ 'c': content }) return fragment_root_element def convert_html_to_telegraph_format(html_string): return [ _recursive_convert(fragment) for fragment in html.fragments_fromstring(html_string) ] ## Instruction: Return string instead of list ## Code After: from lxml import html import json def _recursive_convert(element): # All strings outside tags should be ignored fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': element.text}) if element.attrib: fragment_root_element.update({ 'a': dict(element.attrib) }) for child in element: content.append(_recursive_convert(child)) # Append Text node after element, if exists if child.tail: content.append({'t': child.tail}) if len(content): fragment_root_element.update({ 'c': content }) return fragment_root_element def convert_html_to_telegraph_format(html_string): content = [] for fragment in html.fragments_fromstring(html_string): if not isinstance(fragment, html.HtmlElement): continue content.append(_recursive_convert(fragment)) return json.dumps(content, ensure_ascii=False)
// ... existing code ... from lxml import html import json def _recursive_convert(element): # All strings outside tags should be ignored fragment_root_element = { '_': element.tag // ... modified code ... def convert_html_to_telegraph_format(html_string): content = [] for fragment in html.fragments_fromstring(html_string): if not isinstance(fragment, html.HtmlElement): continue content.append(_recursive_convert(fragment)) return json.dumps(content, ensure_ascii=False) // ... rest of the code ...
1be57ad837352d5cbf7f6e9dc4896f8d1caa7453
src/main/java/enmasse/config/service/podsense/PodSenseMessageEncoder.java
src/main/java/enmasse/config/service/podsense/PodSenseMessageEncoder.java
package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } }
package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("name", pod.getName()); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } }
Add pod name to payload
Add pod name to payload
Java
apache-2.0
EnMasseProject/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse
java
## Code Before: package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } } ## Instruction: Add pod name to payload ## Code After: package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("name", pod.getName()); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } }
... private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("name", pod.getName()); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); ...
75fd032d96ee016bdd86ce6ca15fd872c41b7bb6
src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/ObjectServiceTest.java
src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/ObjectServiceTest.java
package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import javax.ws.rs.core.Application; import static org.junit.Assert.*; public class ObjectServiceTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(FakeObjectService.class); } @Before public void setUp() throws Exception { } }
package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.FakeRepository; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Application; import static org.junit.Assert.*; public class ObjectServiceTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(FakeObjectService.class); } @Before public void setUp() throws Exception { } @Test public void testGetList_except200emptyList() { } @Test public void testGetList_except200nonemptyList() { } @Test public void testGetList_except404wrongHouseId() { } @Test public void testGetObjectById_except200ObjectDo() { } @Test public void testGetObjectById_except404WrongHouseId() { } @Test public void testGetObjectById_except404WrongObjectId() { } @Test public void testAddObject_except200() { } @Test public void testAddObject_except404WrongHouseId() { } @Test public void testUpdateObjectById_except200UpdatedObjectDo() { } @Test public void testUpdateObjectById_except404WrongHouseId() { } @Test public void testUpdateObjectById_except404WrongObjectId() { } @Test public void testDeleteObjectById_except200() { } @Test public void testDeleteObjectById_except404WrongHouseId() { } @Test public void testDeleteObjectById_except404WrongObjectId() { } private WebTarget getTarget(String houseId) { String path = String.format("/houses/%s", houseId); return target(path); } private WebTarget getTarget(String houseId, String objectId) { String path = String.format("/houses/%s/objects/%s", houseId, objectId); return target(path); } }
Add stub tests for ObjectService
Add stub tests for ObjectService
Java
mit
freeuni-sdp/iot-camera-object-recognizer
java
## Code Before: package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import javax.ws.rs.core.Application; import static org.junit.Assert.*; public class ObjectServiceTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(FakeObjectService.class); } @Before public void setUp() throws Exception { } } ## Instruction: Add stub tests for ObjectService ## Code After: package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.FakeRepository; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Application; import static org.junit.Assert.*; public class ObjectServiceTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(FakeObjectService.class); } @Before public void setUp() throws Exception { } @Test public void testGetList_except200emptyList() { } @Test public void testGetList_except200nonemptyList() { } @Test public void testGetList_except404wrongHouseId() { } @Test public void testGetObjectById_except200ObjectDo() { } @Test public void testGetObjectById_except404WrongHouseId() { } @Test public void testGetObjectById_except404WrongObjectId() { } @Test public void testAddObject_except200() { } @Test public void testAddObject_except404WrongHouseId() { } @Test public void testUpdateObjectById_except200UpdatedObjectDo() { } @Test public void testUpdateObjectById_except404WrongHouseId() { } @Test public void testUpdateObjectById_except404WrongObjectId() { } @Test public void testDeleteObjectById_except200() { } @Test public void testDeleteObjectById_except404WrongHouseId() { } @Test public void testDeleteObjectById_except404WrongObjectId() { } private WebTarget getTarget(String houseId) { String path = String.format("/houses/%s", houseId); return target(path); } private WebTarget getTarget(String houseId, String objectId) { String path = String.format("/houses/%s/objects/%s", houseId, objectId); return target(path); } }
... package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.FakeRepository; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Application; import static org.junit.Assert.*; ... } @Test public void testGetList_except200emptyList() { } @Test public void testGetList_except200nonemptyList() { } @Test public void testGetList_except404wrongHouseId() { } @Test public void testGetObjectById_except200ObjectDo() { } @Test public void testGetObjectById_except404WrongHouseId() { } @Test public void testGetObjectById_except404WrongObjectId() { } @Test public void testAddObject_except200() { } @Test public void testAddObject_except404WrongHouseId() { } @Test public void testUpdateObjectById_except200UpdatedObjectDo() { } @Test public void testUpdateObjectById_except404WrongHouseId() { } @Test public void testUpdateObjectById_except404WrongObjectId() { } @Test public void testDeleteObjectById_except200() { } @Test public void testDeleteObjectById_except404WrongHouseId() { } @Test public void testDeleteObjectById_except404WrongObjectId() { } private WebTarget getTarget(String houseId) { String path = String.format("/houses/%s", houseId); return target(path); } private WebTarget getTarget(String houseId, String objectId) { String path = String.format("/houses/%s/objects/%s", houseId, objectId); return target(path); } } ...
db4620130cf8444dec7c42bc1f907acdec89dfed
maws.py
maws.py
import argparse import sys from mawslib.manager import Manager configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command> help maws <command> <subcommand> help ''') parser.add_argument('command', help='Command to run', choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds', 'cloudformation', 'cfn' ]) parser.add_argument('--config', help='alternate config file to use (default: cloudconfig.yaml)', action="store") # parse_args defaults to [1:] for args, but you need to # exclude the rest of the args too, or validation will fail args, subargs = parser.parse_known_args() if hasattr(args, "config"): configfile = args.config mgr = Manager(configfile) mgr.showname() if args.command == "cfn": args.command = "cloudformation" if args.command == "r53": args.command = "route53" exec("from cli.%s_cli import processCommand" % args.command) processCommand(mgr, subargs)
import argparse import sys from mawslib.manager import Manager import importlib configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command> help maws <command> <subcommand> help ''') parser.add_argument('command', help='Command to run', choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds', 'cloudformation', 'cfn' ]) parser.add_argument('--config', help='alternate config file to use (default: cloudconfig.yaml)', action="store") # parse_args defaults to [1:] for args, but you need to # exclude the rest of the args too, or validation will fail args, subargs = parser.parse_known_args() if hasattr(args, "config"): configfile = args.config mgr = Manager(configfile) mgr.showname() if args.command == "cfn": args.command = "cloudformation" if args.command == "r53": args.command = "route53" cli_mod = importlib.import_module("cli.%s_cli" % args.command) cli_mod.processCommand(mgr, subargs)
Use importlib instead of exec (exec was pretty ugly)
Use importlib instead of exec (exec was pretty ugly)
Python
mit
uva-its/awstools
python
## Code Before: import argparse import sys from mawslib.manager import Manager configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command> help maws <command> <subcommand> help ''') parser.add_argument('command', help='Command to run', choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds', 'cloudformation', 'cfn' ]) parser.add_argument('--config', help='alternate config file to use (default: cloudconfig.yaml)', action="store") # parse_args defaults to [1:] for args, but you need to # exclude the rest of the args too, or validation will fail args, subargs = parser.parse_known_args() if hasattr(args, "config"): configfile = args.config mgr = Manager(configfile) mgr.showname() if args.command == "cfn": args.command = "cloudformation" if args.command == "r53": args.command = "route53" exec("from cli.%s_cli import processCommand" % args.command) processCommand(mgr, subargs) ## Instruction: Use importlib instead of exec (exec was pretty ugly) ## Code After: import argparse import sys from mawslib.manager import Manager import importlib configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command> help maws <command> <subcommand> help ''') parser.add_argument('command', help='Command to run', choices = ['help', 'ec2', 'sdb', 'route53', 'r53', 'rds', 'cloudformation', 'cfn' ]) parser.add_argument('--config', help='alternate config file to use (default: cloudconfig.yaml)', action="store") # parse_args defaults to [1:] for args, but you need to # exclude the rest of the args too, or validation will fail args, subargs = parser.parse_known_args() if hasattr(args, "config"): configfile = args.config mgr = Manager(configfile) mgr.showname() if args.command == "cfn": args.command = "cloudformation" if args.command == "r53": args.command = "route53" cli_mod = importlib.import_module("cli.%s_cli" % args.command) cli_mod.processCommand(mgr, subargs)
// ... existing code ... import argparse import sys from mawslib.manager import Manager import importlib configfile="cloudconfig.yaml" // ... modified code ... if args.command == "cfn": args.command = "cloudformation" if args.command == "r53": args.command = "route53" cli_mod = importlib.import_module("cli.%s_cli" % args.command) cli_mod.processCommand(mgr, subargs) // ... rest of the code ...
329e74f280537aab41d5b810f8650bfd8d6d81f5
tests/test_generate_files.py
tests/test_generate_files.py
import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures("clean_system") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import exceptions from cookiecutter import utils @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
Add teardown specific to the former TestCase class
Add teardown specific to the former TestCase class
Python
bsd-3-clause
michaeljoseph/cookiecutter,christabor/cookiecutter,cguardia/cookiecutter,janusnic/cookiecutter,michaeljoseph/cookiecutter,cguardia/cookiecutter,vincentbernat/cookiecutter,drgarcia1986/cookiecutter,Vauxoo/cookiecutter,cichm/cookiecutter,benthomasson/cookiecutter,0k/cookiecutter,terryjbates/cookiecutter,atlassian/cookiecutter,lucius-feng/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,0k/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,jhermann/cookiecutter,ramiroluz/cookiecutter,kkujawinski/cookiecutter,agconti/cookiecutter,sp1rs/cookiecutter,lgp171188/cookiecutter,kkujawinski/cookiecutter,jhermann/cookiecutter,venumech/cookiecutter,sp1rs/cookiecutter,luzfcb/cookiecutter,janusnic/cookiecutter,vintasoftware/cookiecutter,atlassian/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ionelmc/cookiecutter,takeflight/cookiecutter,letolab/cookiecutter,letolab/cookiecutter,pjbull/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,audreyr/cookiecutter,takeflight/cookiecutter,lgp171188/cookiecutter,agconti/cookiecutter,vintasoftware/cookiecutter,Springerle/cookiecutter,cichm/cookiecutter,ionelmc/cookiecutter,benthomasson/cookiecutter,lucius-feng/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,foodszhang/cookiecutter,foodszhang/cookiecutter,vincentbernat/cookiecutter,ramiroluz/cookiecutter,tylerdave/cookiecutter,tylerdave/cookiecutter,nhomar/cookiecutter,dajose/cookiecutter,stevepiercy/cookiecutter,nhomar/cookiecutter,willingc/cookiecutter,Vauxoo/cookiecutter,drgarcia1986/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,dajose/cookiecutter
python
## Code Before: import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures("clean_system") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' ) ## Instruction: Add teardown specific to the former TestCase class ## Code After: from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import exceptions from cookiecutter import utils @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
// ... existing code ... from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import exceptions from cookiecutter import utils @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( // ... rest of the code ...
0bfd715ca0bae0929f2a06bdb42bdb0c95aea6dd
grafeno/_parse_freeling.py
grafeno/_parse_freeling.py
from subprocess import Popen, PIPE import subprocess as subp import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = "grafeno/freeling_deps_"+lang+".cfg" proc = Popen(["analyze", "--flush", "-f", config], stdin=PIPE, stdout=PIPE, stderr=PIPE) data, err = proc.communicate(sentence.encode('UTF-8')) return json.loads('['+regex.sub('},{',data.decode('UTF-8'))+']')
from subprocess import Popen, PIPE import subprocess as subp import os import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = os.path.dirname(__file__)+"/freeling_deps_"+lang+".cfg" proc = Popen(["analyze", "--flush", "-f", config], stdin=PIPE, stdout=PIPE, stderr=PIPE) data, err = proc.communicate(sentence.encode('UTF-8')) return json.loads('['+regex.sub('},{',data.decode('UTF-8'))+']')
Make freeling configuration available independent of execution path
Make freeling configuration available independent of execution path
Python
agpl-3.0
agarsev/grafeno,agarsev/grafeno,agarsev/grafeno
python
## Code Before: from subprocess import Popen, PIPE import subprocess as subp import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = "grafeno/freeling_deps_"+lang+".cfg" proc = Popen(["analyze", "--flush", "-f", config], stdin=PIPE, stdout=PIPE, stderr=PIPE) data, err = proc.communicate(sentence.encode('UTF-8')) return json.loads('['+regex.sub('},{',data.decode('UTF-8'))+']') ## Instruction: Make freeling configuration available independent of execution path ## Code After: from subprocess import Popen, PIPE import subprocess as subp import os import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = os.path.dirname(__file__)+"/freeling_deps_"+lang+".cfg" proc = Popen(["analyze", "--flush", "-f", config], stdin=PIPE, stdout=PIPE, stderr=PIPE) data, err = proc.communicate(sentence.encode('UTF-8')) return json.loads('['+regex.sub('},{',data.decode('UTF-8'))+']')
# ... existing code ... from subprocess import Popen, PIPE import subprocess as subp import os import json import re # ... modified code ... def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = os.path.dirname(__file__)+"/freeling_deps_"+lang+".cfg" proc = Popen(["analyze", "--flush", "-f", config], stdin=PIPE, stdout=PIPE, stderr=PIPE) data, err = proc.communicate(sentence.encode('UTF-8')) return json.loads('['+regex.sub('},{',data.decode('UTF-8'))+']') # ... rest of the code ...
1982c8bc089e456ab932eba79de32afa4970f18f
test-framework/junit5/src/main/java/io/quarkus/test/junit/launcher/ConfigUtil.java
test-framework/junit5/src/main/java/io/quarkus/test/junit/launcher/ConfigUtil.java
package io.quarkus.test.junit.launcher; import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.OptionalLong; import org.eclipse.microprofile.config.Config; public final class ConfigUtil { private ConfigUtil() { } public static List<String> argLineValue(Config config) { List<String> strings = config.getOptionalValues("quarkus.test.arg-line", String.class) .orElse(config.getOptionalValues("quarkus.test.argLine", String.class) // legacy value .orElse(Collections.emptyList())); if (strings.isEmpty()) { return strings; } List<String> sanitizedString = new ArrayList<>(strings.size()); for (String s : strings) { String trimmed = s.trim(); if (trimmed.isEmpty()) { continue; } sanitizedString.add(trimmed); } return sanitizedString; } public static Duration waitTimeValue(Config config) { return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class) .orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value .orElse(DEFAULT_WAIT_TIME_SECONDS))); } }
package io.quarkus.test.junit.launcher; import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.OptionalLong; import org.eclipse.microprofile.config.Config; public final class ConfigUtil { private ConfigUtil() { } public static List<String> argLineValue(Config config) { String strValue = config.getOptionalValue("quarkus.test.arg-line", String.class) .orElse(config.getOptionalValue("quarkus.test.argLine", String.class) // legacy value .orElse(null)); if (strValue == null) { return Collections.emptyList(); } String[] parts = strValue.split("\\s+"); List<String> result = new ArrayList<>(parts.length); for (String s : parts) { String trimmed = s.trim(); if (trimmed.isEmpty()) { continue; } result.add(trimmed); } return result; } public static Duration waitTimeValue(Config config) { return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class) .orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value .orElse(DEFAULT_WAIT_TIME_SECONDS))); } }
Fix quarkus.test.arg-line multiple args handling
Fix quarkus.test.arg-line multiple args handling The split is intended to happen on a whitespace character, not the comma character used by properties Fixes: #19623
Java
apache-2.0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
java
## Code Before: package io.quarkus.test.junit.launcher; import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.OptionalLong; import org.eclipse.microprofile.config.Config; public final class ConfigUtil { private ConfigUtil() { } public static List<String> argLineValue(Config config) { List<String> strings = config.getOptionalValues("quarkus.test.arg-line", String.class) .orElse(config.getOptionalValues("quarkus.test.argLine", String.class) // legacy value .orElse(Collections.emptyList())); if (strings.isEmpty()) { return strings; } List<String> sanitizedString = new ArrayList<>(strings.size()); for (String s : strings) { String trimmed = s.trim(); if (trimmed.isEmpty()) { continue; } sanitizedString.add(trimmed); } return sanitizedString; } public static Duration waitTimeValue(Config config) { return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class) .orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value .orElse(DEFAULT_WAIT_TIME_SECONDS))); } } ## Instruction: Fix quarkus.test.arg-line multiple args handling The split is intended to happen on a whitespace character, not the comma character used by properties Fixes: #19623 ## Code After: package io.quarkus.test.junit.launcher; import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.OptionalLong; import org.eclipse.microprofile.config.Config; public final class ConfigUtil { private ConfigUtil() { } public static List<String> argLineValue(Config config) { String strValue = config.getOptionalValue("quarkus.test.arg-line", String.class) .orElse(config.getOptionalValue("quarkus.test.argLine", String.class) // legacy value .orElse(null)); if (strValue == null) { return Collections.emptyList(); } String[] parts = strValue.split("\\s+"); List<String> result = new ArrayList<>(parts.length); for (String s : parts) { String trimmed = s.trim(); if (trimmed.isEmpty()) { continue; } result.add(trimmed); } return result; } public static Duration waitTimeValue(Config config) { return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class) .orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value .orElse(DEFAULT_WAIT_TIME_SECONDS))); } }
// ... existing code ... } public static List<String> argLineValue(Config config) { String strValue = config.getOptionalValue("quarkus.test.arg-line", String.class) .orElse(config.getOptionalValue("quarkus.test.argLine", String.class) // legacy value .orElse(null)); if (strValue == null) { return Collections.emptyList(); } String[] parts = strValue.split("\\s+"); List<String> result = new ArrayList<>(parts.length); for (String s : parts) { String trimmed = s.trim(); if (trimmed.isEmpty()) { continue; } result.add(trimmed); } return result; } public static Duration waitTimeValue(Config config) { // ... rest of the code ...
b977de3af3ae93a57f36e1d6eea234f01cbc7a61
py/selenium/__init__.py
py/selenium/__init__.py
from selenium import selenium __version__ = "2.53.0"
__version__ = "2.53.0"
Remove import of Selenium RC
Remove import of Selenium RC
Python
apache-2.0
bayandin/selenium,carlosroh/selenium,asolntsev/selenium,Herst/selenium,alb-i986/selenium,joshuaduffy/selenium,oddui/selenium,TikhomirovSergey/selenium,sankha93/selenium,mojwang/selenium,lmtierney/selenium,carlosroh/selenium,jsakamoto/selenium,mach6/selenium,Herst/selenium,krmahadevan/selenium,DrMarcII/selenium,tbeadle/selenium,valfirst/selenium,joshuaduffy/selenium,Ardesco/selenium,Tom-Trumper/selenium,mojwang/selenium,jsakamoto/selenium,markodolancic/selenium,titusfortner/selenium,5hawnknight/selenium,davehunt/selenium,davehunt/selenium,carlosroh/selenium,GorK-ChO/selenium,asolntsev/selenium,krmahadevan/selenium,carlosroh/selenium,oddui/selenium,titusfortner/selenium,mojwang/selenium,jabbrwcky/selenium,kalyanjvn1/selenium,sag-enorman/selenium,markodolancic/selenium,5hawnknight/selenium,twalpole/selenium,Dude-X/selenium,davehunt/selenium,dibagga/selenium,GorK-ChO/selenium,kalyanjvn1/selenium,DrMarcII/selenium,asolntsev/selenium,GorK-ChO/selenium,HtmlUnit/selenium,Dude-X/selenium,Ardesco/selenium,mojwang/selenium,gurayinan/selenium,valfirst/selenium,jsakamoto/selenium,chrisblock/selenium,tbeadle/selenium,TikhomirovSergey/selenium,5hawnknight/selenium,Jarob22/selenium,xmhubj/selenium,Tom-Trumper/selenium,joshuaduffy/selenium,Herst/selenium,xsyntrex/selenium,titusfortner/selenium,valfirst/selenium,asolntsev/selenium,oddui/selenium,Jarob22/selenium,jabbrwcky/selenium,kalyanjvn1/selenium,chrisblock/selenium,jsakamoto/selenium,lmtierney/selenium,xmhubj/selenium,kalyanjvn1/selenium,DrMarcII/selenium,Ardesco/selenium,lmtierney/selenium,bayandin/selenium,GorK-ChO/selenium,lmtierney/selenium,GorK-ChO/selenium,jsakamoto/selenium,jabbrwcky/selenium,xsyntrex/selenium,joshmgrant/selenium,asashour/selenium,xsyntrex/selenium,twalpole/selenium,joshbruning/selenium,markodolancic/selenium,uchida/selenium,dibagga/selenium,alb-i986/selenium,SeleniumHQ/selenium,alb-i986/selenium,sankha93/selenium,lmtierney/selenium,asashour/selenium,TikhomirovSergey/selenium,Dude-X/selenium,gurayinan/selenium,jabbrwcky/selenium,oddui/selenium,oddui/selenium,SeleniumHQ/selenium,sankha93/selenium,bayandin/selenium,mach6/selenium,TikhomirovSergey/selenium,valfirst/selenium,SeleniumHQ/selenium,jabbrwcky/selenium,mach6/selenium,chrisblock/selenium,davehunt/selenium,twalpole/selenium,mojwang/selenium,lmtierney/selenium,juangj/selenium,SeleniumHQ/selenium,gurayinan/selenium,HtmlUnit/selenium,juangj/selenium,oddui/selenium,chrisblock/selenium,sankha93/selenium,krmahadevan/selenium,joshbruning/selenium,dibagga/selenium,jabbrwcky/selenium,joshuaduffy/selenium,alb-i986/selenium,alb-i986/selenium,joshuaduffy/selenium,GorK-ChO/selenium,alb-i986/selenium,tbeadle/selenium,chrisblock/selenium,joshmgrant/selenium,xsyntrex/selenium,twalpole/selenium,twalpole/selenium,bayandin/selenium,uchida/selenium,5hawnknight/selenium,twalpole/selenium,Tom-Trumper/selenium,Ardesco/selenium,Herst/selenium,oddui/selenium,juangj/selenium,TikhomirovSergey/selenium,titusfortner/selenium,kalyanjvn1/selenium,gurayinan/selenium,Tom-Trumper/selenium,GorK-ChO/selenium,Tom-Trumper/selenium,SeleniumHQ/selenium,bayandin/selenium,davehunt/selenium,xmhubj/selenium,TikhomirovSergey/selenium,jsakamoto/selenium,chrisblock/selenium,HtmlUnit/selenium,markodolancic/selenium,sag-enorman/selenium,Tom-Trumper/selenium,juangj/selenium,bayandin/selenium,joshbruning/selenium,TikhomirovSergey/selenium,DrMarcII/selenium,joshbruning/selenium,tbeadle/selenium,mojwang/selenium,xmhubj/selenium,Dude-X/selenium,joshmgrant/selenium,Jarob22/selenium,sankha93/selenium,jabbrwcky/selenium,mojwang/selenium,HtmlUnit/selenium,juangj/selenium,mojwang/selenium,Dude-X/selenium,jsakamoto/selenium,sag-enorman/selenium,joshmgrant/selenium,Jarob22/selenium,carlosroh/selenium,DrMarcII/selenium,GorK-ChO/selenium,dibagga/selenium,uchida/selenium,joshuaduffy/selenium,SeleniumHQ/selenium,chrisblock/selenium,joshuaduffy/selenium,sag-enorman/selenium,krmahadevan/selenium,carlosroh/selenium,Herst/selenium,xsyntrex/selenium,xmhubj/selenium,titusfortner/selenium,kalyanjvn1/selenium,valfirst/selenium,sankha93/selenium,tbeadle/selenium,asashour/selenium,mach6/selenium,twalpole/selenium,bayandin/selenium,HtmlUnit/selenium,joshmgrant/selenium,sag-enorman/selenium,Ardesco/selenium,Ardesco/selenium,sag-enorman/selenium,oddui/selenium,Tom-Trumper/selenium,dibagga/selenium,markodolancic/selenium,asashour/selenium,xmhubj/selenium,alb-i986/selenium,Jarob22/selenium,titusfortner/selenium,jsakamoto/selenium,valfirst/selenium,joshmgrant/selenium,HtmlUnit/selenium,5hawnknight/selenium,davehunt/selenium,tbeadle/selenium,asolntsev/selenium,kalyanjvn1/selenium,HtmlUnit/selenium,uchida/selenium,gurayinan/selenium,titusfortner/selenium,5hawnknight/selenium,joshmgrant/selenium,joshmgrant/selenium,carlosroh/selenium,krmahadevan/selenium,jabbrwcky/selenium,chrisblock/selenium,lmtierney/selenium,alb-i986/selenium,lmtierney/selenium,jsakamoto/selenium,carlosroh/selenium,SeleniumHQ/selenium,joshmgrant/selenium,Herst/selenium,5hawnknight/selenium,twalpole/selenium,Tom-Trumper/selenium,kalyanjvn1/selenium,sankha93/selenium,uchida/selenium,Ardesco/selenium,HtmlUnit/selenium,HtmlUnit/selenium,GorK-ChO/selenium,asashour/selenium,asashour/selenium,xsyntrex/selenium,sag-enorman/selenium,Jarob22/selenium,Herst/selenium,xsyntrex/selenium,mach6/selenium,mojwang/selenium,kalyanjvn1/selenium,joshbruning/selenium,Herst/selenium,tbeadle/selenium,bayandin/selenium,asolntsev/selenium,SeleniumHQ/selenium,valfirst/selenium,5hawnknight/selenium,valfirst/selenium,markodolancic/selenium,joshbruning/selenium,davehunt/selenium,DrMarcII/selenium,davehunt/selenium,sag-enorman/selenium,Dude-X/selenium,lmtierney/selenium,bayandin/selenium,joshmgrant/selenium,SeleniumHQ/selenium,joshuaduffy/selenium,Jarob22/selenium,Tom-Trumper/selenium,asashour/selenium,titusfortner/selenium,davehunt/selenium,Jarob22/selenium,xsyntrex/selenium,uchida/selenium,asolntsev/selenium,Dude-X/selenium,valfirst/selenium,juangj/selenium,mach6/selenium,joshbruning/selenium,chrisblock/selenium,joshuaduffy/selenium,titusfortner/selenium,titusfortner/selenium,gurayinan/selenium,sankha93/selenium,sankha93/selenium,markodolancic/selenium,twalpole/selenium,asashour/selenium,juangj/selenium,5hawnknight/selenium,Ardesco/selenium,uchida/selenium,Jarob22/selenium,xmhubj/selenium,dibagga/selenium,tbeadle/selenium,krmahadevan/selenium,SeleniumHQ/selenium,krmahadevan/selenium,titusfortner/selenium,DrMarcII/selenium,asolntsev/selenium,dibagga/selenium,uchida/selenium,SeleniumHQ/selenium,valfirst/selenium,joshbruning/selenium,gurayinan/selenium,juangj/selenium,sag-enorman/selenium,jabbrwcky/selenium,DrMarcII/selenium,Dude-X/selenium,HtmlUnit/selenium,xmhubj/selenium,dibagga/selenium,asashour/selenium,mach6/selenium,xmhubj/selenium,gurayinan/selenium,Herst/selenium,xsyntrex/selenium,TikhomirovSergey/selenium,joshmgrant/selenium,TikhomirovSergey/selenium,juangj/selenium,Ardesco/selenium,joshbruning/selenium,valfirst/selenium,mach6/selenium,krmahadevan/selenium,markodolancic/selenium,alb-i986/selenium,uchida/selenium,DrMarcII/selenium,Dude-X/selenium,oddui/selenium,krmahadevan/selenium,markodolancic/selenium,asolntsev/selenium,dibagga/selenium,tbeadle/selenium,mach6/selenium,carlosroh/selenium,gurayinan/selenium
python
## Code Before: from selenium import selenium __version__ = "2.53.0" ## Instruction: Remove import of Selenium RC ## Code After: __version__ = "2.53.0"
# ... existing code ... __version__ = "2.53.0" # ... rest of the code ...
9de0a05d28c83742224c0e708e80b8add198a8a8
froide/comments/apps.py
froide/comments/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class CommentConfig(AppConfig): name = 'froide.comments' verbose_name = _('Comments') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_user) def cancel_user(sender, user=None, **kwargs): from .models import FroideComment if user is None: return FroideComment.objects.filter(user=user).update( user_name='', user_email='', user_url='' )
import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class CommentConfig(AppConfig): name = 'froide.comments' verbose_name = _('Comments') def ready(self): from froide.account import account_canceled from froide.account.export import registry account_canceled.connect(cancel_user) registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): from .models import FroideComment if user is None: return FroideComment.objects.filter(user=user).update( user_name='', user_email='', user_url='' ) def export_user_data(user): from .models import FroideComment comments = FroideComment.objects.filter(user=user) if not comments: return yield ('comments.json', json.dumps([ { 'submit_date': ( c.submit_date.isoformat() if c.submit_date else None ), 'comment': c.comment, 'is_public': c.is_public, 'is_removed': c.is_removed, 'url': c.get_absolute_url(), } for c in comments]).encode('utf-8') )
Add user data export for comments
Add user data export for comments
Python
mit
stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
python
## Code Before: from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class CommentConfig(AppConfig): name = 'froide.comments' verbose_name = _('Comments') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_user) def cancel_user(sender, user=None, **kwargs): from .models import FroideComment if user is None: return FroideComment.objects.filter(user=user).update( user_name='', user_email='', user_url='' ) ## Instruction: Add user data export for comments ## Code After: import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class CommentConfig(AppConfig): name = 'froide.comments' verbose_name = _('Comments') def ready(self): from froide.account import account_canceled from froide.account.export import registry account_canceled.connect(cancel_user) registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): from .models import FroideComment if user is None: return FroideComment.objects.filter(user=user).update( user_name='', user_email='', user_url='' ) def export_user_data(user): from .models import FroideComment comments = FroideComment.objects.filter(user=user) if not comments: return yield ('comments.json', json.dumps([ { 'submit_date': ( c.submit_date.isoformat() if c.submit_date else None ), 'comment': c.comment, 'is_public': c.is_public, 'is_removed': c.is_removed, 'url': c.get_absolute_url(), } for c in comments]).encode('utf-8') )
// ... existing code ... import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ // ... modified code ... def ready(self): from froide.account import account_canceled from froide.account.export import registry account_canceled.connect(cancel_user) registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): ... user_email='', user_url='' ) def export_user_data(user): from .models import FroideComment comments = FroideComment.objects.filter(user=user) if not comments: return yield ('comments.json', json.dumps([ { 'submit_date': ( c.submit_date.isoformat() if c.submit_date else None ), 'comment': c.comment, 'is_public': c.is_public, 'is_removed': c.is_removed, 'url': c.get_absolute_url(), } for c in comments]).encode('utf-8') ) // ... rest of the code ...
6ba1d1805a65ff7e07b795ed7b54fc3375a1e3e4
main_AWS.py
main_AWS.py
def process_single_user(username, password): try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") print("Trying to Buy Streak Freeze for " + username) if(lingo.buy_streak_freeze()): print("Bought streak freeze for " + username) else: print("Unable to buy streak freeze") try: print("Trying to Buy Double or nothing for " + username) lingo.buy_item('rupee_wager', 'en') print("Bought Double or nothing for " + username) except: print("Unable to buy double or nothing") def main(a, b): import duolingo, os usernames = os.environ['usernames'].split(',') passwords = os.environ['passwords'].split(',') list(map(process_single_user, usernames, passwords))
def process_single_user(username, password): import duolingo try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") stuff_to_purchase = ['streak_freeze', 'rupee_wager'] for item in stuff_to_purchase: try: print("Trying to Buy " + item + " for " + username) lingo.buy_item(item, 'en') print("Bought " + item + " for " + username) except duolingo.AlreadyHaveStoreItemException: print("Item Already Equipped") except Exception: raise ValueError("Unable to buy double or nothing") def main(a, b): import duolingo, os usernames = os.environ['usernames'].split(',') passwords = os.environ['passwords'].split(',') list(map(process_single_user, usernames, passwords))
UPdate to duolingo for the API
UPdate to duolingo for the API
Python
mit
alexsanjoseph/duolingo-save-streak,alexsanjoseph/duolingo-save-streak
python
## Code Before: def process_single_user(username, password): try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") print("Trying to Buy Streak Freeze for " + username) if(lingo.buy_streak_freeze()): print("Bought streak freeze for " + username) else: print("Unable to buy streak freeze") try: print("Trying to Buy Double or nothing for " + username) lingo.buy_item('rupee_wager', 'en') print("Bought Double or nothing for " + username) except: print("Unable to buy double or nothing") def main(a, b): import duolingo, os usernames = os.environ['usernames'].split(',') passwords = os.environ['passwords'].split(',') list(map(process_single_user, usernames, passwords)) ## Instruction: UPdate to duolingo for the API ## Code After: def process_single_user(username, password): import duolingo try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") stuff_to_purchase = ['streak_freeze', 'rupee_wager'] for item in stuff_to_purchase: try: print("Trying to Buy " + item + " for " + username) lingo.buy_item(item, 'en') print("Bought " + item + " for " + username) except duolingo.AlreadyHaveStoreItemException: print("Item Already Equipped") except Exception: raise ValueError("Unable to buy double or nothing") def main(a, b): import duolingo, os usernames = os.environ['usernames'].split(',') passwords = os.environ['passwords'].split(',') list(map(process_single_user, usernames, passwords))
... def process_single_user(username, password): import duolingo try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") stuff_to_purchase = ['streak_freeze', 'rupee_wager'] for item in stuff_to_purchase: try: print("Trying to Buy " + item + " for " + username) lingo.buy_item(item, 'en') print("Bought " + item + " for " + username) except duolingo.AlreadyHaveStoreItemException: print("Item Already Equipped") except Exception: raise ValueError("Unable to buy double or nothing") ...
31be33e086fbf0b1f09a9d7dca547aa4cd256cbe
src/main/java/handson/Main.java
src/main/java/handson/Main.java
package handson; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import io.sphere.sdk.client.SphereClientFactory; import io.sphere.sdk.products.queries.ProductProjectionQuery; import java.io.IOException; import java.util.Properties; public class Main { public static void main(String[] args) throws IOException { final Properties prop = loadCommercetoolsPlatformProperties(); final String projectKey = prop.getProperty("projectKey"); final String clientId = prop.getProperty("clientId"); final String clientSecret = prop.getProperty("clientSecret"); final SphereClientConfig clientConfig = SphereClientConfig.of(projectKey, clientId, clientSecret); try(final SphereClient client = SphereClientFactory.of().createClient(clientConfig)) { System.err.println(client.execute(ProductProjectionQuery.ofCurrent()).toCompletableFuture().join()); } } private static Properties loadCommercetoolsPlatformProperties() throws IOException { final Properties prop = new Properties(); prop.load(Main.class.getClassLoader().getResourceAsStream("dev.properties")); return prop; } }
package handson; import io.sphere.sdk.client.BlockingSphereClient; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import io.sphere.sdk.client.SphereClientFactory; import io.sphere.sdk.products.queries.ProductProjectionQuery; import java.io.IOException; import java.time.Duration; import java.util.Properties; public class Main { public static void main(String[] args) throws IOException { try(final SphereClient client = createSphereClient()) { System.err.println(client.execute(ProductProjectionQuery.ofCurrent()).toCompletableFuture().join()); } } private static BlockingSphereClient createSphereClient() throws IOException { final SphereClientConfig clientConfig = loadCommercetoolsPlatformClientConfig(); final SphereClient client = SphereClientFactory.of().createClient(clientConfig); return BlockingSphereClient.of(client, Duration.ofMinutes(1)); } private static SphereClientConfig loadCommercetoolsPlatformClientConfig() throws IOException { final Properties prop = new Properties(); prop.load(Main.class.getClassLoader().getResourceAsStream("dev.properties")); final String projectKey = prop.getProperty("projectKey"); final String clientId = prop.getProperty("clientId"); final String clientSecret = prop.getProperty("clientSecret"); return SphereClientConfig.of(projectKey, clientId, clientSecret); } }
Move client creation to another method and use blocking client instead
Move client creation to another method and use blocking client instead
Java
apache-2.0
sphereio/sphere-jvm-sdk-hands-on
java
## Code Before: package handson; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import io.sphere.sdk.client.SphereClientFactory; import io.sphere.sdk.products.queries.ProductProjectionQuery; import java.io.IOException; import java.util.Properties; public class Main { public static void main(String[] args) throws IOException { final Properties prop = loadCommercetoolsPlatformProperties(); final String projectKey = prop.getProperty("projectKey"); final String clientId = prop.getProperty("clientId"); final String clientSecret = prop.getProperty("clientSecret"); final SphereClientConfig clientConfig = SphereClientConfig.of(projectKey, clientId, clientSecret); try(final SphereClient client = SphereClientFactory.of().createClient(clientConfig)) { System.err.println(client.execute(ProductProjectionQuery.ofCurrent()).toCompletableFuture().join()); } } private static Properties loadCommercetoolsPlatformProperties() throws IOException { final Properties prop = new Properties(); prop.load(Main.class.getClassLoader().getResourceAsStream("dev.properties")); return prop; } } ## Instruction: Move client creation to another method and use blocking client instead ## Code After: package handson; import io.sphere.sdk.client.BlockingSphereClient; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import io.sphere.sdk.client.SphereClientFactory; import io.sphere.sdk.products.queries.ProductProjectionQuery; import java.io.IOException; import java.time.Duration; import java.util.Properties; public class Main { public static void main(String[] args) throws IOException { try(final SphereClient client = createSphereClient()) { System.err.println(client.execute(ProductProjectionQuery.ofCurrent()).toCompletableFuture().join()); } } private static BlockingSphereClient createSphereClient() throws IOException { final SphereClientConfig clientConfig = loadCommercetoolsPlatformClientConfig(); final SphereClient client = SphereClientFactory.of().createClient(clientConfig); return BlockingSphereClient.of(client, Duration.ofMinutes(1)); } private static SphereClientConfig loadCommercetoolsPlatformClientConfig() throws IOException { final Properties prop = new Properties(); prop.load(Main.class.getClassLoader().getResourceAsStream("dev.properties")); final String projectKey = prop.getProperty("projectKey"); final String clientId = prop.getProperty("clientId"); final String clientSecret = prop.getProperty("clientSecret"); return SphereClientConfig.of(projectKey, clientId, clientSecret); } }
... package handson; import io.sphere.sdk.client.BlockingSphereClient; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import io.sphere.sdk.client.SphereClientFactory; ... import io.sphere.sdk.products.queries.ProductProjectionQuery; import java.io.IOException; import java.time.Duration; import java.util.Properties; public class Main { public static void main(String[] args) throws IOException { try(final SphereClient client = createSphereClient()) { System.err.println(client.execute(ProductProjectionQuery.ofCurrent()).toCompletableFuture().join()); } } private static BlockingSphereClient createSphereClient() throws IOException { final SphereClientConfig clientConfig = loadCommercetoolsPlatformClientConfig(); final SphereClient client = SphereClientFactory.of().createClient(clientConfig); return BlockingSphereClient.of(client, Duration.ofMinutes(1)); } private static SphereClientConfig loadCommercetoolsPlatformClientConfig() throws IOException { final Properties prop = new Properties(); prop.load(Main.class.getClassLoader().getResourceAsStream("dev.properties")); final String projectKey = prop.getProperty("projectKey"); final String clientId = prop.getProperty("clientId"); final String clientSecret = prop.getProperty("clientSecret"); return SphereClientConfig.of(projectKey, clientId, clientSecret); } } ...