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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
a9b56fe98a0df71881c41a2524bdb5abc4b0de50
|
services/imu-logger.py
|
services/imu-logger.py
|
from sense_hat import SenseHat
from pymongo import MongoClient
import time
DELAY = 1 # in seconds
sense = SenseHat()
client = MongoClient("mongodb://10.0.1.25:27017")
db = client.g2x
while True:
orientation = sense.get_orientation_degrees()
print(orientation)
acceleration = sense.get_accelerometer()
compass = sense.get_compass()
temperature_from_humidity = sense.get_temperature()
temperature_from_pressure = sense.get_temperature_from_pressure()
db.gyroscope.insert_one({
"pitch": orientation["pitch"],
"roll": orientation["roll"],
"yaw": orientation["yaw"]
})
db.accelerometer.insert_one({
"pitch": acceleration["pitch"],
"roll": acceleration["roll"],
"yaw": acceleration["yaw"]
})
db.compass.insert_one({"angle": compass})
db.temperature.insert_one({
"from_humidity": temperature_from_humidity,
"from_pressure": temperature_from_pressure
})
time.sleep(DELAY)
|
from sense_hat import SenseHat
from pymongo import MongoClient
from datetime import datetime
sense = SenseHat()
client = MongoClient("mongodb://10.0.1.25:27017")
db = client.g2x
last_time = datetime.utcnow()
sample_count = 0
while True:
current_time = datetime.utcnow()
elapsed_time = current_time - last_time
orientation = sense.get_orientation()
gyroscope = sense.get_gyroscope()
acceleration = sense.get_accelerometer()
compass = sense.get_compass()
temperature_from_humidity = sense.get_temperature()
temperature_from_pressure = sense.get_temperature_from_pressure()
sample_count += 1
if elapsed_time.seconds >= 1:
last_time = current_time
print("sample per second =", sample_count)
print("orientation =", orientation)
print("gyroscope =", gyroscope)
print("acceleration =", acceleration)
print("compass =", compass)
print("temperature_from_humidity =", temperature_from_humidity)
print("temperature_from_pressure =", temperature_from_pressure)
sample_count = 0
db.orientation.insert_one({
"pitch": orientation["pitch"],
"roll": orientation["roll"],
"yaw": orientation["yaw"]
})
db.gyroscope.insert_one({
"pitch": gyroscope["pitch"],
"roll": gyroscope["roll"],
"yaw": gyroscope["yaw"]
})
db.accelerometer.insert_one({
"pitch": acceleration["pitch"],
"roll": acceleration["roll"],
"yaw": acceleration["yaw"]
})
db.compass.insert_one({"angle": compass})
db.temperature.insert_one({
"from_humidity": temperature_from_humidity,
"from_pressure": temperature_from_pressure
})
|
Read samples faster but log only once a second
|
Read samples faster but log only once a second
|
Python
|
bsd-3-clause
|
gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2
|
python
|
## Code Before:
from sense_hat import SenseHat
from pymongo import MongoClient
import time
DELAY = 1 # in seconds
sense = SenseHat()
client = MongoClient("mongodb://10.0.1.25:27017")
db = client.g2x
while True:
orientation = sense.get_orientation_degrees()
print(orientation)
acceleration = sense.get_accelerometer()
compass = sense.get_compass()
temperature_from_humidity = sense.get_temperature()
temperature_from_pressure = sense.get_temperature_from_pressure()
db.gyroscope.insert_one({
"pitch": orientation["pitch"],
"roll": orientation["roll"],
"yaw": orientation["yaw"]
})
db.accelerometer.insert_one({
"pitch": acceleration["pitch"],
"roll": acceleration["roll"],
"yaw": acceleration["yaw"]
})
db.compass.insert_one({"angle": compass})
db.temperature.insert_one({
"from_humidity": temperature_from_humidity,
"from_pressure": temperature_from_pressure
})
time.sleep(DELAY)
## Instruction:
Read samples faster but log only once a second
## Code After:
from sense_hat import SenseHat
from pymongo import MongoClient
from datetime import datetime
sense = SenseHat()
client = MongoClient("mongodb://10.0.1.25:27017")
db = client.g2x
last_time = datetime.utcnow()
sample_count = 0
while True:
current_time = datetime.utcnow()
elapsed_time = current_time - last_time
orientation = sense.get_orientation()
gyroscope = sense.get_gyroscope()
acceleration = sense.get_accelerometer()
compass = sense.get_compass()
temperature_from_humidity = sense.get_temperature()
temperature_from_pressure = sense.get_temperature_from_pressure()
sample_count += 1
if elapsed_time.seconds >= 1:
last_time = current_time
print("sample per second =", sample_count)
print("orientation =", orientation)
print("gyroscope =", gyroscope)
print("acceleration =", acceleration)
print("compass =", compass)
print("temperature_from_humidity =", temperature_from_humidity)
print("temperature_from_pressure =", temperature_from_pressure)
sample_count = 0
db.orientation.insert_one({
"pitch": orientation["pitch"],
"roll": orientation["roll"],
"yaw": orientation["yaw"]
})
db.gyroscope.insert_one({
"pitch": gyroscope["pitch"],
"roll": gyroscope["roll"],
"yaw": gyroscope["yaw"]
})
db.accelerometer.insert_one({
"pitch": acceleration["pitch"],
"roll": acceleration["roll"],
"yaw": acceleration["yaw"]
})
db.compass.insert_one({"angle": compass})
db.temperature.insert_one({
"from_humidity": temperature_from_humidity,
"from_pressure": temperature_from_pressure
})
|
// ... existing code ...
from sense_hat import SenseHat
from pymongo import MongoClient
from datetime import datetime
sense = SenseHat()
client = MongoClient("mongodb://10.0.1.25:27017")
db = client.g2x
last_time = datetime.utcnow()
sample_count = 0
while True:
current_time = datetime.utcnow()
elapsed_time = current_time - last_time
orientation = sense.get_orientation()
gyroscope = sense.get_gyroscope()
acceleration = sense.get_accelerometer()
compass = sense.get_compass()
temperature_from_humidity = sense.get_temperature()
temperature_from_pressure = sense.get_temperature_from_pressure()
sample_count += 1
if elapsed_time.seconds >= 1:
last_time = current_time
print("sample per second =", sample_count)
print("orientation =", orientation)
print("gyroscope =", gyroscope)
print("acceleration =", acceleration)
print("compass =", compass)
print("temperature_from_humidity =", temperature_from_humidity)
print("temperature_from_pressure =", temperature_from_pressure)
sample_count = 0
db.orientation.insert_one({
"pitch": orientation["pitch"],
"roll": orientation["roll"],
"yaw": orientation["yaw"]
})
db.gyroscope.insert_one({
"pitch": gyroscope["pitch"],
"roll": gyroscope["roll"],
"yaw": gyroscope["yaw"]
})
db.accelerometer.insert_one({
"pitch": acceleration["pitch"],
"roll": acceleration["roll"],
"yaw": acceleration["yaw"]
})
db.compass.insert_one({"angle": compass})
db.temperature.insert_one({
"from_humidity": temperature_from_humidity,
"from_pressure": temperature_from_pressure
})
// ... rest of the code ...
|
736fe6559d6bf5143329f7419cbfdc83d759677b
|
trunk/core/jbehave-core/src/behaviour/java/org/jbehave/scenario/definition/ExamplesTableBehaviour.java
|
trunk/core/jbehave-core/src/behaviour/java/org/jbehave/scenario/definition/ExamplesTableBehaviour.java
|
package org.jbehave.scenario.definition;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ExamplesTableBehaviour {
@Test
public void shouldParseTableIntoHeadersAndRows() {
String tableAsString = "|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
ensureTableContentIsParsed(new ExamplesTable(tableAsString));
}
@Test
public void shouldTrimTableBeforeParsing() {
String tableAsString = "|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
ensureTableContentIsParsed(new ExamplesTable("\n \n" +tableAsString + "\n \n"));
}
private void ensureTableContentIsParsed(ExamplesTable table) {
assertEquals(asList("one", "two"), table.getHeaders());
assertEquals(2, table.getRows().size());
assertEquals("11", tableElement(table, 0, "one"));
assertEquals("12", tableElement(table, 0, "two"));
assertEquals("21", tableElement(table, 1, "one"));
assertEquals("22", tableElement(table, 1, "two"));
}
private String tableElement(ExamplesTable table, int row, String header) {
return table.getRow(row).get(header);
}
}
|
package org.jbehave.scenario.definition;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ExamplesTableBehaviour {
String tableAsString =
"|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
@Test
public void shouldParseTableIntoHeadersAndRows() {
ExamplesTable table = new ExamplesTable(tableAsString);
ensureTableContentIsParsed(table);
assertEquals(tableAsString, table.toString());
}
@Test
public void shouldTrimTableBeforeParsing() {
String untrimmedTableAsString = "\n \n" +tableAsString + "\n \n";
ExamplesTable table = new ExamplesTable(untrimmedTableAsString);
ensureTableContentIsParsed(table);
assertEquals(untrimmedTableAsString, table.toString());
}
private void ensureTableContentIsParsed(ExamplesTable table) {
assertEquals(asList("one", "two"), table.getHeaders());
assertEquals(2, table.getRows().size());
assertEquals("11", tableElement(table, 0, "one"));
assertEquals("12", tableElement(table, 0, "two"));
assertEquals("21", tableElement(table, 1, "one"));
assertEquals("22", tableElement(table, 1, "two"));
}
private String tableElement(ExamplesTable table, int row, String header) {
return table.getRow(row).get(header);
}
}
|
Verify content of table as string.
|
JBEHAVE-243: Verify content of table as string.
git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@1570 df8dfae0-ecdd-0310-b8d8-a050f7ac8317
|
Java
|
bsd-3-clause
|
codehaus/jbehave-git,codehaus/jbehave-git,codehaus/jbehave-git
|
java
|
## Code Before:
package org.jbehave.scenario.definition;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ExamplesTableBehaviour {
@Test
public void shouldParseTableIntoHeadersAndRows() {
String tableAsString = "|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
ensureTableContentIsParsed(new ExamplesTable(tableAsString));
}
@Test
public void shouldTrimTableBeforeParsing() {
String tableAsString = "|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
ensureTableContentIsParsed(new ExamplesTable("\n \n" +tableAsString + "\n \n"));
}
private void ensureTableContentIsParsed(ExamplesTable table) {
assertEquals(asList("one", "two"), table.getHeaders());
assertEquals(2, table.getRows().size());
assertEquals("11", tableElement(table, 0, "one"));
assertEquals("12", tableElement(table, 0, "two"));
assertEquals("21", tableElement(table, 1, "one"));
assertEquals("22", tableElement(table, 1, "two"));
}
private String tableElement(ExamplesTable table, int row, String header) {
return table.getRow(row).get(header);
}
}
## Instruction:
JBEHAVE-243: Verify content of table as string.
git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@1570 df8dfae0-ecdd-0310-b8d8-a050f7ac8317
## Code After:
package org.jbehave.scenario.definition;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ExamplesTableBehaviour {
String tableAsString =
"|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
@Test
public void shouldParseTableIntoHeadersAndRows() {
ExamplesTable table = new ExamplesTable(tableAsString);
ensureTableContentIsParsed(table);
assertEquals(tableAsString, table.toString());
}
@Test
public void shouldTrimTableBeforeParsing() {
String untrimmedTableAsString = "\n \n" +tableAsString + "\n \n";
ExamplesTable table = new ExamplesTable(untrimmedTableAsString);
ensureTableContentIsParsed(table);
assertEquals(untrimmedTableAsString, table.toString());
}
private void ensureTableContentIsParsed(ExamplesTable table) {
assertEquals(asList("one", "two"), table.getHeaders());
assertEquals(2, table.getRows().size());
assertEquals("11", tableElement(table, 0, "one"));
assertEquals("12", tableElement(table, 0, "two"));
assertEquals("21", tableElement(table, 1, "one"));
assertEquals("22", tableElement(table, 1, "two"));
}
private String tableElement(ExamplesTable table, int row, String header) {
return table.getRow(row).get(header);
}
}
|
# ... existing code ...
import org.junit.Test;
public class ExamplesTableBehaviour {
String tableAsString =
"|one|two|\n" +
"|11|12|\n" +
"|21|22|\n";
@Test
public void shouldParseTableIntoHeadersAndRows() {
ExamplesTable table = new ExamplesTable(tableAsString);
ensureTableContentIsParsed(table);
assertEquals(tableAsString, table.toString());
}
@Test
public void shouldTrimTableBeforeParsing() {
String untrimmedTableAsString = "\n \n" +tableAsString + "\n \n";
ExamplesTable table = new ExamplesTable(untrimmedTableAsString);
ensureTableContentIsParsed(table);
assertEquals(untrimmedTableAsString, table.toString());
}
private void ensureTableContentIsParsed(ExamplesTable table) {
# ... rest of the code ...
|
f7629773ce822641fcb918f68c4c47d79c90f903
|
Artsy/Classes/Views/ARArtworkRelatedArtworksView.h
|
Artsy/Classes/Views/ARArtworkRelatedArtworksView.h
|
typedef NS_ENUM(NSInteger, ARRelatedArtworksSubviewOrder) {
ARRelatedArtworksSameShow = 1,
ARRelatedArtworksSameFair,
ARRelatedArtworksSameAuction,
ARRelatedArtworksArtistArtworks,
ARRelatedArtworks,
};
@class ARArtworkRelatedArtworksView;
@protocol ARArtworkRelatedArtworksViewParentViewController <NSObject>
@required
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view shouldShowViewController:(UIViewController *)viewController;
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view didAddSection:(UIView *)section;
@optional
- (Fair *)fair;
@end
@interface ARArtworkRelatedArtworksView : ORTagBasedAutoStackView <ARArtworkMasonryLayoutProvider>
@property (nonatomic, weak) ARArtworkViewController<ARArtworkRelatedArtworksViewParentViewController> *parentViewController;
- (void)cancelRequests;
- (void)updateWithArtwork:(Artwork *)artwork;
- (void)updateWithArtwork:(Artwork *)artwork withCompletion:(void(^)())completion;
// TODO make all these private
// Use this when showing an artwork in the context of a fair.
- (void)addSectionsForFair:(Fair *)fair;
// Use this when showing an artwork in the context of a show.
- (void)addSectionsForShow:(PartnerShow *)show;
// Use this when showing an artwork in the context of an auction.
- (void)addSectionsForAuction:(Sale *)auction;
// In all other cases, this should be used to simply show related artworks.
- (void)addSectionWithRelatedArtworks;
@end
|
typedef NS_ENUM(NSInteger, ARRelatedArtworksSubviewOrder) {
ARRelatedArtworksSameShow = 1,
ARRelatedArtworksSameFair,
ARRelatedArtworksSameAuction,
ARRelatedArtworksArtistArtworks,
ARRelatedArtworks,
};
@class ARArtworkRelatedArtworksView;
@protocol ARArtworkRelatedArtworksViewParentViewController <NSObject>
@required
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view shouldShowViewController:(UIViewController *)viewController;
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view didAddSection:(UIView *)section;
@optional
- (Fair *)fair;
@end
@interface ARArtworkRelatedArtworksView : ORTagBasedAutoStackView <ARArtworkMasonryLayoutProvider>
@property (nonatomic, weak) ARArtworkViewController<ARArtworkRelatedArtworksViewParentViewController> *parentViewController;
- (void)cancelRequests;
- (void)updateWithArtwork:(Artwork *)artwork;
- (void)updateWithArtwork:(Artwork *)artwork withCompletion:(void(^)())completion;
@end
|
Make adding related works sections private.
|
[Artwork] Make adding related works sections private.
|
C
|
mit
|
1aurabrown/eigen,artsy/eigen,Havi4/eigen,artsy/eigen,mbogh/eigen,TribeMedia/eigen,gaurav1981/eigen,Havi4/eigen,artsy/eigen,ichu501/eigen,sarahscott/eigen,orta/eigen,ichu501/eigen,gaurav1981/eigen,ashkan18/eigen,ayunav/eigen,liduanw/eigen,ACChe/eigen,artsy/eigen,artsy/eigen,foxsofter/eigen,Shawn-WangDapeng/eigen,ayunav/eigen,ppamorim/eigen,srrvnn/eigen,liduanw/eigen,1aurabrown/eigen,neonichu/eigen,TribeMedia/eigen,ashkan18/eigen,Shawn-WangDapeng/eigen,artsy/eigen,1aurabrown/eigen,liduanw/eigen,TribeMedia/eigen,Shawn-WangDapeng/eigen,liduanw/eigen,Havi4/eigen,xxclouddd/eigen,ppamorim/eigen,Havi4/eigen,xxclouddd/eigen,ashkan18/eigen,ACChe/eigen,gaurav1981/eigen,sarahscott/eigen,neonichu/eigen,liduanw/eigen,ichu501/eigen,mbogh/eigen,ppamorim/eigen,foxsofter/eigen,ayunav/eigen,orta/eigen,srrvnn/eigen,ayunav/eigen,xxclouddd/eigen,sarahscott/eigen,TribeMedia/eigen,foxsofter/eigen,ichu501/eigen,Shawn-WangDapeng/eigen,mbogh/eigen,zhuzhengwei/eigen,zhuzhengwei/eigen,ACChe/eigen,xxclouddd/eigen,neonichu/eigen,srrvnn/eigen,gaurav1981/eigen,ayunav/eigen,1aurabrown/eigen,srrvnn/eigen,ashkan18/eigen,srrvnn/eigen,orta/eigen,ACChe/eigen,ichu501/eigen,artsy/eigen,foxsofter/eigen,zhuzhengwei/eigen,foxsofter/eigen,sarahscott/eigen,xxclouddd/eigen,Shawn-WangDapeng/eigen,ashkan18/eigen,mbogh/eigen,gaurav1981/eigen,neonichu/eigen,ppamorim/eigen,zhuzhengwei/eigen,ACChe/eigen,neonichu/eigen,TribeMedia/eigen,orta/eigen
|
c
|
## Code Before:
typedef NS_ENUM(NSInteger, ARRelatedArtworksSubviewOrder) {
ARRelatedArtworksSameShow = 1,
ARRelatedArtworksSameFair,
ARRelatedArtworksSameAuction,
ARRelatedArtworksArtistArtworks,
ARRelatedArtworks,
};
@class ARArtworkRelatedArtworksView;
@protocol ARArtworkRelatedArtworksViewParentViewController <NSObject>
@required
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view shouldShowViewController:(UIViewController *)viewController;
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view didAddSection:(UIView *)section;
@optional
- (Fair *)fair;
@end
@interface ARArtworkRelatedArtworksView : ORTagBasedAutoStackView <ARArtworkMasonryLayoutProvider>
@property (nonatomic, weak) ARArtworkViewController<ARArtworkRelatedArtworksViewParentViewController> *parentViewController;
- (void)cancelRequests;
- (void)updateWithArtwork:(Artwork *)artwork;
- (void)updateWithArtwork:(Artwork *)artwork withCompletion:(void(^)())completion;
// TODO make all these private
// Use this when showing an artwork in the context of a fair.
- (void)addSectionsForFair:(Fair *)fair;
// Use this when showing an artwork in the context of a show.
- (void)addSectionsForShow:(PartnerShow *)show;
// Use this when showing an artwork in the context of an auction.
- (void)addSectionsForAuction:(Sale *)auction;
// In all other cases, this should be used to simply show related artworks.
- (void)addSectionWithRelatedArtworks;
@end
## Instruction:
[Artwork] Make adding related works sections private.
## Code After:
typedef NS_ENUM(NSInteger, ARRelatedArtworksSubviewOrder) {
ARRelatedArtworksSameShow = 1,
ARRelatedArtworksSameFair,
ARRelatedArtworksSameAuction,
ARRelatedArtworksArtistArtworks,
ARRelatedArtworks,
};
@class ARArtworkRelatedArtworksView;
@protocol ARArtworkRelatedArtworksViewParentViewController <NSObject>
@required
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view shouldShowViewController:(UIViewController *)viewController;
- (void)relatedArtworksView:(ARArtworkRelatedArtworksView *)view didAddSection:(UIView *)section;
@optional
- (Fair *)fair;
@end
@interface ARArtworkRelatedArtworksView : ORTagBasedAutoStackView <ARArtworkMasonryLayoutProvider>
@property (nonatomic, weak) ARArtworkViewController<ARArtworkRelatedArtworksViewParentViewController> *parentViewController;
- (void)cancelRequests;
- (void)updateWithArtwork:(Artwork *)artwork;
- (void)updateWithArtwork:(Artwork *)artwork withCompletion:(void(^)())completion;
@end
|
// ... existing code ...
- (void)updateWithArtwork:(Artwork *)artwork;
- (void)updateWithArtwork:(Artwork *)artwork withCompletion:(void(^)())completion;
@end
// ... rest of the code ...
|
e1a9f02051038270cdf3377c38c650a27bd65507
|
apps/organizations/middleware.py
|
apps/organizations/middleware.py
|
from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
if subdomain is None:
request.organization = None
return
organization = get_object_or_404(
Organization, slug__iexact=subdomain.lower()
)
if user.is_authenticated() and organization != user.organization:
raise Http404
request.organization = organization
|
from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
request.organization = None
if subdomain is None:
request.organization = None
return
organization = get_object_or_404(
Organization, slug__iexact=subdomain.lower()
)
if user.is_authenticated() and organization != user.organization:
raise Http404
request.organization = organization
|
Set requestion organization to none
|
Set requestion organization to none
|
Python
|
mit
|
xobb1t/ddash2013,xobb1t/ddash2013
|
python
|
## Code Before:
from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
if subdomain is None:
request.organization = None
return
organization = get_object_or_404(
Organization, slug__iexact=subdomain.lower()
)
if user.is_authenticated() and organization != user.organization:
raise Http404
request.organization = organization
## Instruction:
Set requestion organization to none
## Code After:
from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
request.organization = None
if subdomain is None:
request.organization = None
return
organization = get_object_or_404(
Organization, slug__iexact=subdomain.lower()
)
if user.is_authenticated() and organization != user.organization:
raise Http404
request.organization = organization
|
# ... existing code ...
def process_request(self, request):
subdomain = request.subdomain
user = request.user
request.organization = None
if subdomain is None:
request.organization = None
# ... rest of the code ...
|
48b8efabd11a44dfabcd91f6744858535ddfb498
|
djangosaml2/templatetags/idplist.py
|
djangosaml2/templatetags/idplist.py
|
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
self.conf = config_settings_loader()
def render(self, context):
context[self.variable_name] = self.conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
def render(self, context):
conf = config_settings_loader()
context[self.variable_name] = conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
|
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
|
Python
|
apache-2.0
|
GradConnection/djangosaml2,advisory/djangosaml2_tenant,WiserTogether/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,Gagnavarslan/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,City-of-Helsinki/djangosaml2,City-of-Helsinki/djangosaml2
|
python
|
## Code Before:
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
self.conf = config_settings_loader()
def render(self, context):
context[self.variable_name] = self.conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
## Instruction:
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
## Code After:
from django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
def render(self, context):
conf = config_settings_loader()
context[self.variable_name] = conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
# ... existing code ...
def __init__(self, variable_name):
self.variable_name = variable_name
def render(self, context):
conf = config_settings_loader()
context[self.variable_name] = conf.get_available_idps()
return ''
# ... rest of the code ...
|
9c848315eba6580249d1f9fc5b598a08ec818fed
|
tests/test_functions.py
|
tests/test_functions.py
|
"""This module tests the TimeFunction class"""
import pytest
import pandas as pd
from tssim.functions import TimeFunction
@pytest.fixture
def ts():
"""Setup test data.
"""
periods = 10
index = pd.date_range("2017-04-12", periods=periods)
return pd.Series(range(periods), index)
def test_vectorized_no_condition(ts):
func = lambda x: x * 2
assert func(ts).equals(TimeFunction(func).generate(ts))
|
"""This module tests the TimeFunction class"""
import pandas as pd
import pytest
import tssim
@pytest.fixture
def ts():
"""Setup test data.
"""
periods = 10
index = pd.date_range("2017-04-12", periods=periods)
return pd.Series(range(periods), index)
def test_vectorized_no_condition(ts):
func = lambda x: x * 2
assert func(ts).equals(tssim.TimeFunction(func).generate(ts))
|
Update reference in TimeFunction test.
|
Update reference in TimeFunction test.
|
Python
|
mit
|
mansenfranzen/tssim
|
python
|
## Code Before:
"""This module tests the TimeFunction class"""
import pytest
import pandas as pd
from tssim.functions import TimeFunction
@pytest.fixture
def ts():
"""Setup test data.
"""
periods = 10
index = pd.date_range("2017-04-12", periods=periods)
return pd.Series(range(periods), index)
def test_vectorized_no_condition(ts):
func = lambda x: x * 2
assert func(ts).equals(TimeFunction(func).generate(ts))
## Instruction:
Update reference in TimeFunction test.
## Code After:
"""This module tests the TimeFunction class"""
import pandas as pd
import pytest
import tssim
@pytest.fixture
def ts():
"""Setup test data.
"""
periods = 10
index = pd.date_range("2017-04-12", periods=periods)
return pd.Series(range(periods), index)
def test_vectorized_no_condition(ts):
func = lambda x: x * 2
assert func(ts).equals(tssim.TimeFunction(func).generate(ts))
|
...
"""This module tests the TimeFunction class"""
import pandas as pd
import pytest
import tssim
@pytest.fixture
def ts():
...
def test_vectorized_no_condition(ts):
func = lambda x: x * 2
assert func(ts).equals(tssim.TimeFunction(func).generate(ts))
...
|
81ea1101839059cbb57011f0d1af5b06ebe3d458
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='lektor-root-relative-path',
author=u'Atsushi Suga',
author_email='[email protected]',
version='0.1',
url='http://github.com/a2csuga/lektor-root-relative-path',
license='MIT',
packages=['lektor_root_relative_path'],
description='Root relative path plugin for Lektor',
entry_points={
'lektor.plugins': [
'root-relative-path = lektor_root_relative_path:RootRelativePathPlugin',
]
}
)
|
from setuptools import setup
setup(
name='lektor-root-relative-path',
author=u'Atsushi Suga',
author_email='[email protected]',
version='0.1',
url='http://github.com/a2csuga/lektor-root-relative-path',
license='MIT',
install_requires=open('requirements.txt').read(),
packages=['lektor_root_relative_path'],
description='Root relative path plugin for Lektor',
entry_points={
'lektor.plugins': [
'root-relative-path = lektor_root_relative_path:RootRelativePathPlugin',
]
}
)
|
Add dependency, so it gets auto installed when installing the plugin.
|
Add dependency, so it gets auto installed when installing the plugin.
|
Python
|
mit
|
a2csuga/lektor-root-relative-path
|
python
|
## Code Before:
from setuptools import setup
setup(
name='lektor-root-relative-path',
author=u'Atsushi Suga',
author_email='[email protected]',
version='0.1',
url='http://github.com/a2csuga/lektor-root-relative-path',
license='MIT',
packages=['lektor_root_relative_path'],
description='Root relative path plugin for Lektor',
entry_points={
'lektor.plugins': [
'root-relative-path = lektor_root_relative_path:RootRelativePathPlugin',
]
}
)
## Instruction:
Add dependency, so it gets auto installed when installing the plugin.
## Code After:
from setuptools import setup
setup(
name='lektor-root-relative-path',
author=u'Atsushi Suga',
author_email='[email protected]',
version='0.1',
url='http://github.com/a2csuga/lektor-root-relative-path',
license='MIT',
install_requires=open('requirements.txt').read(),
packages=['lektor_root_relative_path'],
description='Root relative path plugin for Lektor',
entry_points={
'lektor.plugins': [
'root-relative-path = lektor_root_relative_path:RootRelativePathPlugin',
]
}
)
|
# ... existing code ...
version='0.1',
url='http://github.com/a2csuga/lektor-root-relative-path',
license='MIT',
install_requires=open('requirements.txt').read(),
packages=['lektor_root_relative_path'],
description='Root relative path plugin for Lektor',
entry_points={
# ... rest of the code ...
|
2d46442f70c8220b418db067570627591feccd3d
|
redef/services/src/main/java/no/deichman/services/service/Service.java
|
redef/services/src/main/java/no/deichman/services/service/Service.java
|
package no.deichman.services.service;
import java.io.UnsupportedEncodingException;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchException;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;
public interface Service {
void setRepository(Repository repository);
void updateWork(String work);
Model retrieveWorkById(String id);
Model retrieveWorkItemsById(String id);
String createWork(String work);
String createPublication(String publication);
void deleteWork(Model work);
void deletePublication(Model publication);
Model patchWork(String work, String requestBody) throws UnsupportedEncodingException, PatchException, PatchParserException;
Model retrievePublicationById(String publicationId);
Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
boolean resourceExists(String resourceUri);
}
|
package no.deichman.services.service;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;
public interface Service {
void setRepository(Repository repository);
void updateWork(String work);
Model retrieveWorkById(String id);
Model retrieveWorkItemsById(String id);
String createWork(String work);
String createPublication(String publication);
void deleteWork(Model work);
void deletePublication(Model publication);
Model patchWork(String work, String requestBody) throws PatchParserException;
Model retrievePublicationById(String publicationId);
Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
boolean resourceExists(String resourceUri);
}
|
Remove unused exceptions from signature.
|
Remove unused exceptions from signature.
|
Java
|
mit
|
digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext
|
java
|
## Code Before:
package no.deichman.services.service;
import java.io.UnsupportedEncodingException;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchException;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;
public interface Service {
void setRepository(Repository repository);
void updateWork(String work);
Model retrieveWorkById(String id);
Model retrieveWorkItemsById(String id);
String createWork(String work);
String createPublication(String publication);
void deleteWork(Model work);
void deletePublication(Model publication);
Model patchWork(String work, String requestBody) throws UnsupportedEncodingException, PatchException, PatchParserException;
Model retrievePublicationById(String publicationId);
Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
boolean resourceExists(String resourceUri);
}
## Instruction:
Remove unused exceptions from signature.
## Code After:
package no.deichman.services.service;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;
public interface Service {
void setRepository(Repository repository);
void updateWork(String work);
Model retrieveWorkById(String id);
Model retrieveWorkItemsById(String id);
String createWork(String work);
String createPublication(String publication);
void deleteWork(Model work);
void deletePublication(Model publication);
Model patchWork(String work, String requestBody) throws PatchParserException;
Model retrievePublicationById(String publicationId);
Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
boolean resourceExists(String resourceUri);
}
|
# ... existing code ...
package no.deichman.services.service;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;
# ... modified code ...
String createPublication(String publication);
void deleteWork(Model work);
void deletePublication(Model publication);
Model patchWork(String work, String requestBody) throws PatchParserException;
Model retrievePublicationById(String publicationId);
Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
boolean resourceExists(String resourceUri);
# ... rest of the code ...
|
554e06c3ee1983f4bd3fcc12e0c7cbd02343e9ad
|
edocs-app/src/main/java/com/github/aureliano/edocs/app/EdocsApp.java
|
edocs-app/src/main/java/com/github/aureliano/edocs/app/EdocsApp.java
|
package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = new EdocsApp();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
}
|
package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = instance();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
}
|
Fix GUI main frame instantiation.
|
Fix GUI main frame instantiation.
|
Java
|
mit
|
aureliano/e-docs
|
java
|
## Code Before:
package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = new EdocsApp();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
}
## Instruction:
Fix GUI main frame instantiation.
## Code After:
package com.github.aureliano.edocs.app;
import javax.swing.SwingUtilities;
import com.github.aureliano.edocs.app.gui.AppFrame;
public class EdocsApp {
private static EdocsApp instance;
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = instance();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
application.getFrame().showFrame();
}
});
}
public static EdocsApp instance() {
if (instance == null) {
instance = new EdocsApp();
}
return instance;
}
public EdocsApp() {
this.frame = new AppFrame();
}
public AppFrame getFrame() {
return this.frame;
}
}
|
...
private AppFrame frame;
public static void main(String[] args) {
final EdocsApp application = instance();
SwingUtilities.invokeLater(new Runnable() {
...
|
2d052b49151ea4fb8e0a422d8d743f49de593a04
|
filter_plugins/filterciscohash.py
|
filter_plugins/filterciscohash.py
|
import passlib.hash
class FilterModule(object):
def filters(self):
return {
'ciscohash5': self.ciscohash5,
'ciscohash7': self.ciscohash7,
'ciscohashpix': self.ciscohashpix,
'ciscohashasa': self.ciscohashasa
}
def ciscohash5(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.md5_crypt.html"""
return passlib.hash.md5_crypt.using(salt_size=4).hash(password)
def ciscohash7(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_type7.html"""
return str(passlib.hash.cisco_type7.hash(password))
def ciscohashpix(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_pix.html"""
return str(passlib.hash.cisco_pix.hash(password, user))
def ciscohashasa(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_asa.html"""
return str(passlib.hash.cisco_asa.hash(password, user))
|
import passlib.hash
# Version 1.7.0 introduced `passlib.hash.md5_crypt.using(salt_size=...)`.
try:
md5_crypt = passlib.hash.md5_crypt.using
except AttributeError:
md5_crypt = passlib.hash.md5_crypt
class FilterModule(object):
def filters(self):
return {
'ciscohash5': self.ciscohash5,
'ciscohash7': self.ciscohash7,
'ciscohashpix': self.ciscohashpix,
'ciscohashasa': self.ciscohashasa
}
def ciscohash5(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.md5_crypt.html"""
return md5_crypt(salt_size=4).hash(password)
def ciscohash7(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_type7.html"""
return passlib.hash.cisco_type7.hash(password)
def ciscohashpix(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_pix.html"""
return passlib.hash.cisco_pix.hash(password, user)
def ciscohashasa(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_asa.html"""
return passlib.hash.cisco_asa.hash(password, user)
|
Add support for Passlib versions prior to 1.7
|
Add support for Passlib versions prior to 1.7
|
Python
|
bsd-2-clause
|
mjuenema/ansible-filter-cisco-hash
|
python
|
## Code Before:
import passlib.hash
class FilterModule(object):
def filters(self):
return {
'ciscohash5': self.ciscohash5,
'ciscohash7': self.ciscohash7,
'ciscohashpix': self.ciscohashpix,
'ciscohashasa': self.ciscohashasa
}
def ciscohash5(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.md5_crypt.html"""
return passlib.hash.md5_crypt.using(salt_size=4).hash(password)
def ciscohash7(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_type7.html"""
return str(passlib.hash.cisco_type7.hash(password))
def ciscohashpix(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_pix.html"""
return str(passlib.hash.cisco_pix.hash(password, user))
def ciscohashasa(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_asa.html"""
return str(passlib.hash.cisco_asa.hash(password, user))
## Instruction:
Add support for Passlib versions prior to 1.7
## Code After:
import passlib.hash
# Version 1.7.0 introduced `passlib.hash.md5_crypt.using(salt_size=...)`.
try:
md5_crypt = passlib.hash.md5_crypt.using
except AttributeError:
md5_crypt = passlib.hash.md5_crypt
class FilterModule(object):
def filters(self):
return {
'ciscohash5': self.ciscohash5,
'ciscohash7': self.ciscohash7,
'ciscohashpix': self.ciscohashpix,
'ciscohashasa': self.ciscohashasa
}
def ciscohash5(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.md5_crypt.html"""
return md5_crypt(salt_size=4).hash(password)
def ciscohash7(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_type7.html"""
return passlib.hash.cisco_type7.hash(password)
def ciscohashpix(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_pix.html"""
return passlib.hash.cisco_pix.hash(password, user)
def ciscohashasa(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_asa.html"""
return passlib.hash.cisco_asa.hash(password, user)
|
...
import passlib.hash
# Version 1.7.0 introduced `passlib.hash.md5_crypt.using(salt_size=...)`.
try:
md5_crypt = passlib.hash.md5_crypt.using
except AttributeError:
md5_crypt = passlib.hash.md5_crypt
class FilterModule(object):
def filters(self):
...
def ciscohash5(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.md5_crypt.html"""
return md5_crypt(salt_size=4).hash(password)
def ciscohash7(self, password):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_type7.html"""
return passlib.hash.cisco_type7.hash(password)
def ciscohashpix(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_pix.html"""
return passlib.hash.cisco_pix.hash(password, user)
def ciscohashasa(self, password, user=''):
"""https://passlib.readthedocs.io/en/stable/lib/passlib.hash.cisco_asa.html"""
return passlib.hash.cisco_asa.hash(password, user)
...
|
20539f35218d24ec960e37b70927849f30c344f0
|
net/flip/flip_bitmasks.h
|
net/flip/flip_bitmasks.h
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_FLIP_FLIP_BITMASKS_H_
#define NET_FLIP_FLIP_BITMASKS_H_
namespace flip {
const int kStreamIdMask = 0x7fffffff; // StreamId mask from the FlipHeader
const int kControlFlagMask = 0x8000; // Control flag mask from the FlipHeader
const int kPriorityMask = 0xc0; // Priority mask from the SYN_FRAME
const int kLengthMask = 0xffffff; // Mask the lower 24 bits.
} // flip
#endif // NET_FLIP_FLIP_BITMASKS_H_
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_FLIP_FLIP_BITMASKS_H_
#define NET_FLIP_FLIP_BITMASKS_H_
namespace flip {
const unsigned int kStreamIdMask = 0x7fffffff; // StreamId mask from the FlipHeader
const unsigned int kControlFlagMask = 0x8000; // Control flag mask from the FlipHeader
const unsigned int kPriorityMask = 0xc0; // Priority mask from the SYN_FRAME
const unsigned int kLengthMask = 0xffffff; // Mask the lower 24 bits.
} // flip
#endif // NET_FLIP_FLIP_BITMASKS_H_
|
Fix signed vs unsigned issue
|
linux: Fix signed vs unsigned issue
Review URL: http://codereview.chromium.org/297015
git-svn-id: http://src.chromium.org/svn/trunk/src@30099 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 86a9c861257cd0e752a713d61f3f4a14473acfa2
|
C
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
c
|
## Code Before:
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_FLIP_FLIP_BITMASKS_H_
#define NET_FLIP_FLIP_BITMASKS_H_
namespace flip {
const int kStreamIdMask = 0x7fffffff; // StreamId mask from the FlipHeader
const int kControlFlagMask = 0x8000; // Control flag mask from the FlipHeader
const int kPriorityMask = 0xc0; // Priority mask from the SYN_FRAME
const int kLengthMask = 0xffffff; // Mask the lower 24 bits.
} // flip
#endif // NET_FLIP_FLIP_BITMASKS_H_
## Instruction:
linux: Fix signed vs unsigned issue
Review URL: http://codereview.chromium.org/297015
git-svn-id: http://src.chromium.org/svn/trunk/src@30099 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 86a9c861257cd0e752a713d61f3f4a14473acfa2
## Code After:
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_FLIP_FLIP_BITMASKS_H_
#define NET_FLIP_FLIP_BITMASKS_H_
namespace flip {
const unsigned int kStreamIdMask = 0x7fffffff; // StreamId mask from the FlipHeader
const unsigned int kControlFlagMask = 0x8000; // Control flag mask from the FlipHeader
const unsigned int kPriorityMask = 0xc0; // Priority mask from the SYN_FRAME
const unsigned int kLengthMask = 0xffffff; // Mask the lower 24 bits.
} // flip
#endif // NET_FLIP_FLIP_BITMASKS_H_
|
// ... existing code ...
namespace flip {
const unsigned int kStreamIdMask = 0x7fffffff; // StreamId mask from the FlipHeader
const unsigned int kControlFlagMask = 0x8000; // Control flag mask from the FlipHeader
const unsigned int kPriorityMask = 0xc0; // Priority mask from the SYN_FRAME
const unsigned int kLengthMask = 0xffffff; // Mask the lower 24 bits.
} // flip
#endif // NET_FLIP_FLIP_BITMASKS_H_
// ... rest of the code ...
|
e9171e8d77b457e2c96fca37c89d68c518bec5f7
|
src/urllib3/util/util.py
|
src/urllib3/util/util.py
|
from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.encode(encoding or "utf-8", errors=errors or "strict")
return x.encode()
def to_str(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
if isinstance(x, str):
return x
elif not isinstance(x, bytes):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.decode(encoding or "utf-8", errors=errors or "strict")
return x.decode()
def reraise(
tp: Optional[Type[BaseException]],
value: Optional[BaseException],
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
finally:
value = None
tb = None
|
from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.encode(encoding or "utf-8", errors=errors or "strict")
return x.encode()
def to_str(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
if isinstance(x, str):
return x
elif not isinstance(x, bytes):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.decode(encoding or "utf-8", errors=errors or "strict")
return x.decode()
def reraise(
tp: Optional[Type[BaseException]],
value: Optional[BaseException],
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
finally:
value = None
tb = None
|
Bring coverage back to 100%
|
Bring coverage back to 100%
All calls to reraise() are in branches where value is truthy, so we
can't reach that code.
|
Python
|
mit
|
sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3,urllib3/urllib3
|
python
|
## Code Before:
from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.encode(encoding or "utf-8", errors=errors or "strict")
return x.encode()
def to_str(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
if isinstance(x, str):
return x
elif not isinstance(x, bytes):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.decode(encoding or "utf-8", errors=errors or "strict")
return x.decode()
def reraise(
tp: Optional[Type[BaseException]],
value: Optional[BaseException],
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
finally:
value = None
tb = None
## Instruction:
Bring coverage back to 100%
All calls to reraise() are in branches where value is truthy, so we
can't reach that code.
## Code After:
from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.encode(encoding or "utf-8", errors=errors or "strict")
return x.encode()
def to_str(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
if isinstance(x, str):
return x
elif not isinstance(x, bytes):
raise TypeError(f"not expecting type {type(x).__name__}")
elif encoding or errors:
return x.decode(encoding or "utf-8", errors=errors or "strict")
return x.decode()
def reraise(
tp: Optional[Type[BaseException]],
value: Optional[BaseException],
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
finally:
value = None
tb = None
|
...
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
...
|
dcb3912d2f150326df2b9534da92bffb4609be2d
|
src/main/java/org/openlmis/fulfillment/domain/ExternalStatus.java
|
src/main/java/org/openlmis/fulfillment/domain/ExternalStatus.java
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.fulfillment.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
public enum ExternalStatus {
INITIATED(1),
SUBMITTED(2),
AUTHORIZED(3),
APPROVED(4),
RELEASED(5),
SKIPPED(-1);
private int value;
ExternalStatus(int value) {
this.value = value;
}
@JsonIgnore
public boolean isPreAuthorize() {
return value == 1 || value == 2;
}
@JsonIgnore
public boolean isPostSubmitted() {
return value >= 2;
}
}
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.fulfillment.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
public enum ExternalStatus {
INITIATED(1),
SUBMITTED(2),
AUTHORIZED(3),
IN_APPROVAL(4),
APPROVED(5),
RELEASED(6),
SKIPPED(-1);
private int value;
ExternalStatus(int value) {
this.value = value;
}
@JsonIgnore
public boolean isPreAuthorize() {
return value == 1 || value == 2;
}
@JsonIgnore
public boolean isPostSubmitted() {
return value >= 2;
}
}
|
Add IN_APPROVAL to list of statuses
|
Add IN_APPROVAL to list of statuses
To match requisition statuses.
|
Java
|
agpl-3.0
|
OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment
|
java
|
## Code Before:
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.fulfillment.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
public enum ExternalStatus {
INITIATED(1),
SUBMITTED(2),
AUTHORIZED(3),
APPROVED(4),
RELEASED(5),
SKIPPED(-1);
private int value;
ExternalStatus(int value) {
this.value = value;
}
@JsonIgnore
public boolean isPreAuthorize() {
return value == 1 || value == 2;
}
@JsonIgnore
public boolean isPostSubmitted() {
return value >= 2;
}
}
## Instruction:
Add IN_APPROVAL to list of statuses
To match requisition statuses.
## Code After:
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.fulfillment.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
public enum ExternalStatus {
INITIATED(1),
SUBMITTED(2),
AUTHORIZED(3),
IN_APPROVAL(4),
APPROVED(5),
RELEASED(6),
SKIPPED(-1);
private int value;
ExternalStatus(int value) {
this.value = value;
}
@JsonIgnore
public boolean isPreAuthorize() {
return value == 1 || value == 2;
}
@JsonIgnore
public boolean isPostSubmitted() {
return value >= 2;
}
}
|
...
INITIATED(1),
SUBMITTED(2),
AUTHORIZED(3),
IN_APPROVAL(4),
APPROVED(5),
RELEASED(6),
SKIPPED(-1);
private int value;
...
|
0f4982691eaf60f6b23e9f7d02c63ee3b9cb0460
|
xlat.h
|
xlat.h
|
struct xlat {
unsigned int val;
const char *str;
};
# define XLAT(val) { (unsigned)(val), #val }
# define XLAT_PAIR(val, str) { (unsigned)(val), str }
# define XLAT_END { 0, 0 }
#endif
|
struct xlat {
unsigned int val;
const char *str;
};
# define XLAT(val) { (unsigned)(val), #val }
# define XLAT_PAIR(val, str) { (unsigned)(val), str }
# define XLAT_TYPE(type, val) { (type)(val), #val }
# define XLAT_TYPE_PAIR(val, str) { (type)(val), str }
# define XLAT_END { 0, 0 }
#endif
|
Introduce XLAT_TYPE and XLAT_TYPE_PAIR macros
|
Introduce XLAT_TYPE and XLAT_TYPE_PAIR macros
* xlat.h (XLAT_TYPE): New macro, similar to XLAT but casts
to the specified type instead of unsigned int.
(XLAT_TYPE_PAIR): New macro, similar to XLAT_PAIR but casts
to the specified type instead of unsigned int.
|
C
|
bsd-3-clause
|
Saruta/strace,Saruta/strace,cuviper/strace,Saruta/strace,Saruta/strace,cuviper/strace,Saruta/strace,cuviper/strace,cuviper/strace,cuviper/strace
|
c
|
## Code Before:
struct xlat {
unsigned int val;
const char *str;
};
# define XLAT(val) { (unsigned)(val), #val }
# define XLAT_PAIR(val, str) { (unsigned)(val), str }
# define XLAT_END { 0, 0 }
#endif
## Instruction:
Introduce XLAT_TYPE and XLAT_TYPE_PAIR macros
* xlat.h (XLAT_TYPE): New macro, similar to XLAT but casts
to the specified type instead of unsigned int.
(XLAT_TYPE_PAIR): New macro, similar to XLAT_PAIR but casts
to the specified type instead of unsigned int.
## Code After:
struct xlat {
unsigned int val;
const char *str;
};
# define XLAT(val) { (unsigned)(val), #val }
# define XLAT_PAIR(val, str) { (unsigned)(val), str }
# define XLAT_TYPE(type, val) { (type)(val), #val }
# define XLAT_TYPE_PAIR(val, str) { (type)(val), str }
# define XLAT_END { 0, 0 }
#endif
|
# ... existing code ...
# define XLAT(val) { (unsigned)(val), #val }
# define XLAT_PAIR(val, str) { (unsigned)(val), str }
# define XLAT_TYPE(type, val) { (type)(val), #val }
# define XLAT_TYPE_PAIR(val, str) { (type)(val), str }
# define XLAT_END { 0, 0 }
#endif
# ... rest of the code ...
|
e5beaabc66cbb87f63e2648b277bada72ddec7dc
|
tests/conftest.py
|
tests/conftest.py
|
import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param)
|
import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param, unsafe=True)
|
Allow unsafe change of backend for testing
|
Allow unsafe change of backend for testing
|
Python
|
bsd-2-clause
|
FilipeMaia/afnumpy,daurer/afnumpy
|
python
|
## Code Before:
import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param)
## Instruction:
Allow unsafe change of backend for testing
## Code After:
import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param, unsafe=True)
|
// ... existing code ...
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
def set_backend(request):
arrayfire.library.set_backend(request.param, unsafe=True)
// ... rest of the code ...
|
cdefa6cb4a91cbbac5d2680fe2e116a2a4ebb86b
|
recipe_scrapers/allrecipes.py
|
recipe_scrapers/allrecipes.py
|
from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and type(author) == list and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
|
from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and isinstance(author, list) and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
|
Use 'isinstance' in preference to 'type' method
|
Use 'isinstance' in preference to 'type' method
|
Python
|
mit
|
hhursev/recipe-scraper
|
python
|
## Code Before:
from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and type(author) == list and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
## Instruction:
Use 'isinstance' in preference to 'type' method
## Code After:
from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and isinstance(author, list) and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
|
// ... existing code ...
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and isinstance(author, list) and len(author) == 1:
return author[0].get("name")
def title(self):
// ... rest of the code ...
|
294b1c4d398c5f6a01323e18e53d9ab1d1e1a732
|
web/mooctracker/api/views.py
|
web/mooctracker/api/views.py
|
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request,id=0):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
elif request.method == 'DELETE':
Student.objects.get(id=id).delete()
message={ 'success' : 'True' }
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
# POST method
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
#DELETE Method
elif request.method == 'DELETE':
requestJson = json.loads(request.body)
sid = requestJson['id']
Student.objects.get(id=sid).delete()
message={ 'success' : 'True', 'id': sid}
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
DELETE method added to api
|
DELETE method added to api
|
Python
|
mit
|
Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker
|
python
|
## Code Before:
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request,id=0):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
elif request.method == 'DELETE':
Student.objects.get(id=id).delete()
message={ 'success' : 'True' }
return HttpResponse(
json.dumps(message),
content_type='application/json')
## Instruction:
DELETE method added to api
## Code After:
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
# POST method
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
#DELETE Method
elif request.method == 'DELETE':
requestJson = json.loads(request.body)
sid = requestJson['id']
Student.objects.get(id=sid).delete()
message={ 'success' : 'True', 'id': sid}
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
# ... existing code ...
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
# ... modified code ...
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
# POST method
elif request.method == 'POST':
requestJson = json.loads(request.body)
...
json.dumps(addedStudent),
content_type='application/json')
#DELETE Method
elif request.method == 'DELETE':
requestJson = json.loads(request.body)
sid = requestJson['id']
Student.objects.get(id=sid).delete()
message={ 'success' : 'True', 'id': sid}
return HttpResponse(
json.dumps(message),
content_type='application/json')
# ... rest of the code ...
|
3fe0313d67857ec302cc20e0cdc30d658e41dd97
|
troposphere/ecr.py
|
troposphere/ecr.py
|
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
|
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class PublicRepository(AWSObject):
resource_type = "AWS::ECR::PublicRepository"
props = {
'RepositoryCatalogData': (dict, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
class RegistryPolicy(AWSObject):
resource_type = "AWS::ECR::RegistryPolicy"
props = {
'PolicyText': (policytypes, True),
}
class ReplicationDestination(AWSProperty):
props = {
'Region': (basestring, True),
'RegistryId': (basestring, True),
}
class ReplicationRule(AWSProperty):
props = {
'Destinations': ([ReplicationDestination], True),
}
class ReplicationConfigurationProperty(AWSProperty):
props = {
'Rules': ([ReplicationRule], True),
}
class ReplicationConfiguration(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ReplicationConfigurationProperty':
(ReplicationConfigurationProperty, True),
}
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
|
Update ECR per 2020-12-18 and 2021-02-04 changes
|
Update ECR per 2020-12-18 and 2021-02-04 changes
|
Python
|
bsd-2-clause
|
cloudtools/troposphere,cloudtools/troposphere
|
python
|
## Code Before:
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
## Instruction:
Update ECR per 2020-12-18 and 2021-02-04 changes
## Code After:
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class PublicRepository(AWSObject):
resource_type = "AWS::ECR::PublicRepository"
props = {
'RepositoryCatalogData': (dict, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
class RegistryPolicy(AWSObject):
resource_type = "AWS::ECR::RegistryPolicy"
props = {
'PolicyText': (policytypes, True),
}
class ReplicationDestination(AWSProperty):
props = {
'Region': (basestring, True),
'RegistryId': (basestring, True),
}
class ReplicationRule(AWSProperty):
props = {
'Destinations': ([ReplicationDestination], True),
}
class ReplicationConfigurationProperty(AWSProperty):
props = {
'Rules': ([ReplicationRule], True),
}
class ReplicationConfiguration(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ReplicationConfigurationProperty':
(ReplicationConfigurationProperty, True),
}
class LifecyclePolicy(AWSProperty):
props = {
'LifecyclePolicyText': (basestring, False),
'RegistryId': (basestring, False),
}
class Repository(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ImageScanningConfiguration': (dict, False),
'ImageTagMutability': (basestring, False),
'LifecyclePolicy': (LifecyclePolicy, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
|
# ... existing code ...
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
class PublicRepository(AWSObject):
resource_type = "AWS::ECR::PublicRepository"
props = {
'RepositoryCatalogData': (dict, False),
'RepositoryName': (basestring, False),
'RepositoryPolicyText': (policytypes, False),
'Tags': (Tags, False),
}
class RegistryPolicy(AWSObject):
resource_type = "AWS::ECR::RegistryPolicy"
props = {
'PolicyText': (policytypes, True),
}
class ReplicationDestination(AWSProperty):
props = {
'Region': (basestring, True),
'RegistryId': (basestring, True),
}
class ReplicationRule(AWSProperty):
props = {
'Destinations': ([ReplicationDestination], True),
}
class ReplicationConfigurationProperty(AWSProperty):
props = {
'Rules': ([ReplicationRule], True),
}
class ReplicationConfiguration(AWSObject):
resource_type = "AWS::ECR::Repository"
props = {
'ReplicationConfigurationProperty':
(ReplicationConfigurationProperty, True),
}
class LifecyclePolicy(AWSProperty):
# ... rest of the code ...
|
2b933faaf2f9aba9158d56c49367e423ea1a2ea3
|
pelican/plugins/related_posts.py
|
pelican/plugins/related_posts.py
|
from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
for tag in metadata['tags']:
#print tag
for related_article in generator.tags[tag]:
related_posts.append(related_article)
if len(related_posts) < 1:
return
relation_score = dict( \
zip(set(related_posts), \
map(related_posts.count, \
set(related_posts))))
ranked_related = sorted(relation_score, key=relation_score.get)
metadata["related_posts"] = ranked_related[:5]
else:
return
def register():
signals.article_generate_context.connect(add_related_posts)
|
from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
Settings
--------
To enable, add
from pelican.plugins import related_posts
PLUGINS = [related_posts]
to your settings.py.
Usage
-----
{% if article.related_posts %}
<ul>
{% for related_post in article.related_posts %}
<li>{{ related_post }}</li>
{% endfor %}
</ul>
{% endif %}
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
for tag in metadata['tags']:
#print tag
for related_article in generator.tags[tag]:
related_posts.append(related_article)
if len(related_posts) < 1:
return
relation_score = dict( \
zip(set(related_posts), \
map(related_posts.count, \
set(related_posts))))
ranked_related = sorted(relation_score, key=relation_score.get)
metadata["related_posts"] = ranked_related[:5]
else:
return
def register():
signals.article_generate_context.connect(add_related_posts)
|
Add usage and intallation instructions
|
Add usage and intallation instructions
|
Python
|
agpl-3.0
|
alexras/pelican,HyperGroups/pelican,jvehent/pelican,11craft/pelican,51itclub/pelican,number5/pelican,avaris/pelican,treyhunner/pelican,number5/pelican,deved69/pelican-1,lazycoder-ru/pelican,Polyconseil/pelican,simonjj/pelican,ehashman/pelican,koobs/pelican,florianjacob/pelican,joetboole/pelican,sunzhongwei/pelican,GiovanniMoretti/pelican,Summonee/pelican,Scheirle/pelican,rbarraud/pelican,jimperio/pelican,karlcow/pelican,ls2uper/pelican,lazycoder-ru/pelican,janaurka/git-debug-presentiation,catdog2/pelican,GiovanniMoretti/pelican,JeremyMorgan/pelican,zackw/pelican,levanhien8/pelican,levanhien8/pelican,jimperio/pelican,ehashman/pelican,liyonghelpme/myBlog,liyonghelpme/myBlog,goerz/pelican,btnpushnmunky/pelican,abrahamvarricatt/pelican,crmackay/pelican,iurisilvio/pelican,arty-name/pelican,deanishe/pelican,TC01/pelican,goerz/pelican,UdeskDeveloper/pelican,Scheirle/pelican,alexras/pelican,janaurka/git-debug-presentiation,justinmayer/pelican,farseerfc/pelican,iKevinY/pelican,jimperio/pelican,treyhunner/pelican,JeremyMorgan/pelican,karlcow/pelican,abrahamvarricatt/pelican,51itclub/pelican,11craft/pelican,talha131/pelican,Rogdham/pelican,eevee/pelican,joetboole/pelican,number5/pelican,catdog2/pelican,btnpushnmunky/pelican,lucasplus/pelican,farseerfc/pelican,HyperGroups/pelican,gymglish/pelican,11craft/pelican,deved69/pelican-1,simonjj/pelican,florianjacob/pelican,jvehent/pelican,Scheirle/pelican,getpelican/pelican,Polyconseil/pelican,kennethlyn/pelican,karlcow/pelican,eevee/pelican,douglaskastle/pelican,ls2uper/pelican,eevee/pelican,lucasplus/pelican,jo-tham/pelican,garbas/pelican,Rogdham/pelican,levanhien8/pelican,joetboole/pelican,iurisilvio/pelican,0xMF/pelican,garbas/pelican,Rogdham/pelican,florianjacob/pelican,koobs/pelican,GiovanniMoretti/pelican,simonjj/pelican,ls2uper/pelican,kernc/pelican,kernc/pelican,treyhunner/pelican,ionelmc/pelican,iKevinY/pelican,rbarraud/pelican,JeremyMorgan/pelican,HyperGroups/pelican,douglaskastle/pelican,abrahamvarricatt/pelican,crmackay/pelican,crmackay/pelican,kernc/pelican,deanishe/pelican,zackw/pelican,ehashman/pelican,lazycoder-ru/pelican,sunzhongwei/pelican,janaurka/git-debug-presentiation,talha131/pelican,rbarraud/pelican,UdeskDeveloper/pelican,deved69/pelican-1,kennethlyn/pelican,51itclub/pelican,avaris/pelican,alexras/pelican,fbs/pelican,iurisilvio/pelican,TC01/pelican,douglaskastle/pelican,TC01/pelican,kennethlyn/pelican,Summonee/pelican,ingwinlu/pelican,Summonee/pelican,sunzhongwei/pelican,jo-tham/pelican,sunzhongwei/pelican,gymglish/pelican,koobs/pelican,zackw/pelican,deanishe/pelican,liyonghelpme/myBlog,catdog2/pelican,liyonghelpme/myBlog,getpelican/pelican,garbas/pelican,UdeskDeveloper/pelican,ingwinlu/pelican,btnpushnmunky/pelican,lucasplus/pelican,Natim/pelican,gymglish/pelican,liyonghelpme/myBlog,jvehent/pelican,goerz/pelican
|
python
|
## Code Before:
from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
for tag in metadata['tags']:
#print tag
for related_article in generator.tags[tag]:
related_posts.append(related_article)
if len(related_posts) < 1:
return
relation_score = dict( \
zip(set(related_posts), \
map(related_posts.count, \
set(related_posts))))
ranked_related = sorted(relation_score, key=relation_score.get)
metadata["related_posts"] = ranked_related[:5]
else:
return
def register():
signals.article_generate_context.connect(add_related_posts)
## Instruction:
Add usage and intallation instructions
## Code After:
from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
Settings
--------
To enable, add
from pelican.plugins import related_posts
PLUGINS = [related_posts]
to your settings.py.
Usage
-----
{% if article.related_posts %}
<ul>
{% for related_post in article.related_posts %}
<li>{{ related_post }}</li>
{% endfor %}
</ul>
{% endif %}
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
for tag in metadata['tags']:
#print tag
for related_article in generator.tags[tag]:
related_posts.append(related_article)
if len(related_posts) < 1:
return
relation_score = dict( \
zip(set(related_posts), \
map(related_posts.count, \
set(related_posts))))
ranked_related = sorted(relation_score, key=relation_score.get)
metadata["related_posts"] = ranked_related[:5]
else:
return
def register():
signals.article_generate_context.connect(add_related_posts)
|
# ... existing code ...
================================
Adds related_posts variable to article's context
Settings
--------
To enable, add
from pelican.plugins import related_posts
PLUGINS = [related_posts]
to your settings.py.
Usage
-----
{% if article.related_posts %}
<ul>
{% for related_post in article.related_posts %}
<li>{{ related_post }}</li>
{% endfor %}
</ul>
{% endif %}
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
# ... rest of the code ...
|
1aca107934c5fe9e540ecab279879583515472f4
|
biz.aQute.bnd.gradle/testresources/builderplugin1/src/test/java/doubler/impl/DoublerImplTest.java
|
biz.aQute.bnd.gradle/testresources/builderplugin1/src/test/java/doubler/impl/DoublerImplTest.java
|
package doubler.impl;
import doubler.Doubler;
import org.junit.Test;
public class DoublerImplTest {
@Test
public void testIt() {
Doubler doubler = new DoublerImpl();
assert doubler.doubleIt(2) == 4;
}
}
|
package doubler.impl;
import doubler.Doubler;
import org.junit.Test;
import static org.junit.Assert.*;
public class DoublerImplTest {
@Test
public void testIt() {
Doubler doubler = new DoublerImpl();
assertEquals(4, doubler.doubleIt(2));
}
}
|
Use JUnit assert method in test case
|
gradle: Use JUnit assert method in test case
Signed-off-by: BJ Hargrave <[email protected]>
|
Java
|
apache-2.0
|
magnet/bnd,psoreide/bnd,mcculls/bnd,magnet/bnd,lostiniceland/bnd,magnet/bnd,psoreide/bnd,mcculls/bnd,mcculls/bnd,lostiniceland/bnd,psoreide/bnd,lostiniceland/bnd
|
java
|
## Code Before:
package doubler.impl;
import doubler.Doubler;
import org.junit.Test;
public class DoublerImplTest {
@Test
public void testIt() {
Doubler doubler = new DoublerImpl();
assert doubler.doubleIt(2) == 4;
}
}
## Instruction:
gradle: Use JUnit assert method in test case
Signed-off-by: BJ Hargrave <[email protected]>
## Code After:
package doubler.impl;
import doubler.Doubler;
import org.junit.Test;
import static org.junit.Assert.*;
public class DoublerImplTest {
@Test
public void testIt() {
Doubler doubler = new DoublerImpl();
assertEquals(4, doubler.doubleIt(2));
}
}
|
...
import doubler.Doubler;
import org.junit.Test;
import static org.junit.Assert.*;
public class DoublerImplTest {
@Test
public void testIt() {
Doubler doubler = new DoublerImpl();
assertEquals(4, doubler.doubleIt(2));
}
}
...
|
11741fe35b7a62effa5e07ced86946b0d744015a
|
setup.py
|
setup.py
|
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'h5py',
'numpy',
'ConfigSpace'
'pandas', # missing dependency of nasbench
'https://github.com/google-research/nasbench/archive/master.zip'
]
setup(name='profet',
version='0.0.1',
description='tabular benchmarks for feed forward neural networks',
author='Aaron Klein',
author_email='[email protected]',
keywords='hyperparameter optimization',
packages=find_packages(),
install_requires=requires)
|
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'h5py',
'numpy',
'ConfigSpace'
'pandas', # missing dependency of nasbench
'git+https://github.com/google-research/nasbench.git@master'
]
setup(name='profet',
version='0.0.1',
description='tabular benchmarks for feed forward neural networks',
author='Aaron Klein',
author_email='[email protected]',
keywords='hyperparameter optimization',
packages=find_packages(),
install_requires=requires)
|
Change nasbench dependency to git+https style.
|
Change nasbench dependency to git+https style.
|
Python
|
bsd-3-clause
|
automl/nas_benchmarks
|
python
|
## Code Before:
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'h5py',
'numpy',
'ConfigSpace'
'pandas', # missing dependency of nasbench
'https://github.com/google-research/nasbench/archive/master.zip'
]
setup(name='profet',
version='0.0.1',
description='tabular benchmarks for feed forward neural networks',
author='Aaron Klein',
author_email='[email protected]',
keywords='hyperparameter optimization',
packages=find_packages(),
install_requires=requires)
## Instruction:
Change nasbench dependency to git+https style.
## Code After:
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'h5py',
'numpy',
'ConfigSpace'
'pandas', # missing dependency of nasbench
'git+https://github.com/google-research/nasbench.git@master'
]
setup(name='profet',
version='0.0.1',
description='tabular benchmarks for feed forward neural networks',
author='Aaron Klein',
author_email='[email protected]',
keywords='hyperparameter optimization',
packages=find_packages(),
install_requires=requires)
|
...
'numpy',
'ConfigSpace'
'pandas', # missing dependency of nasbench
'git+https://github.com/google-research/nasbench.git@master'
]
setup(name='profet',
...
|
c862a4c40f17040017e9bb6f67f5b9fa293c23e5
|
mcb_interface/driver.py
|
mcb_interface/driver.py
|
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(0.1, 0)
print "Battery Voltage: ", battery_millivolts[0], " Volts."
print "Vx: ", v_x, " m/s"
print "Vtheta: ", v_theta, "rad/s"
sleep(0.01)
|
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(1.0, 0)
print "Battery Voltage: ", battery_millivolts[0], " Volts."
print "Vx: ", v_x, " m/s"
print "Vtheta: ", v_theta, "rad/s"
print "X: ", x, " Y: ", y, " Theta: ", theta
sleep(0.01)
|
Add more output printing, increase velocity command.
|
Add more output printing, increase velocity command.
|
Python
|
mit
|
waddletown/sw
|
python
|
## Code Before:
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(0.1, 0)
print "Battery Voltage: ", battery_millivolts[0], " Volts."
print "Vx: ", v_x, " m/s"
print "Vtheta: ", v_theta, "rad/s"
sleep(0.01)
## Instruction:
Add more output printing, increase velocity command.
## Code After:
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(1.0, 0)
print "Battery Voltage: ", battery_millivolts[0], " Volts."
print "Vx: ", v_x, " m/s"
print "Vtheta: ", v_theta, "rad/s"
print "X: ", x, " Y: ", y, " Theta: ", theta
sleep(0.01)
|
...
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(1.0, 0)
print "Battery Voltage: ", battery_millivolts[0], " Volts."
print "Vx: ", v_x, " m/s"
print "Vtheta: ", v_theta, "rad/s"
print "X: ", x, " Y: ", y, " Theta: ", theta
sleep(0.01)
...
|
f70eec24ef936db6318464da27dc9c619da339d3
|
scratch/asb/experiment_json_to_cbf_def.py
|
scratch/asb/experiment_json_to_cbf_def.py
|
from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Apply the header file to the cbfs with cxi.apply_metrology
# Note hardcoded distance of 105
from dials.util.command_line import Importer
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_to_basis_dict
importer = Importer(['refined_experiments.json'], check_format=False)
experiment = importer.experiments[0]
detector = experiment.detector
metro = map_detector_to_basis_dict(detector)
write_cspad_cbf(None, metro, 'cbf', None, 'quad_refined.def', None, 105, header_only=True)
print "Done"
|
from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Note hardcoded distance of 100 isn't relevant for just a cbf header
from dials.util.options import OptionParser
from dials.util.options import flatten_experiments
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_to_basis_dict
class Script(object):
def __init__(self):
# Create the parser
self.parser = OptionParser(
read_experiments=True)
def run(self):
params, options = self.parser.parse_args(show_diff_phil=True)
experiments = flatten_experiments(params.input.experiments)
detector = experiments[0].detector
metro = map_detector_to_basis_dict(detector)
write_cspad_cbf(None, metro, 'cbf', None, 'refined_detector.def', None, 100, header_only=True)
print "Done"
if __name__ == '__main__':
from dials.util import halraiser
try:
script = Script()
script.run()
except Exception as e:
halraiser(e)
|
Refactor for new OptionParser interface
|
Refactor for new OptionParser interface
|
Python
|
bsd-3-clause
|
dials/dials,dials/dials,dials/dials,dials/dials,dials/dials
|
python
|
## Code Before:
from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Apply the header file to the cbfs with cxi.apply_metrology
# Note hardcoded distance of 105
from dials.util.command_line import Importer
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_to_basis_dict
importer = Importer(['refined_experiments.json'], check_format=False)
experiment = importer.experiments[0]
detector = experiment.detector
metro = map_detector_to_basis_dict(detector)
write_cspad_cbf(None, metro, 'cbf', None, 'quad_refined.def', None, 105, header_only=True)
print "Done"
## Instruction:
Refactor for new OptionParser interface
## Code After:
from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Note hardcoded distance of 100 isn't relevant for just a cbf header
from dials.util.options import OptionParser
from dials.util.options import flatten_experiments
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_to_basis_dict
class Script(object):
def __init__(self):
# Create the parser
self.parser = OptionParser(
read_experiments=True)
def run(self):
params, options = self.parser.parse_args(show_diff_phil=True)
experiments = flatten_experiments(params.input.experiments)
detector = experiments[0].detector
metro = map_detector_to_basis_dict(detector)
write_cspad_cbf(None, metro, 'cbf', None, 'refined_detector.def', None, 100, header_only=True)
print "Done"
if __name__ == '__main__':
from dials.util import halraiser
try:
script = Script()
script.run()
except Exception as e:
halraiser(e)
|
// ... existing code ...
from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Note hardcoded distance of 100 isn't relevant for just a cbf header
from dials.util.options import OptionParser
from dials.util.options import flatten_experiments
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_to_basis_dict
class Script(object):
def __init__(self):
# Create the parser
self.parser = OptionParser(
read_experiments=True)
def run(self):
params, options = self.parser.parse_args(show_diff_phil=True)
experiments = flatten_experiments(params.input.experiments)
detector = experiments[0].detector
metro = map_detector_to_basis_dict(detector)
write_cspad_cbf(None, metro, 'cbf', None, 'refined_detector.def', None, 100, header_only=True)
print "Done"
if __name__ == '__main__':
from dials.util import halraiser
try:
script = Script()
script.run()
except Exception as e:
halraiser(e)
// ... rest of the code ...
|
94710706b818acd113d6f56c0cdaa787f13b74eb
|
content/common/gpu/surface_handle_types_mac.h
|
content/common/gpu/surface_handle_types_mac.h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#define CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#include <OpenGL/CGLIOSurface.h>
#include "base/basictypes.h"
#include "ui/base/cocoa/remote_layer_api.h"
namespace content {
// The surface handle passed between the GPU and browser process may refer to
// an IOSurface or a CAContext. These helper functions must be used to identify
// and translate between the types.
enum SurfaceHandleType {
kSurfaceHandleTypeInvalid,
kSurfaceHandleTypeIOSurface,
kSurfaceHandleTypeCAContext,
};
SurfaceHandleType GetSurfaceHandleType(uint64 surface_handle);
CAContextID CAContextIDFromSurfaceHandle(uint64 surface_handle);
IOSurfaceID IOSurfaceIDFromSurfaceHandle(uint64 surface_handle);
uint64 SurfaceHandleFromIOSurfaceID(IOSurfaceID io_surface_id);
uint64 SurfaceHandleFromCAContextID(CAContextID ca_context_id);
} // namespace content
#endif // CONTENT_COMMON_GPU_HANDLE_TYPES_MAC_H_
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#define CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#include <IOSurface/IOSurface.h>
#include <OpenGL/CGLIOSurface.h>
#include "base/basictypes.h"
#include "ui/base/cocoa/remote_layer_api.h"
namespace content {
// The surface handle passed between the GPU and browser process may refer to
// an IOSurface or a CAContext. These helper functions must be used to identify
// and translate between the types.
enum SurfaceHandleType {
kSurfaceHandleTypeInvalid,
kSurfaceHandleTypeIOSurface,
kSurfaceHandleTypeCAContext,
};
SurfaceHandleType GetSurfaceHandleType(uint64 surface_handle);
CAContextID CAContextIDFromSurfaceHandle(uint64 surface_handle);
IOSurfaceID IOSurfaceIDFromSurfaceHandle(uint64 surface_handle);
uint64 SurfaceHandleFromIOSurfaceID(IOSurfaceID io_surface_id);
uint64 SurfaceHandleFromCAContextID(CAContextID ca_context_id);
} // namespace content
#endif // CONTENT_COMMON_GPU_HANDLE_TYPES_MAC_H_
|
Fix build on OSX 10.9.
|
Fix build on OSX 10.9.
This fixes a build error on OSX 10.9 introduced by
https://codereview.chromium.org/347653005/
BUG=388160
[email protected],[email protected],[email protected]
Review URL: https://codereview.chromium.org/350833002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@279428 0039d316-1c4b-4281-b951-d872f2087c98
|
C
|
bsd-3-clause
|
crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,littlstar/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,dednal/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,ltilve/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,Just-D/chromium-1,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,ltilve/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk
|
c
|
## Code Before:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#define CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#include <OpenGL/CGLIOSurface.h>
#include "base/basictypes.h"
#include "ui/base/cocoa/remote_layer_api.h"
namespace content {
// The surface handle passed between the GPU and browser process may refer to
// an IOSurface or a CAContext. These helper functions must be used to identify
// and translate between the types.
enum SurfaceHandleType {
kSurfaceHandleTypeInvalid,
kSurfaceHandleTypeIOSurface,
kSurfaceHandleTypeCAContext,
};
SurfaceHandleType GetSurfaceHandleType(uint64 surface_handle);
CAContextID CAContextIDFromSurfaceHandle(uint64 surface_handle);
IOSurfaceID IOSurfaceIDFromSurfaceHandle(uint64 surface_handle);
uint64 SurfaceHandleFromIOSurfaceID(IOSurfaceID io_surface_id);
uint64 SurfaceHandleFromCAContextID(CAContextID ca_context_id);
} // namespace content
#endif // CONTENT_COMMON_GPU_HANDLE_TYPES_MAC_H_
## Instruction:
Fix build on OSX 10.9.
This fixes a build error on OSX 10.9 introduced by
https://codereview.chromium.org/347653005/
BUG=388160
[email protected],[email protected],[email protected]
Review URL: https://codereview.chromium.org/350833002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@279428 0039d316-1c4b-4281-b951-d872f2087c98
## Code After:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#define CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#include <IOSurface/IOSurface.h>
#include <OpenGL/CGLIOSurface.h>
#include "base/basictypes.h"
#include "ui/base/cocoa/remote_layer_api.h"
namespace content {
// The surface handle passed between the GPU and browser process may refer to
// an IOSurface or a CAContext. These helper functions must be used to identify
// and translate between the types.
enum SurfaceHandleType {
kSurfaceHandleTypeInvalid,
kSurfaceHandleTypeIOSurface,
kSurfaceHandleTypeCAContext,
};
SurfaceHandleType GetSurfaceHandleType(uint64 surface_handle);
CAContextID CAContextIDFromSurfaceHandle(uint64 surface_handle);
IOSurfaceID IOSurfaceIDFromSurfaceHandle(uint64 surface_handle);
uint64 SurfaceHandleFromIOSurfaceID(IOSurfaceID io_surface_id);
uint64 SurfaceHandleFromCAContextID(CAContextID ca_context_id);
} // namespace content
#endif // CONTENT_COMMON_GPU_HANDLE_TYPES_MAC_H_
|
// ... existing code ...
#ifndef CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#define CONTENT_COMMON_GPU_SURFACE_HANDLE_TYPES_MAC_H_
#include <IOSurface/IOSurface.h>
#include <OpenGL/CGLIOSurface.h>
#include "base/basictypes.h"
// ... rest of the code ...
|
ecef06a4970c3d6283b62be2ceeb0d8c96f039d8
|
include/llvm/Transforms/Utils/PromoteMemToReg.h
|
include/llvm/Transforms/Utils/PromoteMemToReg.h
|
//===- PromoteMemToReg.h - Promote Allocas to Scalars -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exposes an interface to promote alloca instructions to SSA
// registers, by using the SSA construction algorithm.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#define TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#include <vector>
namespace llvm {
class AllocaInst;
class DominatorTree;
class DominanceFrontier;
class AliasSetTracker;
/// isAllocaPromotable - Return true if this alloca is legal for promotion.
/// This is true if there are only loads and stores to the alloca...
///
bool isAllocaPromotable(const AllocaInst *AI);
/// PromoteMemToReg - Promote the specified list of alloca instructions into
/// scalar registers, inserting PHI nodes as appropriate. This function makes
/// use of DominanceFrontier information. This function does not modify the CFG
/// of the function at all. All allocas must be from the same function.
///
/// If AST is specified, the specified tracker is updated to reflect changes
/// made to the IR.
///
void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
DominatorTree &DT, AliasSetTracker *AST = 0);
} // End llvm namespace
#endif
|
//===- PromoteMemToReg.h - Promote Allocas to Scalars -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exposes an interface to promote alloca instructions to SSA
// registers, by using the SSA construction algorithm.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#define TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#include <vector>
namespace llvm {
class AllocaInst;
class DominatorTree;
class AliasSetTracker;
/// isAllocaPromotable - Return true if this alloca is legal for promotion.
/// This is true if there are only loads and stores to the alloca...
///
bool isAllocaPromotable(const AllocaInst *AI);
/// PromoteMemToReg - Promote the specified list of alloca instructions into
/// scalar registers, inserting PHI nodes as appropriate. This function makes
/// use of DominanceFrontier information. This function does not modify the CFG
/// of the function at all. All allocas must be from the same function.
///
/// If AST is specified, the specified tracker is updated to reflect changes
/// made to the IR.
///
void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
DominatorTree &DT, AliasSetTracker *AST = 0);
} // End llvm namespace
#endif
|
Remove a stale forward declaration.
|
Remove a stale forward declaration.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@156770 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
bsd-2-clause
|
dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap
|
c
|
## Code Before:
//===- PromoteMemToReg.h - Promote Allocas to Scalars -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exposes an interface to promote alloca instructions to SSA
// registers, by using the SSA construction algorithm.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#define TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#include <vector>
namespace llvm {
class AllocaInst;
class DominatorTree;
class DominanceFrontier;
class AliasSetTracker;
/// isAllocaPromotable - Return true if this alloca is legal for promotion.
/// This is true if there are only loads and stores to the alloca...
///
bool isAllocaPromotable(const AllocaInst *AI);
/// PromoteMemToReg - Promote the specified list of alloca instructions into
/// scalar registers, inserting PHI nodes as appropriate. This function makes
/// use of DominanceFrontier information. This function does not modify the CFG
/// of the function at all. All allocas must be from the same function.
///
/// If AST is specified, the specified tracker is updated to reflect changes
/// made to the IR.
///
void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
DominatorTree &DT, AliasSetTracker *AST = 0);
} // End llvm namespace
#endif
## Instruction:
Remove a stale forward declaration.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@156770 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
//===- PromoteMemToReg.h - Promote Allocas to Scalars -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exposes an interface to promote alloca instructions to SSA
// registers, by using the SSA construction algorithm.
//
//===----------------------------------------------------------------------===//
#ifndef TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#define TRANSFORMS_UTILS_PROMOTEMEMTOREG_H
#include <vector>
namespace llvm {
class AllocaInst;
class DominatorTree;
class AliasSetTracker;
/// isAllocaPromotable - Return true if this alloca is legal for promotion.
/// This is true if there are only loads and stores to the alloca...
///
bool isAllocaPromotable(const AllocaInst *AI);
/// PromoteMemToReg - Promote the specified list of alloca instructions into
/// scalar registers, inserting PHI nodes as appropriate. This function makes
/// use of DominanceFrontier information. This function does not modify the CFG
/// of the function at all. All allocas must be from the same function.
///
/// If AST is specified, the specified tracker is updated to reflect changes
/// made to the IR.
///
void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
DominatorTree &DT, AliasSetTracker *AST = 0);
} // End llvm namespace
#endif
|
# ... existing code ...
class AllocaInst;
class DominatorTree;
class AliasSetTracker;
/// isAllocaPromotable - Return true if this alloca is legal for promotion.
# ... rest of the code ...
|
b24fa6443e70cca01ff5059fe29ba6e33c0262ea
|
pylisp/packet/ip/protocol.py
|
pylisp/packet/ip/protocol.py
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
Split Protocol class in Protocol and ProtocolElement
|
Split Protocol class in Protocol and ProtocolElement
|
Python
|
bsd-3-clause
|
steffann/pylisp
|
python
|
## Code Before:
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
## Instruction:
Split Protocol class in Protocol and ProtocolElement
## Code After:
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
...
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
...
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
...
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
...
|
29419cf81068183029b1dc63e718937de155a754
|
test/weakref_test.py
|
test/weakref_test.py
|
import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assert_(ref() is self.core)
def test_weakref_node(self):
video = self.core.std.BlankClip()
ref = weakref.ref(video)
self.assert_(ref() is video)
def test_weakref_frame(self):
video = self.core.std.BlankClip()
frame = video.get_frame(0)
ref = weakref.ref(frame)
self.assert_(ref() is frame)
if __name__ == '__main__':
unittest.main()
|
import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assertTrue(ref() is self.core)
def test_weakref_node(self):
video = self.core.std.BlankClip()
ref = weakref.ref(video)
self.assertTrue(ref() is video)
def test_weakref_frame(self):
video = self.core.std.BlankClip()
frame = video.get_frame(0)
ref = weakref.ref(frame)
self.assertTrue(ref() is frame)
if __name__ == '__main__':
unittest.main()
|
Fix one more deprecation warning
|
Fix one more deprecation warning
|
Python
|
lgpl-2.1
|
vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth
|
python
|
## Code Before:
import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assert_(ref() is self.core)
def test_weakref_node(self):
video = self.core.std.BlankClip()
ref = weakref.ref(video)
self.assert_(ref() is video)
def test_weakref_frame(self):
video = self.core.std.BlankClip()
frame = video.get_frame(0)
ref = weakref.ref(frame)
self.assert_(ref() is frame)
if __name__ == '__main__':
unittest.main()
## Instruction:
Fix one more deprecation warning
## Code After:
import weakref
import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assertTrue(ref() is self.core)
def test_weakref_node(self):
video = self.core.std.BlankClip()
ref = weakref.ref(video)
self.assertTrue(ref() is video)
def test_weakref_frame(self):
video = self.core.std.BlankClip()
frame = video.get_frame(0)
ref = weakref.ref(frame)
self.assertTrue(ref() is frame)
if __name__ == '__main__':
unittest.main()
|
...
def test_weakref_core(self):
ref = weakref.ref(self.core)
self.assertTrue(ref() is self.core)
def test_weakref_node(self):
video = self.core.std.BlankClip()
ref = weakref.ref(video)
self.assertTrue(ref() is video)
def test_weakref_frame(self):
video = self.core.std.BlankClip()
frame = video.get_frame(0)
ref = weakref.ref(frame)
self.assertTrue(ref() is frame)
if __name__ == '__main__':
unittest.main()
...
|
c161615270d340e2ab77285e37c28162939a33d2
|
extensions/mutiny/runtime/src/main/java/io/quarkus/mutiny/runtime/MutinyInfrastructure.java
|
extensions/mutiny/runtime/src/main/java/io/quarkus/mutiny/runtime/MutinyInfrastructure.java
|
package io.quarkus.mutiny.runtime;
import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.jboss.logging.Logger;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;
@Recorder
public class MutinyInfrastructure {
public void configureMutinyInfrastructure(ExecutorService exec) {
Infrastructure.setDefaultExecutor(exec);
}
public void configureDroppedExceptionHandler() {
Logger logger = Logger.getLogger(MutinyInfrastructure.class);
Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
logger.error("Mutiny had to drop the following exception", throwable);
}
});
}
public void configureThreadBlockingChecker() {
Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
@Override
public boolean getAsBoolean() {
String threadName = Thread.currentThread().getName();
return !threadName.contains("vertx-eventloop-thread-");
}
});
}
}
|
package io.quarkus.mutiny.runtime;
import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.jboss.logging.Logger;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;
@Recorder
public class MutinyInfrastructure {
public void configureMutinyInfrastructure(ExecutorService exec) {
Infrastructure.setDefaultExecutor(exec);
}
public void configureDroppedExceptionHandler() {
Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable);
}
});
}
public void configureThreadBlockingChecker() {
Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
@Override
public boolean getAsBoolean() {
String threadName = Thread.currentThread().getName();
return !threadName.contains("vertx-eventloop-thread-");
}
});
}
}
|
Remove the logger from the heap
|
Remove the logger from the heap
|
Java
|
apache-2.0
|
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
|
java
|
## Code Before:
package io.quarkus.mutiny.runtime;
import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.jboss.logging.Logger;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;
@Recorder
public class MutinyInfrastructure {
public void configureMutinyInfrastructure(ExecutorService exec) {
Infrastructure.setDefaultExecutor(exec);
}
public void configureDroppedExceptionHandler() {
Logger logger = Logger.getLogger(MutinyInfrastructure.class);
Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
logger.error("Mutiny had to drop the following exception", throwable);
}
});
}
public void configureThreadBlockingChecker() {
Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
@Override
public boolean getAsBoolean() {
String threadName = Thread.currentThread().getName();
return !threadName.contains("vertx-eventloop-thread-");
}
});
}
}
## Instruction:
Remove the logger from the heap
## Code After:
package io.quarkus.mutiny.runtime;
import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.jboss.logging.Logger;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;
@Recorder
public class MutinyInfrastructure {
public void configureMutinyInfrastructure(ExecutorService exec) {
Infrastructure.setDefaultExecutor(exec);
}
public void configureDroppedExceptionHandler() {
Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable);
}
});
}
public void configureThreadBlockingChecker() {
Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
@Override
public boolean getAsBoolean() {
String threadName = Thread.currentThread().getName();
return !threadName.contains("vertx-eventloop-thread-");
}
});
}
}
|
# ... existing code ...
}
public void configureDroppedExceptionHandler() {
Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable);
}
});
}
# ... rest of the code ...
|
01ecb7f5235568095ddbb8ecdaf8369fd86b8cbf
|
src/main/java/org/springframework/social/discord/connect/DiscordAdapter.java
|
src/main/java/org/springframework/social/discord/connect/DiscordAdapter.java
|
package org.springframework.social.discord.connect;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;
public class DiscordAdapter implements ApiAdapter<Discord> {
@Override
public boolean test(Discord api) {
try {
api.applicationOperations().getApplicationInfo();
return true;
} catch (HttpClientErrorException e) {
return false;
}
}
@Override
public void setConnectionValues(Discord api, ConnectionValues values) {
DiscordUser profile = api.userOperations().getUser();
values.setProviderUserId(String.valueOf(profile.getId()));
values.setDisplayName(api.userOperations().getNickname());
values.setProfileUrl("https://discordapp.com/channels/@me");
values.setImageUrl(api.userOperations().getAvatarUrl());
}
@Override
public UserProfile fetchUserProfile(Discord api) {
DiscordUser profile = api.userOperations().getUser();
return new UserProfileBuilder()
.setId(profile.getId())
.setFirstName(profile.getUsername())
.setLastName("#" + profile.getDiscriminator())
.setUsername(api.userOperations().getNickname())
.setEmail(profile.getEmail())
.build();
}
@Override
public void updateStatus(Discord api, String message) {
// not supported
}
}
|
package org.springframework.social.discord.connect;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;
public class DiscordAdapter implements ApiAdapter<Discord> {
@Override
public boolean test(Discord api) {
try {
api.applicationOperations().getApplicationInfo();
return true;
} catch (HttpClientErrorException e) {
return false;
}
}
@Override
public void setConnectionValues(Discord api, ConnectionValues values) {
DiscordUser profile = api.userOperations().getUser();
values.setProviderUserId(String.valueOf(profile.getId()));
values.setDisplayName(profile.getUsername());
values.setProfileUrl("https://discordapp.com/channels/@me");
values.setImageUrl(api.userOperations().getAvatarUrl());
}
@Override
public UserProfile fetchUserProfile(Discord api) {
DiscordUser profile = api.userOperations().getUser();
return new UserProfileBuilder()
.setId(profile.getId())
.setName(profile.getUsername() + " " + profile.getDiscriminator())
.setUsername(api.userOperations().getNickname())
.setEmail(profile.getEmail())
.build();
}
@Override
public void updateStatus(Discord api, String message) {
// not supported
}
}
|
Drop the discriminator under displayName
|
Drop the discriminator under displayName
|
Java
|
apache-2.0
|
quanticc/sentry,quanticc/sentry,quanticc/sentry
|
java
|
## Code Before:
package org.springframework.social.discord.connect;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;
public class DiscordAdapter implements ApiAdapter<Discord> {
@Override
public boolean test(Discord api) {
try {
api.applicationOperations().getApplicationInfo();
return true;
} catch (HttpClientErrorException e) {
return false;
}
}
@Override
public void setConnectionValues(Discord api, ConnectionValues values) {
DiscordUser profile = api.userOperations().getUser();
values.setProviderUserId(String.valueOf(profile.getId()));
values.setDisplayName(api.userOperations().getNickname());
values.setProfileUrl("https://discordapp.com/channels/@me");
values.setImageUrl(api.userOperations().getAvatarUrl());
}
@Override
public UserProfile fetchUserProfile(Discord api) {
DiscordUser profile = api.userOperations().getUser();
return new UserProfileBuilder()
.setId(profile.getId())
.setFirstName(profile.getUsername())
.setLastName("#" + profile.getDiscriminator())
.setUsername(api.userOperations().getNickname())
.setEmail(profile.getEmail())
.build();
}
@Override
public void updateStatus(Discord api, String message) {
// not supported
}
}
## Instruction:
Drop the discriminator under displayName
## Code After:
package org.springframework.social.discord.connect;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;
public class DiscordAdapter implements ApiAdapter<Discord> {
@Override
public boolean test(Discord api) {
try {
api.applicationOperations().getApplicationInfo();
return true;
} catch (HttpClientErrorException e) {
return false;
}
}
@Override
public void setConnectionValues(Discord api, ConnectionValues values) {
DiscordUser profile = api.userOperations().getUser();
values.setProviderUserId(String.valueOf(profile.getId()));
values.setDisplayName(profile.getUsername());
values.setProfileUrl("https://discordapp.com/channels/@me");
values.setImageUrl(api.userOperations().getAvatarUrl());
}
@Override
public UserProfile fetchUserProfile(Discord api) {
DiscordUser profile = api.userOperations().getUser();
return new UserProfileBuilder()
.setId(profile.getId())
.setName(profile.getUsername() + " " + profile.getDiscriminator())
.setUsername(api.userOperations().getNickname())
.setEmail(profile.getEmail())
.build();
}
@Override
public void updateStatus(Discord api, String message) {
// not supported
}
}
|
# ... existing code ...
public void setConnectionValues(Discord api, ConnectionValues values) {
DiscordUser profile = api.userOperations().getUser();
values.setProviderUserId(String.valueOf(profile.getId()));
values.setDisplayName(profile.getUsername());
values.setProfileUrl("https://discordapp.com/channels/@me");
values.setImageUrl(api.userOperations().getAvatarUrl());
}
# ... modified code ...
DiscordUser profile = api.userOperations().getUser();
return new UserProfileBuilder()
.setId(profile.getId())
.setName(profile.getUsername() + " " + profile.getDiscriminator())
.setUsername(api.userOperations().getNickname())
.setEmail(profile.getEmail())
.build();
# ... rest of the code ...
|
5f5fe3e92916d1c76cb4aff9fc0a7a18c830e8f6
|
subprojects/performance/src/templates/java-source/Production.java
|
subprojects/performance/src/templates/java-source/Production.java
|
package ${packageName};
public class ${productionClassName} ${extendsAndImplementsClause} {
public static ${productionClassName} one() { return new ${productionClassName}(); }
private final String property;
<% extraFields.each { %>
${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
<% } %>
public ${productionClassName}(){
this.property = null;
}
public ${productionClassName}(String param) {
this.property = param;
}
public String getProperty() {
return property;
}
<% propertyCount.times { %>
private String prop${it};
public String getProp${it}() {
return prop${it};
}
public void setProp${it}(String value) {
prop${it} = value;
}
<% } %>
}
|
package ${packageName};
import java.util.List;
import java.util.Arrays;
public class ${productionClassName} ${extendsAndImplementsClause} {
public static ${productionClassName} one() { return new ${productionClassName}(); }
private final String property;
<% extraFields.each { %>
${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
public boolean check(${it.type} o) {
// dummy code to add arbitrary compile time
String p = o.getProperty();
p = p.toUpperCase();
List<String> strings = Arrays.asList(p, this.getProperty());
int len = 0;
for (String s: strings) {
len += s.length();
<% propertyCount.times { %>
len += o.getProp${it}().length();
<%}%>
}
return len>10;
}
<% } %>
public ${productionClassName}(){
this.property = null;
}
public ${productionClassName}(String param) {
this.property = param;
}
public String getProperty() {
return property;
}
<% propertyCount.times { %>
private String prop${it};
public String getProp${it}() {
return prop${it};
}
public void setProp${it}(String value) {
prop${it} = value;
}
<% } %>
}
|
Add arbitrary code to make compile time longer * the original code was too fast to compile to make compile avoidance relevant * the original code didn't represent what we could find in "real" code
|
Add arbitrary code to make compile time longer
* the original code was too fast to compile to make compile avoidance relevant
* the original code didn't represent what we could find in "real" code
+review REVIEW-5688
|
Java
|
apache-2.0
|
lsmaira/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle
|
java
|
## Code Before:
package ${packageName};
public class ${productionClassName} ${extendsAndImplementsClause} {
public static ${productionClassName} one() { return new ${productionClassName}(); }
private final String property;
<% extraFields.each { %>
${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
<% } %>
public ${productionClassName}(){
this.property = null;
}
public ${productionClassName}(String param) {
this.property = param;
}
public String getProperty() {
return property;
}
<% propertyCount.times { %>
private String prop${it};
public String getProp${it}() {
return prop${it};
}
public void setProp${it}(String value) {
prop${it} = value;
}
<% } %>
}
## Instruction:
Add arbitrary code to make compile time longer
* the original code was too fast to compile to make compile avoidance relevant
* the original code didn't represent what we could find in "real" code
+review REVIEW-5688
## Code After:
package ${packageName};
import java.util.List;
import java.util.Arrays;
public class ${productionClassName} ${extendsAndImplementsClause} {
public static ${productionClassName} one() { return new ${productionClassName}(); }
private final String property;
<% extraFields.each { %>
${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
public boolean check(${it.type} o) {
// dummy code to add arbitrary compile time
String p = o.getProperty();
p = p.toUpperCase();
List<String> strings = Arrays.asList(p, this.getProperty());
int len = 0;
for (String s: strings) {
len += s.length();
<% propertyCount.times { %>
len += o.getProp${it}().length();
<%}%>
}
return len>10;
}
<% } %>
public ${productionClassName}(){
this.property = null;
}
public ${productionClassName}(String param) {
this.property = param;
}
public String getProperty() {
return property;
}
<% propertyCount.times { %>
private String prop${it};
public String getProp${it}() {
return prop${it};
}
public void setProp${it}(String value) {
prop${it} = value;
}
<% } %>
}
|
...
package ${packageName};
import java.util.List;
import java.util.Arrays;
public class ${productionClassName} ${extendsAndImplementsClause} {
...
private final String property;
<% extraFields.each { %>
${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
public boolean check(${it.type} o) {
// dummy code to add arbitrary compile time
String p = o.getProperty();
p = p.toUpperCase();
List<String> strings = Arrays.asList(p, this.getProperty());
int len = 0;
for (String s: strings) {
len += s.length();
<% propertyCount.times { %>
len += o.getProp${it}().length();
<%}%>
}
return len>10;
}
<% } %>
public ${productionClassName}(){
...
|
030e64d7aee6c3f0b3a0d0508ac1d5ece0bf4a40
|
astroquery/fermi/__init__.py
|
astroquery/fermi/__init__.py
|
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
|
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
del ConfigurationItem # clean up namespace - prevents doc warnings
|
Clean up namespace to get rid of sphinx warnings
|
Clean up namespace to get rid of sphinx warnings
|
Python
|
bsd-3-clause
|
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
|
python
|
## Code Before:
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
## Instruction:
Clean up namespace to get rid of sphinx warnings
## Code After:
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
del ConfigurationItem # clean up namespace - prevents doc warnings
|
# ... existing code ...
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
del ConfigurationItem # clean up namespace - prevents doc warnings
# ... rest of the code ...
|
8b889c10abf043f6612409973458e8a0f0ed952e
|
bonus_level.py
|
bonus_level.py
|
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i
print log_counter
|
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
log_counter = 0xFF
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i
print log_counter
|
Initialize the log counter to 0xFF
|
Initialize the log counter to 0xFF
|
Python
|
mit
|
japesinator/Bad-Crypto,japesinator/Bad-Crypto
|
python
|
## Code Before:
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i
print log_counter
## Instruction:
Initialize the log counter to 0xFF
## Code After:
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
log_counter = 0xFF
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i
print log_counter
|
# ... existing code ...
secret = input("Please enter your plaintext: ")
for char in secret:
log_counter = 0xFF
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i
# ... rest of the code ...
|
5dc5de9dab24cf698dc26db24d1e1697472c2e05
|
tests/integration/pillar/test_pillar_include.py
|
tests/integration/pillar/test_pillar_include.py
|
from __future__ import unicode_literals
from tests.support.case import ModuleCase
class PillarIncludeTest(ModuleCase):
def test_pillar_include(self):
'''
Test pillar include
'''
ret = self.minion_run('pillar.items')
assert 'a' in ret['element']
assert ret['element']['a'] == {'a': ['Entry A']}
assert 'b' in ret['element']
assert ret['element']['b'] == {'b': ['Entry B']}
def test_pillar_glob_include(self):
'''
Test pillar include via glob pattern
'''
ret = self.minion_run('pillar.items')
assert 'glob-a' in ret
assert ret['glob-a'] == 'Entry A'
assert 'glob-b' in ret
assert ret['glob-b'] == 'Entry B'
|
'''
Pillar include tests
'''
from __future__ import unicode_literals
from tests.support.case import ModuleCase
class PillarIncludeTest(ModuleCase):
def test_pillar_include(self):
'''
Test pillar include
'''
ret = self.minion_run('pillar.items')
assert 'a' in ret['element']
assert ret['element']['a'] == {'a': ['Entry A']}
assert 'b' in ret['element']
assert ret['element']['b'] == {'b': ['Entry B']}
def test_pillar_glob_include(self):
'''
Test pillar include via glob pattern
'''
ret = self.minion_run('pillar.items')
assert 'glob-a' in ret
assert ret['glob-a'] == 'Entry A'
assert 'glob-b' in ret
assert ret['glob-b'] == 'Entry B'
|
Use file encoding and add docstring
|
Use file encoding and add docstring
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
python
|
## Code Before:
from __future__ import unicode_literals
from tests.support.case import ModuleCase
class PillarIncludeTest(ModuleCase):
def test_pillar_include(self):
'''
Test pillar include
'''
ret = self.minion_run('pillar.items')
assert 'a' in ret['element']
assert ret['element']['a'] == {'a': ['Entry A']}
assert 'b' in ret['element']
assert ret['element']['b'] == {'b': ['Entry B']}
def test_pillar_glob_include(self):
'''
Test pillar include via glob pattern
'''
ret = self.minion_run('pillar.items')
assert 'glob-a' in ret
assert ret['glob-a'] == 'Entry A'
assert 'glob-b' in ret
assert ret['glob-b'] == 'Entry B'
## Instruction:
Use file encoding and add docstring
## Code After:
'''
Pillar include tests
'''
from __future__ import unicode_literals
from tests.support.case import ModuleCase
class PillarIncludeTest(ModuleCase):
def test_pillar_include(self):
'''
Test pillar include
'''
ret = self.minion_run('pillar.items')
assert 'a' in ret['element']
assert ret['element']['a'] == {'a': ['Entry A']}
assert 'b' in ret['element']
assert ret['element']['b'] == {'b': ['Entry B']}
def test_pillar_glob_include(self):
'''
Test pillar include via glob pattern
'''
ret = self.minion_run('pillar.items')
assert 'glob-a' in ret
assert ret['glob-a'] == 'Entry A'
assert 'glob-b' in ret
assert ret['glob-b'] == 'Entry B'
|
// ... existing code ...
'''
Pillar include tests
'''
from __future__ import unicode_literals
from tests.support.case import ModuleCase
// ... rest of the code ...
|
d3f09baf1e1de0272e1a579a207f685feb6c673f
|
common/mixins.py
|
common/mixins.py
|
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
self.slug = slugify(getattr(self, self.slugify_field))
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError("This object already exists.")
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
Return user-friendly error message for SlugifyMixin class
|
Return user-friendly error message for SlugifyMixin class
|
Python
|
mit
|
teamtaverna/core
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
self.slug = slugify(getattr(self, self.slugify_field))
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError("This object already exists.")
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
## Instruction:
Return user-friendly error message for SlugifyMixin class
## Code After:
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
...
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
...
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
...
|
fd65d227f4e5dc639ab38b350ad17302cc81b3d8
|
library/src/main/java/com/lorentzos/flingswipe/internal/SwipeEvent.java
|
library/src/main/java/com/lorentzos/flingswipe/internal/SwipeEvent.java
|
package com.lorentzos.flingswipe.internal;
import android.animation.AnimatorListenerAdapter;
import android.view.View;
/**
*
*/
class SwipeEvent {
private final float rotationFactor;
private final FrameData frameData;
private final View frame;
SwipeEvent(float rotationFactor, View frame) {
this.rotationFactor = rotationFactor;
frameData = FrameData.fromView(frame);
this.frame = frame;
}
void resultView(@Direction int direction, AnimatorListenerAdapter onAnimationEnd) {
PointF f = new PointF(frame.getX(), frame.getY());
frameData.getExitPosition(f, direction, rotationFactor)
.exit(frame, onAnimationEnd);
}
}
|
package com.lorentzos.flingswipe.internal;
import android.animation.AnimatorListenerAdapter;
import android.view.View;
/**
*
*/
class SwipeEvent {
private final float rotationFactor;
private final FrameData frameData;
private final View frame;
SwipeEvent(float rotationFactor, View frame) {
this.rotationFactor = rotationFactor;
frameData = FrameData.fromView(frame);
this.frame = frame;
}
void resultView(@Direction int direction, AnimatorListenerAdapter onAnimationEnd) {
PointF f = new PointF(frame.getX(), frame.getY());
float adjustedFactor = rotationFactor;
if (direction == Direction.LEFT) {
adjustedFactor *= -1;
}
frameData.getExitPosition(f, direction, adjustedFactor)
.exit(frame, onAnimationEnd);
}
}
|
Fix left exit rotation for button events
|
Fix left exit rotation for button events
|
Java
|
apache-2.0
|
Diolor/Swipecards,Topface/Swipecards
|
java
|
## Code Before:
package com.lorentzos.flingswipe.internal;
import android.animation.AnimatorListenerAdapter;
import android.view.View;
/**
*
*/
class SwipeEvent {
private final float rotationFactor;
private final FrameData frameData;
private final View frame;
SwipeEvent(float rotationFactor, View frame) {
this.rotationFactor = rotationFactor;
frameData = FrameData.fromView(frame);
this.frame = frame;
}
void resultView(@Direction int direction, AnimatorListenerAdapter onAnimationEnd) {
PointF f = new PointF(frame.getX(), frame.getY());
frameData.getExitPosition(f, direction, rotationFactor)
.exit(frame, onAnimationEnd);
}
}
## Instruction:
Fix left exit rotation for button events
## Code After:
package com.lorentzos.flingswipe.internal;
import android.animation.AnimatorListenerAdapter;
import android.view.View;
/**
*
*/
class SwipeEvent {
private final float rotationFactor;
private final FrameData frameData;
private final View frame;
SwipeEvent(float rotationFactor, View frame) {
this.rotationFactor = rotationFactor;
frameData = FrameData.fromView(frame);
this.frame = frame;
}
void resultView(@Direction int direction, AnimatorListenerAdapter onAnimationEnd) {
PointF f = new PointF(frame.getX(), frame.getY());
float adjustedFactor = rotationFactor;
if (direction == Direction.LEFT) {
adjustedFactor *= -1;
}
frameData.getExitPosition(f, direction, adjustedFactor)
.exit(frame, onAnimationEnd);
}
}
|
...
void resultView(@Direction int direction, AnimatorListenerAdapter onAnimationEnd) {
PointF f = new PointF(frame.getX(), frame.getY());
float adjustedFactor = rotationFactor;
if (direction == Direction.LEFT) {
adjustedFactor *= -1;
}
frameData.getExitPosition(f, direction, adjustedFactor)
.exit(frame, onAnimationEnd);
}
...
|
cd5f4c65777253d265a620194f553f5f4b76881d
|
l10n_ch_payment_slip/report/__init__.py
|
l10n_ch_payment_slip/report/__init__.py
|
from . import payment_slip_from_invoice
|
from . import payment_slip_from_invoice
from . import reports_common
|
Add common in import statement
|
Add common in import statement
|
Python
|
agpl-3.0
|
brain-tec/l10n-switzerland,BT-jmichaud/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland
|
python
|
## Code Before:
from . import payment_slip_from_invoice
## Instruction:
Add common in import statement
## Code After:
from . import payment_slip_from_invoice
from . import reports_common
|
// ... existing code ...
from . import payment_slip_from_invoice
from . import reports_common
// ... rest of the code ...
|
686a21bf859f955ff8d3d179da64b7a23c0fed44
|
test/Preprocessor/macro_paste_spacing2.c
|
test/Preprocessor/macro_paste_spacing2.c
|
// RUN: clang-cc %s -E | grep "movl %eax"
#define R1E %eax
#define epilogue(r1) movl r1;
epilogue(R1E)
|
// RUN: clang-cc %s -E | grep "movl %eax"
// PR4132
#define R1E %eax
#define epilogue(r1) movl r1 ## E;
epilogue(R1)
|
Fix the testcase for PR4132.
|
Fix the testcase for PR4132.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@70796 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
|
c
|
## Code Before:
// RUN: clang-cc %s -E | grep "movl %eax"
#define R1E %eax
#define epilogue(r1) movl r1;
epilogue(R1E)
## Instruction:
Fix the testcase for PR4132.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@70796 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: clang-cc %s -E | grep "movl %eax"
// PR4132
#define R1E %eax
#define epilogue(r1) movl r1 ## E;
epilogue(R1)
|
...
// RUN: clang-cc %s -E | grep "movl %eax"
// PR4132
#define R1E %eax
#define epilogue(r1) movl r1 ## E;
epilogue(R1)
...
|
15e713f76f1fbfef26d9a7d3d3c95fac2d8f213e
|
casepro/settings_production_momza.py
|
casepro/settings_production_momza.py
|
from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID_FIELDNAME',
'registrant_id',
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "msisdn_registrant", "field_name": "Cell Number"},
{"field": "language", "field_name": "Language Preference"},
{"field": "faccode", "field_name": "Facility Code"},
{"field": "reg_type", "field_name": "Registration Type"},
{"field": "mom_dob", "field_name": "Mother's Date of Birth"},
{"field": "edd", "field_name": "Expected Due Date"},
]
|
from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID_FIELDNAME',
'registrant_id',
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "faccode", "field_name": "Facility Code"},
{"field": "reg_type", "field_name": "Registration Type"},
{"field": "mom_dob", "field_name": "Mother's Date of Birth"},
{"field": "edd", "field_name": "Expected Due Date"},
]
|
Remove cell number and language from pod
|
Remove cell number and language from pod
We started using the identity store and the hub to fetch this information,
but unfortunately the field names are different depending on which service
the info is coming from.
These 2 fields are already displayed in the CasePro interface so it makes
sense to not use the pod at all for them.
|
Python
|
bsd-3-clause
|
praekelt/casepro,praekelt/casepro,praekelt/casepro
|
python
|
## Code Before:
from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID_FIELDNAME',
'registrant_id',
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "msisdn_registrant", "field_name": "Cell Number"},
{"field": "language", "field_name": "Language Preference"},
{"field": "faccode", "field_name": "Facility Code"},
{"field": "reg_type", "field_name": "Registration Type"},
{"field": "mom_dob", "field_name": "Mother's Date of Birth"},
{"field": "edd", "field_name": "Expected Due Date"},
]
## Instruction:
Remove cell number and language from pod
We started using the identity store and the hub to fetch this information,
but unfortunately the field names are different depending on which service
the info is coming from.
These 2 fields are already displayed in the CasePro interface so it makes
sense to not use the pod at all for them.
## Code After:
from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID_FIELDNAME',
'registrant_id',
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "faccode", "field_name": "Facility Code"},
{"field": "reg_type", "field_name": "Registration Type"},
{"field": "mom_dob", "field_name": "Mother's Date of Birth"},
{"field": "edd", "field_name": "Expected Due Date"},
]
|
# ... existing code ...
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "faccode", "field_name": "Facility Code"},
{"field": "reg_type", "field_name": "Registration Type"},
{"field": "mom_dob", "field_name": "Mother's Date of Birth"},
# ... rest of the code ...
|
ebfc7061f7515af3ec8b2f61bdbcf4a26c212095
|
src/clarifai_client.py
|
src/clarifai_client.py
|
from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/metro-north.jpg'])
print(res)
|
from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/metro-north.jpg'])
if res['status']['description'] == 'Ok':
print("COOL!")
concepts = res['outputs'][0]['data']['concepts']
for concept in concepts:
print(concept['name'], concept['value'])
|
Test on clarifai is working and returns the tags
|
Test on clarifai is working and returns the tags
|
Python
|
apache-2.0
|
rlokc/PyCVTagger
|
python
|
## Code Before:
from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/metro-north.jpg'])
print(res)
## Instruction:
Test on clarifai is working and returns the tags
## Code After:
from clarifai.rest import ClarifaiApp
class Clarifai():
def __init__(self, api_id, api_secret):
self.api_id = api_id
self.api_secret = api_secret
self.app = ClarifaiApp(self.api_id, self.api_secret)
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/metro-north.jpg'])
if res['status']['description'] == 'Ok':
print("COOL!")
concepts = res['outputs'][0]['data']['concepts']
for concept in concepts:
print(concept['name'], concept['value'])
|
// ... existing code ...
def test(self):
res = self.app.tag_urls(['https://samples.clarifai.com/metro-north.jpg'])
if res['status']['description'] == 'Ok':
print("COOL!")
concepts = res['outputs'][0]['data']['concepts']
for concept in concepts:
print(concept['name'], concept['value'])
// ... rest of the code ...
|
a1ec7fbf4bb00d2a24dfba0acf6baf18d1b016ee
|
froide/comments/forms.py
|
froide/comments/forms.py
|
from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
help_text=_('Your name will only be visible to logged in users.'),
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
comment = forms.CharField(
label=_('Comment'),
widget=forms.Textarea(
attrs={
'class': 'form-control',
'rows': '4'
}
),
max_length=COMMENT_MAX_LENGTH
)
|
from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
max_length=50,
help_text=_('Your name will only be visible to logged in users.'),
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
comment = forms.CharField(
label=_('Comment'),
widget=forms.Textarea(
attrs={
'class': 'form-control',
'rows': '4'
}
),
max_length=COMMENT_MAX_LENGTH
)
|
Add max length to comment field
|
Add max length to comment field
|
Python
|
mit
|
fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide
|
python
|
## Code Before:
from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
help_text=_('Your name will only be visible to logged in users.'),
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
comment = forms.CharField(
label=_('Comment'),
widget=forms.Textarea(
attrs={
'class': 'form-control',
'rows': '4'
}
),
max_length=COMMENT_MAX_LENGTH
)
## Instruction:
Add max length to comment field
## Code After:
from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
max_length=50,
help_text=_('Your name will only be visible to logged in users.'),
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
comment = forms.CharField(
label=_('Comment'),
widget=forms.Textarea(
attrs={
'class': 'form-control',
'rows': '4'
}
),
max_length=COMMENT_MAX_LENGTH
)
|
...
name = forms.CharField(
label=_('Name'),
required=True,
max_length=50,
help_text=_('Your name will only be visible to logged in users.'),
widget=forms.TextInput(
attrs={
...
|
8b32603f1492f8847ffecd683c1d666a528abbf2
|
include/Athena-Physics/Prerequisites.h
|
include/Athena-Physics/Prerequisites.h
|
/** @file Prerequisites.h
@author Philip Abbet
Declaration of the types of the Athena-Physics module
*/
#ifndef _ATHENA_PHYSICS_PREREQUISITES_H_
#define _ATHENA_PHYSICS_PREREQUISITES_H_
#include <Athena-Core/Prerequisites.h>
#include <Athena-Physics/Config.h>
#include <Bullet/btConfig.h>
#include <btBulletDynamicsCommon.h>
//----------------------------------------------------------------------------------------
/// @brief Main namespace. All the components of the Athena engine belongs to this
/// namespace
//----------------------------------------------------------------------------------------
namespace Athena
{
//------------------------------------------------------------------------------------
/// @brief Contains all the physics-related classes
//------------------------------------------------------------------------------------
namespace Physics
{
class Body;
class CollisionShape;
class PhysicalComponent;
class World;
class BoxShape;
class CapsuleShape;
class ConeShape;
class CylinderShape;
class SphereShape;
class StaticTriMeshShape;
}
//------------------------------------------------------------------------------------
/// @brief Initialize the Physics module
//------------------------------------------------------------------------------------
extern void initialize();
}
#endif
|
/** @file Prerequisites.h
@author Philip Abbet
Declaration of the types of the Athena-Physics module
*/
#ifndef _ATHENA_PHYSICS_PREREQUISITES_H_
#define _ATHENA_PHYSICS_PREREQUISITES_H_
#include <Athena-Core/Prerequisites.h>
#include <Athena-Physics/Config.h>
#include <Bullet/btConfig.h>
#include <btBulletDynamicsCommon.h>
//----------------------------------------------------------------------------------------
/// @brief Main namespace. All the components of the Athena engine belongs to this
/// namespace
//----------------------------------------------------------------------------------------
namespace Athena
{
//------------------------------------------------------------------------------------
/// @brief Contains all the physics-related classes
//------------------------------------------------------------------------------------
namespace Physics
{
class Body;
class CollisionShape;
class PhysicalComponent;
class World;
class BoxShape;
class CapsuleShape;
class ConeShape;
class CylinderShape;
class SphereShape;
class StaticTriMeshShape;
//------------------------------------------------------------------------------------
/// @brief Initialize the Physics module
//------------------------------------------------------------------------------------
extern void initialize();
}
}
#endif
|
Fix the previous commit: the 'initialize()' function wasn't declared in the 'Athena::Physics' namespace
|
Fix the previous commit: the 'initialize()' function wasn't declared in the 'Athena::Physics' namespace
|
C
|
mit
|
Kanma/Athena-Physics,Kanma/Athena-Physics
|
c
|
## Code Before:
/** @file Prerequisites.h
@author Philip Abbet
Declaration of the types of the Athena-Physics module
*/
#ifndef _ATHENA_PHYSICS_PREREQUISITES_H_
#define _ATHENA_PHYSICS_PREREQUISITES_H_
#include <Athena-Core/Prerequisites.h>
#include <Athena-Physics/Config.h>
#include <Bullet/btConfig.h>
#include <btBulletDynamicsCommon.h>
//----------------------------------------------------------------------------------------
/// @brief Main namespace. All the components of the Athena engine belongs to this
/// namespace
//----------------------------------------------------------------------------------------
namespace Athena
{
//------------------------------------------------------------------------------------
/// @brief Contains all the physics-related classes
//------------------------------------------------------------------------------------
namespace Physics
{
class Body;
class CollisionShape;
class PhysicalComponent;
class World;
class BoxShape;
class CapsuleShape;
class ConeShape;
class CylinderShape;
class SphereShape;
class StaticTriMeshShape;
}
//------------------------------------------------------------------------------------
/// @brief Initialize the Physics module
//------------------------------------------------------------------------------------
extern void initialize();
}
#endif
## Instruction:
Fix the previous commit: the 'initialize()' function wasn't declared in the 'Athena::Physics' namespace
## Code After:
/** @file Prerequisites.h
@author Philip Abbet
Declaration of the types of the Athena-Physics module
*/
#ifndef _ATHENA_PHYSICS_PREREQUISITES_H_
#define _ATHENA_PHYSICS_PREREQUISITES_H_
#include <Athena-Core/Prerequisites.h>
#include <Athena-Physics/Config.h>
#include <Bullet/btConfig.h>
#include <btBulletDynamicsCommon.h>
//----------------------------------------------------------------------------------------
/// @brief Main namespace. All the components of the Athena engine belongs to this
/// namespace
//----------------------------------------------------------------------------------------
namespace Athena
{
//------------------------------------------------------------------------------------
/// @brief Contains all the physics-related classes
//------------------------------------------------------------------------------------
namespace Physics
{
class Body;
class CollisionShape;
class PhysicalComponent;
class World;
class BoxShape;
class CapsuleShape;
class ConeShape;
class CylinderShape;
class SphereShape;
class StaticTriMeshShape;
//------------------------------------------------------------------------------------
/// @brief Initialize the Physics module
//------------------------------------------------------------------------------------
extern void initialize();
}
}
#endif
|
// ... existing code ...
class CylinderShape;
class SphereShape;
class StaticTriMeshShape;
//------------------------------------------------------------------------------------
/// @brief Initialize the Physics module
//------------------------------------------------------------------------------------
extern void initialize();
}
}
#endif
// ... rest of the code ...
|
2b05f0dd0af44367a077f1d106da9f47921d4392
|
src/main/java/org/purescript/psi/var/LocalForeignValueReference.kt
|
src/main/java/org/purescript/psi/var/LocalForeignValueReference.kt
|
package org.purescript.psi.`var`
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.PSForeignValueDeclaration
class LocalForeignValueReference(element: PSVar) : PsiReferenceBase<PSVar>(
element,
TextRange.allOf(element.text.trim()),
false
) {
override fun getVariants(): Array<PSForeignValueDeclaration> {
return myElement.module.foreignValueDeclarations
}
override fun resolve(): PSForeignValueDeclaration? {
return myElement
.module
.foreignValueDeclarations
.find { it.name == myElement.name }
}
}
|
package org.purescript.psi.`var`
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.PSForeignValueDeclaration
class LocalForeignValueReference(element: PSVar) : PsiReferenceBase<PSVar>(
element,
TextRange.allOf(element.text.trim()),
false
) {
override fun getVariants(): Array<PSForeignValueDeclaration> {
return myElement.module.foreignValueDeclarations
}
override fun resolve(): PSForeignValueDeclaration? {
return variants.find { it.name == myElement.name }
}
}
|
Simplify local foreign value reference
|
Simplify local foreign value reference
|
Kotlin
|
bsd-3-clause
|
intellij-purescript/intellij-purescript,intellij-purescript/intellij-purescript
|
kotlin
|
## Code Before:
package org.purescript.psi.`var`
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.PSForeignValueDeclaration
class LocalForeignValueReference(element: PSVar) : PsiReferenceBase<PSVar>(
element,
TextRange.allOf(element.text.trim()),
false
) {
override fun getVariants(): Array<PSForeignValueDeclaration> {
return myElement.module.foreignValueDeclarations
}
override fun resolve(): PSForeignValueDeclaration? {
return myElement
.module
.foreignValueDeclarations
.find { it.name == myElement.name }
}
}
## Instruction:
Simplify local foreign value reference
## Code After:
package org.purescript.psi.`var`
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.PSForeignValueDeclaration
class LocalForeignValueReference(element: PSVar) : PsiReferenceBase<PSVar>(
element,
TextRange.allOf(element.text.trim()),
false
) {
override fun getVariants(): Array<PSForeignValueDeclaration> {
return myElement.module.foreignValueDeclarations
}
override fun resolve(): PSForeignValueDeclaration? {
return variants.find { it.name == myElement.name }
}
}
|
// ... existing code ...
}
override fun resolve(): PSForeignValueDeclaration? {
return variants.find { it.name == myElement.name }
}
}
// ... rest of the code ...
|
8ce6aa788573aa10758375d58881f03ff438db16
|
machete/base.py
|
machete/base.py
|
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
|
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
|
Add __repr__ To BaseVertex and BaseEdge
|
Add __repr__ To BaseVertex and BaseEdge
|
Python
|
bsd-3-clause
|
rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete
|
python
|
## Code Before:
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
## Instruction:
Add __repr__ To BaseVertex and BaseEdge
## Code After:
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
|
# ... existing code ...
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
# ... rest of the code ...
|
d76497aad6a0040c78f816c10081b7ec71a2bec6
|
src/org/bootstrapjsp/tags/core/carousel/CarouselItem.java
|
src/org/bootstrapjsp/tags/core/carousel/CarouselItem.java
|
/*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.tags.core.carousel;
import javax.servlet.jsp.tagext.JspTag;
import org.bootstrapjsp.facet.ActiveFacet;
import org.bootstrapjsp.tags.html.Div;
import org.tldgen.annotations.Attribute;
import org.tldgen.annotations.Tag;
/**
* A carousel item.
* <p>
* <div class="item">...</div>
* </p>
*/
@Tag(name="carouselitem",dynamicAttributes=true)
public class CarouselItem extends Div {
public CarouselItem() {
super("item");
super.addFacet(new ActiveFacet(false));
}
/**
* Sets a caption for this item. The caption is automatically
* wrapped in a <carouselcaption>.
*/
@Attribute(rtexprvalue=true)
public void setCaption(String caption) {
super.appendChild(new CarouselCaption(caption), BEFORE_BODY);
}
@Override
public void setParent(JspTag parent) {
if (parent != null) {
if (parent instanceof Carousel) {
((Carousel) parent).addItem(this);
} else {
throw new IllegalArgumentException("Illegal parent");
}
}
super.setParent(parent);
}
}
|
/*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.tags.core.carousel;
import javax.servlet.jsp.tagext.JspTag;
import org.bootstrapjsp.facet.ActiveFacet;
import org.bootstrapjsp.tags.html.Div;
import org.tldgen.annotations.Attribute;
import org.tldgen.annotations.Tag;
/**
* A carousel item.
* <p>
* <div class="item">...</div>
* </p>
*/
@Tag(name="carouselitem",dynamicAttributes=true)
public class CarouselItem extends Div {
@SuppressWarnings("unchecked")
public CarouselItem() {
super("item");
super.addFacet(new ActiveFacet(false));
super.setValidParents(Carousel.class);
}
/**
* Sets a caption for this item. The caption is automatically
* wrapped in a <carouselcaption>.
*/
@Attribute(rtexprvalue=true)
public void setCaption(String caption) {
super.appendChild(new CarouselCaption(caption), BEFORE_BODY);
}
@Override
public void setParent(JspTag parent) {
if (parent != null) {
if (parent instanceof Carousel) {
((Carousel) parent).addItem(this);
}
}
super.setParent(parent);
}
}
|
Set valid parents on carousel item
|
Set valid parents on carousel item
|
Java
|
lgpl-2.1
|
Mrdigs/Bootstrap.jsp,Mrdigs/Bootstrap.jsp,Mrdigs/Bootstrap.jsp
|
java
|
## Code Before:
/*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.tags.core.carousel;
import javax.servlet.jsp.tagext.JspTag;
import org.bootstrapjsp.facet.ActiveFacet;
import org.bootstrapjsp.tags.html.Div;
import org.tldgen.annotations.Attribute;
import org.tldgen.annotations.Tag;
/**
* A carousel item.
* <p>
* <div class="item">...</div>
* </p>
*/
@Tag(name="carouselitem",dynamicAttributes=true)
public class CarouselItem extends Div {
public CarouselItem() {
super("item");
super.addFacet(new ActiveFacet(false));
}
/**
* Sets a caption for this item. The caption is automatically
* wrapped in a <carouselcaption>.
*/
@Attribute(rtexprvalue=true)
public void setCaption(String caption) {
super.appendChild(new CarouselCaption(caption), BEFORE_BODY);
}
@Override
public void setParent(JspTag parent) {
if (parent != null) {
if (parent instanceof Carousel) {
((Carousel) parent).addItem(this);
} else {
throw new IllegalArgumentException("Illegal parent");
}
}
super.setParent(parent);
}
}
## Instruction:
Set valid parents on carousel item
## Code After:
/*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.tags.core.carousel;
import javax.servlet.jsp.tagext.JspTag;
import org.bootstrapjsp.facet.ActiveFacet;
import org.bootstrapjsp.tags.html.Div;
import org.tldgen.annotations.Attribute;
import org.tldgen.annotations.Tag;
/**
* A carousel item.
* <p>
* <div class="item">...</div>
* </p>
*/
@Tag(name="carouselitem",dynamicAttributes=true)
public class CarouselItem extends Div {
@SuppressWarnings("unchecked")
public CarouselItem() {
super("item");
super.addFacet(new ActiveFacet(false));
super.setValidParents(Carousel.class);
}
/**
* Sets a caption for this item. The caption is automatically
* wrapped in a <carouselcaption>.
*/
@Attribute(rtexprvalue=true)
public void setCaption(String caption) {
super.appendChild(new CarouselCaption(caption), BEFORE_BODY);
}
@Override
public void setParent(JspTag parent) {
if (parent != null) {
if (parent instanceof Carousel) {
((Carousel) parent).addItem(this);
}
}
super.setParent(parent);
}
}
|
...
@Tag(name="carouselitem",dynamicAttributes=true)
public class CarouselItem extends Div {
@SuppressWarnings("unchecked")
public CarouselItem() {
super("item");
super.addFacet(new ActiveFacet(false));
super.setValidParents(Carousel.class);
}
/**
...
if (parent != null) {
if (parent instanceof Carousel) {
((Carousel) parent).addItem(this);
}
}
super.setParent(parent);
...
|
58eaaeca980d8ec92d77c201aa01d5c46cf761dd
|
neuroshare/NeuralEntity.py
|
neuroshare/NeuralEntity.py
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
Update Neural Entity (now complete)
|
doc: Update Neural Entity (now complete)
|
Python
|
lgpl-2.1
|
abhay447/python-neuroshare,G-Node/python-neuroshare,G-Node/python-neuroshare,abhay447/python-neuroshare
|
python
|
## Code Before:
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
## Instruction:
doc: Update Neural Entity (now complete)
## Code After:
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
// ... existing code ...
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
// ... modified code ...
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
// ... rest of the code ...
|
52c5f4ddfde8db6179f11c3bec2bc8be69eed238
|
flake8_docstrings.py
|
flake8_docstrings.py
|
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
def run(self):
"""Use directly check() api from pep257."""
for error in pep257.check([self.filename]):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
yield (error.line, 0, error.message, type(self))
|
import io
import pep8
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
STDIN_NAMES = set(['stdin', '-', '(none)', None])
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
def run(self):
"""Use directly check() api from pep257."""
for error in self.checker.check_source(self.source, self.filename):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
yield (error.line, 0, error.message, type(self))
def load_source(self):
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pep8.stdin_get_value()
else:
with io.open(self.filename, encoding='utf-8') as fd:
self.source = fd.read()
|
Handle stdin in the plugin
|
Handle stdin in the plugin
Closes #2
|
Python
|
mit
|
PyCQA/flake8-docstrings
|
python
|
## Code Before:
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
def run(self):
"""Use directly check() api from pep257."""
for error in pep257.check([self.filename]):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
yield (error.line, 0, error.message, type(self))
## Instruction:
Handle stdin in the plugin
Closes #2
## Code After:
import io
import pep8
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
STDIN_NAMES = set(['stdin', '-', '(none)', None])
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
def run(self):
"""Use directly check() api from pep257."""
for error in self.checker.check_source(self.source, self.filename):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
yield (error.line, 0, error.message, type(self))
def load_source(self):
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pep8.stdin_get_value()
else:
with io.open(self.filename, encoding='utf-8') as fd:
self.source = fd.read()
|
// ... existing code ...
import io
import pep8
import pep257
__version__ = '0.2.1.post1'
// ... modified code ...
name = 'pep257'
version = __version__
STDIN_NAMES = set(['stdin', '-', '(none)', None])
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
def run(self):
"""Use directly check() api from pep257."""
for error in self.checker.check_source(self.source, self.filename):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
yield (error.line, 0, error.message, type(self))
def load_source(self):
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pep8.stdin_get_value()
else:
with io.open(self.filename, encoding='utf-8') as fd:
self.source = fd.read()
// ... rest of the code ...
|
601fe6fd1fc2f34f7cefe2fac0ff343144d139cc
|
src/ipf/ipfblock/rgb2gray.py
|
src/ipf/ipfblock/rgb2gray.py
|
import ipfblock
import ioport
import ipf.ipfblock.processing
from ipf.ipftype.ipfimage3ctype import IPFImage3cType
from ipf.ipftype.ipfimage1ctype import IPFImage1cType
class RGB2Gray(ipfblock.IPFBlock):
""" Convert 3 channel image to 1 channel gray block class
"""
type = "RGB2Gray"
category = "Channel operations"
is_abstract_block = False
def __init__(self):
super(RGB2Gray, self).__init__()
self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType)
self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType)
self.processing_function = ipf.ipfblock.processing.rgb2gray
def get_preview_image(self):
return IPFImage3cType.convert(self.output_ports["output_image"]._value)
|
import ipfblock
import ioport
import ipf.ipfblock.processing
from ipf.ipftype.ipfimage3ctype import IPFImage3cType
from ipf.ipftype.ipfimage1ctype import IPFImage1cType
class RGB2Gray(ipfblock.IPFBlock):
""" Convert 3 channel image to 1 channel gray block class
"""
type = "RGB2Gray"
category = "Channel operations"
is_abstract_block = False
def __init__(self):
super(RGB2Gray, self).__init__()
self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType)
self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType)
self.processing_function = ipf.ipfblock.processing.rgb2gray
def get_preview_image(self):
return self.output_ports["output_image"]._value
|
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
|
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
|
Python
|
lgpl-2.1
|
anton-golubkov/Garland,anton-golubkov/Garland
|
python
|
## Code Before:
import ipfblock
import ioport
import ipf.ipfblock.processing
from ipf.ipftype.ipfimage3ctype import IPFImage3cType
from ipf.ipftype.ipfimage1ctype import IPFImage1cType
class RGB2Gray(ipfblock.IPFBlock):
""" Convert 3 channel image to 1 channel gray block class
"""
type = "RGB2Gray"
category = "Channel operations"
is_abstract_block = False
def __init__(self):
super(RGB2Gray, self).__init__()
self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType)
self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType)
self.processing_function = ipf.ipfblock.processing.rgb2gray
def get_preview_image(self):
return IPFImage3cType.convert(self.output_ports["output_image"]._value)
## Instruction:
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
## Code After:
import ipfblock
import ioport
import ipf.ipfblock.processing
from ipf.ipftype.ipfimage3ctype import IPFImage3cType
from ipf.ipftype.ipfimage1ctype import IPFImage1cType
class RGB2Gray(ipfblock.IPFBlock):
""" Convert 3 channel image to 1 channel gray block class
"""
type = "RGB2Gray"
category = "Channel operations"
is_abstract_block = False
def __init__(self):
super(RGB2Gray, self).__init__()
self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType)
self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType)
self.processing_function = ipf.ipfblock.processing.rgb2gray
def get_preview_image(self):
return self.output_ports["output_image"]._value
|
# ... existing code ...
self.processing_function = ipf.ipfblock.processing.rgb2gray
def get_preview_image(self):
return self.output_ports["output_image"]._value
# ... rest of the code ...
|
1c2ea508bd0c4e687d6a46c438a476609b43d264
|
databroker/tests/test_document.py
|
databroker/tests/test_document.py
|
import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert not isinstance(b, Document)
assert isinstance(b, dict)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
|
import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
|
Make test stricter to be safe.
|
Make test stricter to be safe.
|
Python
|
bsd-3-clause
|
ericdill/databroker,ericdill/databroker
|
python
|
## Code Before:
import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert not isinstance(b, Document)
assert isinstance(b, dict)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
## Instruction:
Make test stricter to be safe.
## Code After:
import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
|
# ... existing code ...
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
# ... rest of the code ...
|
364fde2dd6554760ca63c5b16e35222d5482999e
|
report/report_util.py
|
report/report_util.py
|
def compare_ledger_types(account, data, orm):
selected_ledger = data['form']['ledger_type']
account_ledgers = [ledger.id for ledger in account.ledger_types]
if not selected_ledger:
return account_ledgers == []
return selected_ledger in account_ledgers
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
|
def compare_ledger_types(account, data, orm):
if not hasattr(account, 'ledger_types'):
# Ignore this filter when alternate_ledger is not installed.
return True
selected_ledger = data['form']['ledger_type']
account_ledgers = [ledger.id for ledger in account.ledger_types]
if not selected_ledger:
return account_ledgers == []
return selected_ledger in account_ledgers
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
|
Fix errors when alternate_ledger is not installed
|
Fix errors when alternate_ledger is not installed
|
Python
|
agpl-3.0
|
lithint/account_report_webkit,xcgd/account_report_webkit,xcgd/account_report_webkit,lithint/account_report_webkit
|
python
|
## Code Before:
def compare_ledger_types(account, data, orm):
selected_ledger = data['form']['ledger_type']
account_ledgers = [ledger.id for ledger in account.ledger_types]
if not selected_ledger:
return account_ledgers == []
return selected_ledger in account_ledgers
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
## Instruction:
Fix errors when alternate_ledger is not installed
## Code After:
def compare_ledger_types(account, data, orm):
if not hasattr(account, 'ledger_types'):
# Ignore this filter when alternate_ledger is not installed.
return True
selected_ledger = data['form']['ledger_type']
account_ledgers = [ledger.id for ledger in account.ledger_types]
if not selected_ledger:
return account_ledgers == []
return selected_ledger in account_ledgers
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
|
// ... existing code ...
def compare_ledger_types(account, data, orm):
if not hasattr(account, 'ledger_types'):
# Ignore this filter when alternate_ledger is not installed.
return True
selected_ledger = data['form']['ledger_type']
account_ledgers = [ledger.id for ledger in account.ledger_types]
// ... rest of the code ...
|
f1bbec3d097cec8fda1ae01e5aa1b23b9d479235
|
src/main/java/com/pturpin/quickcheck/junit4/DefaultRegistryFactory.java
|
src/main/java/com/pturpin/quickcheck/junit4/DefaultRegistryFactory.java
|
package com.pturpin.quickcheck.junit4;
import com.pturpin.quickcheck.identifier.ClassIdentifier;
import com.pturpin.quickcheck.registry.Registries;
import com.pturpin.quickcheck.registry.Registry;
import static com.pturpin.quickcheck.generator.Numbers.doubleGen;
/**
* Created by turpif on 28/04/17.
*/
final class DefaultRegistryFactory implements RandomRunner.RegistryFactory {
public DefaultRegistryFactory() {
// nothing
}
@Override
public Registry create() {
return Registries.builder()
.put(new ClassIdentifier<>(double.class), doubleGen())
.put(new ClassIdentifier<>(Double.class), doubleGen())
.build();
}
}
|
package com.pturpin.quickcheck.junit4;
import com.pturpin.quickcheck.base.Ranges;
import com.pturpin.quickcheck.base.Ranges.Range;
import com.pturpin.quickcheck.identifier.ClassIdentifier;
import com.pturpin.quickcheck.registry.Registries;
import com.pturpin.quickcheck.registry.Registry;
import java.math.BigDecimal;
import java.math.BigInteger;
import static com.pturpin.quickcheck.generator.Numbers.*;
/**
* Created by turpif on 28/04/17.
*/
final class DefaultRegistryFactory implements RandomRunner.RegistryFactory {
public DefaultRegistryFactory() {
// nothing
}
@Override
public Registry create() {
Range<BigInteger> bigIntegerRange = Ranges.closed(
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)),
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)));
Range<BigDecimal> bigDecimalRange = Ranges.closed(
BigDecimal.valueOf(-Double.MAX_VALUE).multiply(BigDecimal.valueOf(1000)),
BigDecimal.valueOf(Double.MIN_VALUE).multiply(BigDecimal.valueOf(1000)));
return Registries.builder()
.put(new ClassIdentifier<>(double.class), doubleGen())
.put(new ClassIdentifier<>(Double.class), doubleGen())
.put(new ClassIdentifier<>(int.class), integerGen())
.put(new ClassIdentifier<>(Integer.class), integerGen())
.put(new ClassIdentifier<>(long.class), longGen())
.put(new ClassIdentifier<>(Long.class), longGen())
.put(new ClassIdentifier<>(BigInteger.class), bigIntegerGen(bigIntegerRange))
.put(new ClassIdentifier<>(BigDecimal.class), bigDecimalGen(bigDecimalRange))
.build();
}
}
|
Complete default registry with promitive generators
|
Complete default registry with promitive generators
|
Java
|
mit
|
TurpIF/QuickCheck
|
java
|
## Code Before:
package com.pturpin.quickcheck.junit4;
import com.pturpin.quickcheck.identifier.ClassIdentifier;
import com.pturpin.quickcheck.registry.Registries;
import com.pturpin.quickcheck.registry.Registry;
import static com.pturpin.quickcheck.generator.Numbers.doubleGen;
/**
* Created by turpif on 28/04/17.
*/
final class DefaultRegistryFactory implements RandomRunner.RegistryFactory {
public DefaultRegistryFactory() {
// nothing
}
@Override
public Registry create() {
return Registries.builder()
.put(new ClassIdentifier<>(double.class), doubleGen())
.put(new ClassIdentifier<>(Double.class), doubleGen())
.build();
}
}
## Instruction:
Complete default registry with promitive generators
## Code After:
package com.pturpin.quickcheck.junit4;
import com.pturpin.quickcheck.base.Ranges;
import com.pturpin.quickcheck.base.Ranges.Range;
import com.pturpin.quickcheck.identifier.ClassIdentifier;
import com.pturpin.quickcheck.registry.Registries;
import com.pturpin.quickcheck.registry.Registry;
import java.math.BigDecimal;
import java.math.BigInteger;
import static com.pturpin.quickcheck.generator.Numbers.*;
/**
* Created by turpif on 28/04/17.
*/
final class DefaultRegistryFactory implements RandomRunner.RegistryFactory {
public DefaultRegistryFactory() {
// nothing
}
@Override
public Registry create() {
Range<BigInteger> bigIntegerRange = Ranges.closed(
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)),
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)));
Range<BigDecimal> bigDecimalRange = Ranges.closed(
BigDecimal.valueOf(-Double.MAX_VALUE).multiply(BigDecimal.valueOf(1000)),
BigDecimal.valueOf(Double.MIN_VALUE).multiply(BigDecimal.valueOf(1000)));
return Registries.builder()
.put(new ClassIdentifier<>(double.class), doubleGen())
.put(new ClassIdentifier<>(Double.class), doubleGen())
.put(new ClassIdentifier<>(int.class), integerGen())
.put(new ClassIdentifier<>(Integer.class), integerGen())
.put(new ClassIdentifier<>(long.class), longGen())
.put(new ClassIdentifier<>(Long.class), longGen())
.put(new ClassIdentifier<>(BigInteger.class), bigIntegerGen(bigIntegerRange))
.put(new ClassIdentifier<>(BigDecimal.class), bigDecimalGen(bigDecimalRange))
.build();
}
}
|
...
package com.pturpin.quickcheck.junit4;
import com.pturpin.quickcheck.base.Ranges;
import com.pturpin.quickcheck.base.Ranges.Range;
import com.pturpin.quickcheck.identifier.ClassIdentifier;
import com.pturpin.quickcheck.registry.Registries;
import com.pturpin.quickcheck.registry.Registry;
import java.math.BigDecimal;
import java.math.BigInteger;
import static com.pturpin.quickcheck.generator.Numbers.*;
/**
* Created by turpif on 28/04/17.
...
@Override
public Registry create() {
Range<BigInteger> bigIntegerRange = Ranges.closed(
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)),
BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(1000)));
Range<BigDecimal> bigDecimalRange = Ranges.closed(
BigDecimal.valueOf(-Double.MAX_VALUE).multiply(BigDecimal.valueOf(1000)),
BigDecimal.valueOf(Double.MIN_VALUE).multiply(BigDecimal.valueOf(1000)));
return Registries.builder()
.put(new ClassIdentifier<>(double.class), doubleGen())
.put(new ClassIdentifier<>(Double.class), doubleGen())
.put(new ClassIdentifier<>(int.class), integerGen())
.put(new ClassIdentifier<>(Integer.class), integerGen())
.put(new ClassIdentifier<>(long.class), longGen())
.put(new ClassIdentifier<>(Long.class), longGen())
.put(new ClassIdentifier<>(BigInteger.class), bigIntegerGen(bigIntegerRange))
.put(new ClassIdentifier<>(BigDecimal.class), bigDecimalGen(bigDecimalRange))
.build();
}
}
...
|
47cb8d841569225b3e8e33945313709f964bd932
|
src/drivers/tty/serial/ttys_oldfs.h
|
src/drivers/tty/serial/ttys_oldfs.h
|
/**
* @file
*
* @date 21.04.2016
* @author Anton Bondarev
*/
#ifndef TTYS_H_
#define TTYS_H_
#include <fs/idesc.h>
#include <drivers/tty.h>
struct uart;
struct tty_uart {
struct idesc idesc;
struct tty tty;
struct uart *uart;
};
#endif /* TTYS_H_ */
|
/**
* @file
*
* @date 21.04.2016
* @author Anton Bondarev
*/
#ifndef TTYS_H_
#define TTYS_H_
#include <fs/idesc.h>
#include <drivers/tty.h>
#include <drivers/char_dev.h>
struct uart;
struct tty_uart {
struct idesc idesc;
struct tty tty;
struct uart *uart;
};
extern struct idesc *uart_cdev_open(struct dev_module *cdev, void *priv);
#define TTYS_DEF(name, uart) \
CHAR_DEV_DEF(name, uart_cdev_open, NULL, NULL, uart)
#endif /* TTYS_H_ */
|
Add TTYS_DEF macro to oldfs
|
drivers: Add TTYS_DEF macro to oldfs
|
C
|
bsd-2-clause
|
embox/embox,embox/embox,embox/embox,embox/embox,embox/embox,embox/embox
|
c
|
## Code Before:
/**
* @file
*
* @date 21.04.2016
* @author Anton Bondarev
*/
#ifndef TTYS_H_
#define TTYS_H_
#include <fs/idesc.h>
#include <drivers/tty.h>
struct uart;
struct tty_uart {
struct idesc idesc;
struct tty tty;
struct uart *uart;
};
#endif /* TTYS_H_ */
## Instruction:
drivers: Add TTYS_DEF macro to oldfs
## Code After:
/**
* @file
*
* @date 21.04.2016
* @author Anton Bondarev
*/
#ifndef TTYS_H_
#define TTYS_H_
#include <fs/idesc.h>
#include <drivers/tty.h>
#include <drivers/char_dev.h>
struct uart;
struct tty_uart {
struct idesc idesc;
struct tty tty;
struct uart *uart;
};
extern struct idesc *uart_cdev_open(struct dev_module *cdev, void *priv);
#define TTYS_DEF(name, uart) \
CHAR_DEV_DEF(name, uart_cdev_open, NULL, NULL, uart)
#endif /* TTYS_H_ */
|
# ... existing code ...
#include <fs/idesc.h>
#include <drivers/tty.h>
#include <drivers/char_dev.h>
struct uart;
struct tty_uart {
struct idesc idesc;
struct tty tty;
# ... modified code ...
struct uart *uart;
};
extern struct idesc *uart_cdev_open(struct dev_module *cdev, void *priv);
#define TTYS_DEF(name, uart) \
CHAR_DEV_DEF(name, uart_cdev_open, NULL, NULL, uart)
#endif /* TTYS_H_ */
# ... rest of the code ...
|
7228d4db754fc0c57f6c2e5ad8d45c0b0b909a08
|
src/main/java/com/icosillion/podengine/utils/DateUtils.java
|
src/main/java/com/icosillion/podengine/utils/DateUtils.java
|
package com.icosillion.podengine.utils;
import com.icosillion.podengine.exceptions.DateFormatException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private static SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"),
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z"),
new SimpleDateFormat("dd MMM yyyy HH:mm Z")
};
public static Date stringToDate(String dt) throws DateFormatException {
Date date = null;
for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
try {
date = dateFormat.parse(dt);
break;
} catch (ParseException e) {
//This format didn't work, keep going
}
}
return date;
}
}
|
package com.icosillion.podengine.utils;
import com.icosillion.podengine.exceptions.DateFormatException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateUtils {
private static SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm Z", Locale.US)
};
public static Date stringToDate(String dt) throws DateFormatException {
Date date = null;
for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
try {
date = dateFormat.parse(dt);
break;
} catch (ParseException e) {
//This format didn't work, keep going
}
}
return date;
}
}
|
Use US Locale for date parser
|
Use US Locale for date parser
|
Java
|
mit
|
MarkusLewis/Podcast-Feed-Library,EdgeOwl/Podcast-Feed-Library
|
java
|
## Code Before:
package com.icosillion.podengine.utils;
import com.icosillion.podengine.exceptions.DateFormatException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private static SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"),
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z"),
new SimpleDateFormat("dd MMM yyyy HH:mm Z")
};
public static Date stringToDate(String dt) throws DateFormatException {
Date date = null;
for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
try {
date = dateFormat.parse(dt);
break;
} catch (ParseException e) {
//This format didn't work, keep going
}
}
return date;
}
}
## Instruction:
Use US Locale for date parser
## Code After:
package com.icosillion.podengine.utils;
import com.icosillion.podengine.exceptions.DateFormatException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateUtils {
private static SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm Z", Locale.US)
};
public static Date stringToDate(String dt) throws DateFormatException {
Date date = null;
for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
try {
date = dateFormat.parse(dt);
break;
} catch (ParseException e) {
//This format didn't work, keep going
}
}
return date;
}
}
|
...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateUtils {
private static SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z", Locale.US),
new SimpleDateFormat("dd MMM yyyy HH:mm Z", Locale.US)
};
public static Date stringToDate(String dt) throws DateFormatException {
...
|
7187dbb7ca378726e2b58dc052dbc150582f9a24
|
src/summon.py
|
src/summon.py
|
from __future__ import print_function
''' summon.py
A simple wrapper for OS-dependent file launchers.
Copyright 2013 Julian Gonggrijp
Licensed under the Red Spider Project License.
See the License.txt that shipped with your copy of this software for details.
'''
import sys
import subprocess
if sys.platform.startswith('win32'):
summoning_command = ['start']
elif sys.platform.startswith('darwin'):
summoning_command = ['open']
else: # linux assumed
summoning_command = ['xdg-open']
def main (argv = None):
if not argv:
print(usage_msg)
else:
for filename in argv:
subprocess.call(summoning_command + [filename])
usage_msg = '''
Call me with a space-separated list of file paths and I'll summon
them for you.
'''
if __name__ == '__main__':
main(sys.argv[1:])
|
from __future__ import print_function
''' summon.py
A simple wrapper for OS-dependent file launchers.
Copyright 2013 Julian Gonggrijp
Licensed under the Red Spider Project License.
See the License.txt that shipped with your copy of this software for details.
'''
import sys
import subprocess
useshell = False
if sys.platform.startswith('win32'):
summoning_command = ['start']
useshell = True
elif sys.platform.startswith('darwin'):
summoning_command = ['open']
else: # linux assumed
summoning_command = ['xdg-open']
def main (argv = None):
if not argv:
print(usage_msg)
else:
for filename in argv:
subprocess.call(summoning_command + [filename], shell = useshell)
usage_msg = '''
Call me with a space-separated list of file paths and I'll summon
them for you.
'''
if __name__ == '__main__':
main(sys.argv[1:])
|
Use shell in subprocess.call for Windows.
|
Use shell in subprocess.call for Windows.
|
Python
|
mit
|
the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project
|
python
|
## Code Before:
from __future__ import print_function
''' summon.py
A simple wrapper for OS-dependent file launchers.
Copyright 2013 Julian Gonggrijp
Licensed under the Red Spider Project License.
See the License.txt that shipped with your copy of this software for details.
'''
import sys
import subprocess
if sys.platform.startswith('win32'):
summoning_command = ['start']
elif sys.platform.startswith('darwin'):
summoning_command = ['open']
else: # linux assumed
summoning_command = ['xdg-open']
def main (argv = None):
if not argv:
print(usage_msg)
else:
for filename in argv:
subprocess.call(summoning_command + [filename])
usage_msg = '''
Call me with a space-separated list of file paths and I'll summon
them for you.
'''
if __name__ == '__main__':
main(sys.argv[1:])
## Instruction:
Use shell in subprocess.call for Windows.
## Code After:
from __future__ import print_function
''' summon.py
A simple wrapper for OS-dependent file launchers.
Copyright 2013 Julian Gonggrijp
Licensed under the Red Spider Project License.
See the License.txt that shipped with your copy of this software for details.
'''
import sys
import subprocess
useshell = False
if sys.platform.startswith('win32'):
summoning_command = ['start']
useshell = True
elif sys.platform.startswith('darwin'):
summoning_command = ['open']
else: # linux assumed
summoning_command = ['xdg-open']
def main (argv = None):
if not argv:
print(usage_msg)
else:
for filename in argv:
subprocess.call(summoning_command + [filename], shell = useshell)
usage_msg = '''
Call me with a space-separated list of file paths and I'll summon
them for you.
'''
if __name__ == '__main__':
main(sys.argv[1:])
|
// ... existing code ...
import sys
import subprocess
useshell = False
if sys.platform.startswith('win32'):
summoning_command = ['start']
useshell = True
elif sys.platform.startswith('darwin'):
summoning_command = ['open']
else: # linux assumed
// ... modified code ...
print(usage_msg)
else:
for filename in argv:
subprocess.call(summoning_command + [filename], shell = useshell)
usage_msg = '''
Call me with a space-separated list of file paths and I'll summon
// ... rest of the code ...
|
1ae097291a42022013969287ecb91bafa60ae625
|
examples/send_transfer.py
|
examples/send_transfer.py
|
from iota import *
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = b'SEED9GOES9HERE'
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
Clarify Address usage in send example
|
Clarify Address usage in send example
Improved the script to explain the recipient address a little better.
Changed the address concat to a reference to a specific kind of Iota address.
This is loosely inspired by the JAVA sen transaction test case.
|
Python
|
mit
|
iotaledger/iota.lib.py
|
python
|
## Code Before:
from iota import *
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = b'SEED9GOES9HERE'
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
## Instruction:
Clarify Address usage in send example
Improved the script to explain the recipient address a little better.
Changed the address concat to a reference to a specific kind of Iota address.
This is loosely inspired by the JAVA sen transaction test case.
## Code After:
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
...
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
...
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
...
# Recipient of the transfer.
address =
Address(
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
...
|
82d312826ee67b098d9e9a52277912d8e1829960
|
geocode.py
|
geocode.py
|
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Green Bank Telescope',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + '?' + data
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
|
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Campbell Hall',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + data
print full_url
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
|
Remove second ? from URL
|
Remove second ? from URL
|
Python
|
bsd-3-clause
|
caseyjlaw/flaskigm,caseyjlaw/flaskigm
|
python
|
## Code Before:
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Green Bank Telescope',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + '?' + data
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
## Instruction:
Remove second ? from URL
## Code After:
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Campbell Hall',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + data
print full_url
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
|
// ... existing code ...
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Campbell Hall',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + data
print full_url
response = urllib2.urlopen(full_url)
json_response = response.read()
// ... rest of the code ...
|
bc11202f53d082c559ff5d0ce1693c463b4777db
|
VisualPractice/auxiliary.h
|
VisualPractice/auxiliary.h
|
struct SDL_Rect;
namespace te
{
struct Vector2i;
class Rectangle;
bool checkCollision(const SDL_Rect& a, const SDL_Rect& b);
bool checkCollision(const Rectangle& a, const Rectangle& b);
SDL_Rect getIntersection(const SDL_Rect& a, const SDL_Rect& b);
SDL_Rect getIntersection(const Rectangle& a, const Rectangle& b);
Vector2i getCenter(const SDL_Rect& rect);
Vector2i getCenter(const Rectangle& rect);
void handlePaddleCollision(Rectangle& ball, const Rectangle& paddle, float dt, float velocityScalar = 200.f);
void handleWallCollision(Rectangle& ball, const Rectangle& wall, float dt);
}
#endif
|
struct SDL_Rect;
namespace te
{
struct Vector2i;
class Rectangle;
bool checkCollision(const SDL_Rect& a, const SDL_Rect& b);
bool checkCollision(const Rectangle& a, const Rectangle& b);
SDL_Rect getIntersection(const SDL_Rect& a, const SDL_Rect& b);
SDL_Rect getIntersection(const Rectangle& a, const Rectangle& b);
Vector2i getCenter(const SDL_Rect& rect);
Vector2i getCenter(const Rectangle& rect);
void handlePaddleCollision(Rectangle& ball, const Rectangle& paddle, float dt, float velocityScalar = 200.f);
void handleWallCollision(Rectangle& ball, const Rectangle& wall, float dt);
template <class K, class V>
void insertOrAssign(std::map<K,V>& map, std::pair<K, V>&& kvPair)
{
auto it = map.find(kvPair.first);
if (it == map.end())
{
map.insert(std::move(kvPair));
}
else
{
it->second = std::move(kvPair.second);
}
}
template <class K, class V>
void insertOrAssign(std::map<K, V>& map, const std::pair<K, V>& kvPair)
{
auto it = map.find(kvPair.first);
if (it != map.end())
{
map.insert(kvPair);
}
else
{
it->second = kvPair.second;
}
}
}
#endif
|
Add insertOrAssign helper for maps
|
Add insertOrAssign helper for maps
|
C
|
mit
|
evinstk/TantechEngineOriginal,evinstk/TantechEngine,evinstk/TantechEngine,evinstk/TantechEngine,evinstk/TantechEngineOriginal,evinstk/TantechEngineOriginal,evinstk/TantechEngine,evinstk/TantechEngineOriginal,evinstk/TantechEngine,evinstk/TantechEngineOriginal,evinstk/TantechEngineOriginal,evinstk/TantechEngine
|
c
|
## Code Before:
struct SDL_Rect;
namespace te
{
struct Vector2i;
class Rectangle;
bool checkCollision(const SDL_Rect& a, const SDL_Rect& b);
bool checkCollision(const Rectangle& a, const Rectangle& b);
SDL_Rect getIntersection(const SDL_Rect& a, const SDL_Rect& b);
SDL_Rect getIntersection(const Rectangle& a, const Rectangle& b);
Vector2i getCenter(const SDL_Rect& rect);
Vector2i getCenter(const Rectangle& rect);
void handlePaddleCollision(Rectangle& ball, const Rectangle& paddle, float dt, float velocityScalar = 200.f);
void handleWallCollision(Rectangle& ball, const Rectangle& wall, float dt);
}
#endif
## Instruction:
Add insertOrAssign helper for maps
## Code After:
struct SDL_Rect;
namespace te
{
struct Vector2i;
class Rectangle;
bool checkCollision(const SDL_Rect& a, const SDL_Rect& b);
bool checkCollision(const Rectangle& a, const Rectangle& b);
SDL_Rect getIntersection(const SDL_Rect& a, const SDL_Rect& b);
SDL_Rect getIntersection(const Rectangle& a, const Rectangle& b);
Vector2i getCenter(const SDL_Rect& rect);
Vector2i getCenter(const Rectangle& rect);
void handlePaddleCollision(Rectangle& ball, const Rectangle& paddle, float dt, float velocityScalar = 200.f);
void handleWallCollision(Rectangle& ball, const Rectangle& wall, float dt);
template <class K, class V>
void insertOrAssign(std::map<K,V>& map, std::pair<K, V>&& kvPair)
{
auto it = map.find(kvPair.first);
if (it == map.end())
{
map.insert(std::move(kvPair));
}
else
{
it->second = std::move(kvPair.second);
}
}
template <class K, class V>
void insertOrAssign(std::map<K, V>& map, const std::pair<K, V>& kvPair)
{
auto it = map.find(kvPair.first);
if (it != map.end())
{
map.insert(kvPair);
}
else
{
it->second = kvPair.second;
}
}
}
#endif
|
# ... existing code ...
void handlePaddleCollision(Rectangle& ball, const Rectangle& paddle, float dt, float velocityScalar = 200.f);
void handleWallCollision(Rectangle& ball, const Rectangle& wall, float dt);
template <class K, class V>
void insertOrAssign(std::map<K,V>& map, std::pair<K, V>&& kvPair)
{
auto it = map.find(kvPair.first);
if (it == map.end())
{
map.insert(std::move(kvPair));
}
else
{
it->second = std::move(kvPair.second);
}
}
template <class K, class V>
void insertOrAssign(std::map<K, V>& map, const std::pair<K, V>& kvPair)
{
auto it = map.find(kvPair.first);
if (it != map.end())
{
map.insert(kvPair);
}
else
{
it->second = kvPair.second;
}
}
}
#endif
# ... rest of the code ...
|
b9f302f38e07b32590fc4008f413a5baa756dbee
|
zou/app/resources/source/csv/assets.py
|
zou/app/resources/source/csv/assets.py
|
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
return entity
|
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
if entity is None:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
pass
return entity
|
Fix duplicates in asset import
|
Fix duplicates in asset import
It relied on the unique constraint from the database, but it doesn't apply if
parent_id is null. So it checks the existence of the asset before inserting it.
|
Python
|
agpl-3.0
|
cgwire/zou
|
python
|
## Code Before:
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
return entity
## Instruction:
Fix duplicates in asset import
It relied on the unique constraint from the database, but it doesn't apply if
parent_id is null. So it checks the existence of the asset before inserting it.
## Code After:
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
if entity is None:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
pass
return entity
|
// ... existing code ...
)
try:
entity = Entity.get_by(
name=name,
project_id=project_id,
// ... modified code ...
entity_type_id=entity_type_id
)
if entity is None:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
pass
return entity
// ... rest of the code ...
|
e09894b92823392891fd0dddb63fd30bfd5bdc2a
|
pyclient/integtest.py
|
pyclient/integtest.py
|
from lockd import LockdClient
lockd_client = LockdClient()
# Lock
assert lockd_client.lock("foo")
# Dup lock should fail
assert not lockd_client.lock("foo")
# Lock another entry should work
assert lockd_client.lock("bar")
# Unlock entries
assert lockd_client.unlock("foo")
assert lockd_client.unlock("bar")
# Dup unlock should fail
assert not lockd_client.unlock("bar")
|
from lockd import LockdClient
lockd_client = LockdClient()
# Initial state
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Lock
assert lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Dup lock should fail
assert not lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Lock another entry should work
assert lockd_client.lock("bar")
assert lockd_client.is_locked("bar")
# Unlock entries
assert lockd_client.unlock("foo")
assert lockd_client.unlock("bar")
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Dup unlock should fail
assert not lockd_client.unlock("bar")
assert not lockd_client.is_locked("bar")
|
Add is_locked calls to integration test
|
Add is_locked calls to integration test
|
Python
|
mit
|
divtxt/lockd,divtxt/lockd
|
python
|
## Code Before:
from lockd import LockdClient
lockd_client = LockdClient()
# Lock
assert lockd_client.lock("foo")
# Dup lock should fail
assert not lockd_client.lock("foo")
# Lock another entry should work
assert lockd_client.lock("bar")
# Unlock entries
assert lockd_client.unlock("foo")
assert lockd_client.unlock("bar")
# Dup unlock should fail
assert not lockd_client.unlock("bar")
## Instruction:
Add is_locked calls to integration test
## Code After:
from lockd import LockdClient
lockd_client = LockdClient()
# Initial state
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Lock
assert lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Dup lock should fail
assert not lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Lock another entry should work
assert lockd_client.lock("bar")
assert lockd_client.is_locked("bar")
# Unlock entries
assert lockd_client.unlock("foo")
assert lockd_client.unlock("bar")
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Dup unlock should fail
assert not lockd_client.unlock("bar")
assert not lockd_client.is_locked("bar")
|
...
lockd_client = LockdClient()
# Initial state
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Lock
assert lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Dup lock should fail
assert not lockd_client.lock("foo")
assert lockd_client.is_locked("foo")
# Lock another entry should work
assert lockd_client.lock("bar")
assert lockd_client.is_locked("bar")
# Unlock entries
assert lockd_client.unlock("foo")
assert lockd_client.unlock("bar")
assert not lockd_client.is_locked("foo")
assert not lockd_client.is_locked("bar")
# Dup unlock should fail
assert not lockd_client.unlock("bar")
assert not lockd_client.is_locked("bar")
...
|
0b8b32a044e92f4e996af734d44a2d93d1492684
|
project_code/bulk_fitting.py
|
project_code/bulk_fitting.py
|
'''
Bulk spectral line fitting with SDSS galaxy spectra
'''
import os
from astropy.io import fits
from pandas import concat
# Bring in the package funcs
from specfit import do_specfit
from download_spectra import download_spectra
def bulk_fit(obs_file, output_file, keep_spectra=False):
'''
Downloads files based off of the entries in the given file, performs
spectral line fitting and saves the results to a FITS table.
'''
# Open the file
data_file = fits.open(obs_file)
spectra_data = data_file[1].data
del data_file
num_spectra = spectra_data['Z'].shape[0]
for i in range(num_spectra):
spec_info = spectra_data[i]
# Download the spectrum
spec_name = \
download_spectra(spec_info['PLATEID'], spec_info['FIBREID'],
spec_info['MJD'], spec_info['SURVEY'])
spec_df = do_specfit(spec_name, verbose=False)
if i == 0:
df = spec_df
else:
df = concat([df, spec_df])
if not keep_spectra:
os.system('rm ' + spec_name)
df.write(output_file)
return
|
'''
Bulk spectral line fitting with SDSS galaxy spectra
'''
import os
from astropy.io import fits
from pandas import DataFrame
# Bring in the package funcs
from specfit import do_specfit
from download_spectra import download_spectra
def bulk_fit(obs_file, output_file, keep_spectra=False):
'''
Downloads files based off of the entries in the given file, performs
spectral line fitting and saves the results to a FITS table.
'''
# Open the file
data_file = fits.open(obs_file)
spectra_data = data_file[1].data
del data_file
num_spectra = spectra_data['Z'].shape[0]
for i in range(num_spectra):
spec_info = spectra_data[i]
# Download the spectrum
spec_name = \
download_spectra(spec_info['PLATE'], spec_info['FIBERID'],
spec_info['MJD'], spec_info['SURVEY'])
spec_df = do_specfit(spec_name, verbose=False)
if i == 0:
df = DataFrame(spec_df, columns=[spec_name[:-5]])
else:
df[spec_name[:-5]] = spec_df
if not keep_spectra:
os.system('rm ' + spec_name)
df.to_csv(output_file)
return
|
Correct names, concat dataframes properly
|
Correct names, concat dataframes properly
|
Python
|
mit
|
e-koch/Phys-595
|
python
|
## Code Before:
'''
Bulk spectral line fitting with SDSS galaxy spectra
'''
import os
from astropy.io import fits
from pandas import concat
# Bring in the package funcs
from specfit import do_specfit
from download_spectra import download_spectra
def bulk_fit(obs_file, output_file, keep_spectra=False):
'''
Downloads files based off of the entries in the given file, performs
spectral line fitting and saves the results to a FITS table.
'''
# Open the file
data_file = fits.open(obs_file)
spectra_data = data_file[1].data
del data_file
num_spectra = spectra_data['Z'].shape[0]
for i in range(num_spectra):
spec_info = spectra_data[i]
# Download the spectrum
spec_name = \
download_spectra(spec_info['PLATEID'], spec_info['FIBREID'],
spec_info['MJD'], spec_info['SURVEY'])
spec_df = do_specfit(spec_name, verbose=False)
if i == 0:
df = spec_df
else:
df = concat([df, spec_df])
if not keep_spectra:
os.system('rm ' + spec_name)
df.write(output_file)
return
## Instruction:
Correct names, concat dataframes properly
## Code After:
'''
Bulk spectral line fitting with SDSS galaxy spectra
'''
import os
from astropy.io import fits
from pandas import DataFrame
# Bring in the package funcs
from specfit import do_specfit
from download_spectra import download_spectra
def bulk_fit(obs_file, output_file, keep_spectra=False):
'''
Downloads files based off of the entries in the given file, performs
spectral line fitting and saves the results to a FITS table.
'''
# Open the file
data_file = fits.open(obs_file)
spectra_data = data_file[1].data
del data_file
num_spectra = spectra_data['Z'].shape[0]
for i in range(num_spectra):
spec_info = spectra_data[i]
# Download the spectrum
spec_name = \
download_spectra(spec_info['PLATE'], spec_info['FIBERID'],
spec_info['MJD'], spec_info['SURVEY'])
spec_df = do_specfit(spec_name, verbose=False)
if i == 0:
df = DataFrame(spec_df, columns=[spec_name[:-5]])
else:
df[spec_name[:-5]] = spec_df
if not keep_spectra:
os.system('rm ' + spec_name)
df.to_csv(output_file)
return
|
...
import os
from astropy.io import fits
from pandas import DataFrame
# Bring in the package funcs
from specfit import do_specfit
...
# Download the spectrum
spec_name = \
download_spectra(spec_info['PLATE'], spec_info['FIBERID'],
spec_info['MJD'], spec_info['SURVEY'])
spec_df = do_specfit(spec_name, verbose=False)
if i == 0:
df = DataFrame(spec_df, columns=[spec_name[:-5]])
else:
df[spec_name[:-5]] = spec_df
if not keep_spectra:
os.system('rm ' + spec_name)
df.to_csv(output_file)
return
...
|
a3eb4602aa5ec87e6f78477c4789ed2fbde1cf93
|
stevedore/__init__.py
|
stevedore/__init__.py
|
from .extension import ExtensionManager
from .enabled import EnabledExtensionManager
from .named import NamedExtensionManager
from .hook import HookManager
from .driver import DriverManager
import logging
# Configure a NullHandler for our log messages in case
# the app we're used from does not set up logging.
LOG = logging.getLogger(__name__)
try:
LOG.addHandler(logging.NullHandler())
except AttributeError:
# No NullHandler, probably python 2.6
pass
|
__all__ = [
'ExtensionManager',
'EnabledExtensionManager',
'NamedExtensionManager',
'HookManager',
'DriverManager',
]
from .extension import ExtensionManager
from .enabled import EnabledExtensionManager
from .named import NamedExtensionManager
from .hook import HookManager
from .driver import DriverManager
import logging
# Configure a NullHandler for our log messages in case
# the app we're used from does not set up logging.
LOG = logging.getLogger('stevedore')
if hasattr(logging, 'NullHandler'):
LOG.addHandler(logging.NullHandler())
else:
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.lock = None
LOG.addHandler(NullHandler())
|
Update null log handling for py26
|
Update null log handling for py26
Python 2.6 does not have a NullHandler in the logging
module, so introduce a little class that does the same
work.
Also add __all__ to the package init so extra names are
not exported.
Resolves issue #2
Change-Id: Id59d394cd02372e2c31de336894f06653cb1e22d
|
Python
|
apache-2.0
|
mandeepdhami/stevedore,nelsnelson/stevedore,nelsnelson/stevedore,openstack/stevedore,varunarya10/stevedore,JioCloud/stevedore,JioCloud/stevedore,citrix-openstack-build/stevedore,mandeepdhami/stevedore,citrix-openstack-build/stevedore,varunarya10/stevedore
|
python
|
## Code Before:
from .extension import ExtensionManager
from .enabled import EnabledExtensionManager
from .named import NamedExtensionManager
from .hook import HookManager
from .driver import DriverManager
import logging
# Configure a NullHandler for our log messages in case
# the app we're used from does not set up logging.
LOG = logging.getLogger(__name__)
try:
LOG.addHandler(logging.NullHandler())
except AttributeError:
# No NullHandler, probably python 2.6
pass
## Instruction:
Update null log handling for py26
Python 2.6 does not have a NullHandler in the logging
module, so introduce a little class that does the same
work.
Also add __all__ to the package init so extra names are
not exported.
Resolves issue #2
Change-Id: Id59d394cd02372e2c31de336894f06653cb1e22d
## Code After:
__all__ = [
'ExtensionManager',
'EnabledExtensionManager',
'NamedExtensionManager',
'HookManager',
'DriverManager',
]
from .extension import ExtensionManager
from .enabled import EnabledExtensionManager
from .named import NamedExtensionManager
from .hook import HookManager
from .driver import DriverManager
import logging
# Configure a NullHandler for our log messages in case
# the app we're used from does not set up logging.
LOG = logging.getLogger('stevedore')
if hasattr(logging, 'NullHandler'):
LOG.addHandler(logging.NullHandler())
else:
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.lock = None
LOG.addHandler(NullHandler())
|
...
__all__ = [
'ExtensionManager',
'EnabledExtensionManager',
'NamedExtensionManager',
'HookManager',
'DriverManager',
]
from .extension import ExtensionManager
from .enabled import EnabledExtensionManager
...
# Configure a NullHandler for our log messages in case
# the app we're used from does not set up logging.
LOG = logging.getLogger('stevedore')
if hasattr(logging, 'NullHandler'):
LOG.addHandler(logging.NullHandler())
else:
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.lock = None
LOG.addHandler(NullHandler())
...
|
fce1b1bdb5a39bbe57b750cd453a9697b8447d6b
|
chat.py
|
chat.py
|
import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
# if chatroom doesn't exist create it!
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
|
import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
# if chatroom doesn't exist create it!
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
|
Correct position of comment :)
|
Correct position of comment :)
|
Python
|
bsd-3-clause
|
arturosevilla/notification-server-example,arturosevilla/notification-server-example
|
python
|
## Code Before:
import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
# if chatroom doesn't exist create it!
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
## Instruction:
Correct position of comment :)
## Code After:
import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
storage = get_redis()
return [
json.loads(m)
for m in storage.lrange('notifexample:' + chatroom, 0, -1)
]
def send_message(chatroom, user_id, name, message):
if '<script>' in message:
message += '-- Not this time DefConFags'
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
# if chatroom doesn't exist create it!
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
'author': name,
'userID': user_id,
'message': message,
'createdOn': created_on
})
)
|
// ... existing code ...
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
storage = get_redis()
return [
json.loads(m)
// ... modified code ...
storage = get_redis()
now = datetime.now()
created_on = now.strftime('%Y-%m-%d %H:%M:%S')
# if chatroom doesn't exist create it!
storage.rpush(
'notifexample:' + chatroom,
json.dumps({
// ... rest of the code ...
|
b501ee5dc2a41bf51f9f91c29501792338bf7269
|
automatron/backend/controller.py
|
automatron/backend/controller.py
|
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
def proxy(*args):
self.plugins.emit(IAutomatronClientActions[item], *args)
return proxy
|
from functools import partial
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
return partial(self.plugins.emit, IAutomatronClientActions[item])
|
Use functools.partial for client action proxy.
|
Use functools.partial for client action proxy.
|
Python
|
mit
|
automatron/automatron
|
python
|
## Code Before:
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
def proxy(*args):
self.plugins.emit(IAutomatronClientActions[item], *args)
return proxy
## Instruction:
Use functools.partial for client action proxy.
## Code After:
from functools import partial
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
return partial(self.plugins.emit, IAutomatronClientActions[item])
|
# ... existing code ...
from functools import partial
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
# ... modified code ...
self.plugins = PluginManager(self)
def __getattr__(self, item):
return partial(self.plugins.emit, IAutomatronClientActions[item])
# ... rest of the code ...
|
3e3f7b827e226146ec7d3efe523f1f900ac4e99a
|
sjconfparts/type.py
|
sjconfparts/type.py
|
class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true":
return True
elif str_object == "no" or str_object == "off" or str_object == "false":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
|
class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable":
return True
elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
|
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
|
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
|
Python
|
lgpl-2.1
|
SmartJog/sjconf,SmartJog/sjconf
|
python
|
## Code Before:
class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true":
return True
elif str_object == "no" or str_object == "off" or str_object == "false":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
## Instruction:
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
## Code After:
class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable":
return True
elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
|
// ... existing code ...
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable":
return True
elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable":
return False
else:
raise TypeError
// ... rest of the code ...
|
747c912a39f74f51cb5c38176b3e0328938d6d7a
|
setup.py
|
setup.py
|
"""Setup configuration specifying XManager dependencies."""
from setuptools import find_namespace_packages
from setuptools import setup
setup(
name='xmanager',
version='0.1.0',
description='A framework for managing experiments',
author='DeepMind Technologies Limited',
packages=find_namespace_packages(),
include_package_data=True,
package_data={'': ['*.sh', '*.sql']},
python_requires='>=3.7',
install_requires=[
'absl-py',
'async_generator',
'attrs',
'docker',
'google-api-core',
'google-api-python-client',
'google-cloud-aiplatform>=1.4.0',
'google-auth',
'google-cloud-storage',
'humanize',
'immutabledict',
'kubernetes',
'sqlalchemy==1.2',
'termcolor',
],
entry_points={
'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',],
},
)
|
"""Setup configuration specifying XManager dependencies."""
from setuptools import find_namespace_packages
from setuptools import setup
setup(
name='xmanager',
version='0.1.0',
description='A framework for managing experiments',
author='DeepMind Technologies Limited',
packages=find_namespace_packages(exclude=['examples.*']),
include_package_data=True,
package_data={'': ['*.sh', '*.sql']},
python_requires='>=3.7',
install_requires=[
'absl-py',
'async_generator',
'attrs',
'docker',
'google-api-core',
'google-api-python-client',
'google-auth',
'google-cloud-aiplatform>=1.4.0',
'google-cloud-storage',
'humanize',
'immutabledict',
'kubernetes',
'sqlalchemy==1.2',
'termcolor',
],
entry_points={
'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',],
},
)
|
Exclude examples from the package installation
|
Exclude examples from the package installation
PiperOrigin-RevId: 398741057
Change-Id: I7fd7921b8275b9f8b8994b0f20f0d40e814c3a23
GitOrigin-RevId: 4ca481ae4f7c6cf62e38a970f13a14716f9661fc
|
Python
|
apache-2.0
|
deepmind/xmanager,deepmind/xmanager
|
python
|
## Code Before:
"""Setup configuration specifying XManager dependencies."""
from setuptools import find_namespace_packages
from setuptools import setup
setup(
name='xmanager',
version='0.1.0',
description='A framework for managing experiments',
author='DeepMind Technologies Limited',
packages=find_namespace_packages(),
include_package_data=True,
package_data={'': ['*.sh', '*.sql']},
python_requires='>=3.7',
install_requires=[
'absl-py',
'async_generator',
'attrs',
'docker',
'google-api-core',
'google-api-python-client',
'google-cloud-aiplatform>=1.4.0',
'google-auth',
'google-cloud-storage',
'humanize',
'immutabledict',
'kubernetes',
'sqlalchemy==1.2',
'termcolor',
],
entry_points={
'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',],
},
)
## Instruction:
Exclude examples from the package installation
PiperOrigin-RevId: 398741057
Change-Id: I7fd7921b8275b9f8b8994b0f20f0d40e814c3a23
GitOrigin-RevId: 4ca481ae4f7c6cf62e38a970f13a14716f9661fc
## Code After:
"""Setup configuration specifying XManager dependencies."""
from setuptools import find_namespace_packages
from setuptools import setup
setup(
name='xmanager',
version='0.1.0',
description='A framework for managing experiments',
author='DeepMind Technologies Limited',
packages=find_namespace_packages(exclude=['examples.*']),
include_package_data=True,
package_data={'': ['*.sh', '*.sql']},
python_requires='>=3.7',
install_requires=[
'absl-py',
'async_generator',
'attrs',
'docker',
'google-api-core',
'google-api-python-client',
'google-auth',
'google-cloud-aiplatform>=1.4.0',
'google-cloud-storage',
'humanize',
'immutabledict',
'kubernetes',
'sqlalchemy==1.2',
'termcolor',
],
entry_points={
'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',],
},
)
|
...
version='0.1.0',
description='A framework for managing experiments',
author='DeepMind Technologies Limited',
packages=find_namespace_packages(exclude=['examples.*']),
include_package_data=True,
package_data={'': ['*.sh', '*.sql']},
python_requires='>=3.7',
...
'docker',
'google-api-core',
'google-api-python-client',
'google-auth',
'google-cloud-aiplatform>=1.4.0',
'google-cloud-storage',
'humanize',
'immutabledict',
...
|
dc186adbb1b49c821911af724725df4512fbf9f5
|
socialregistration/templatetags/facebook_tags.py
|
socialregistration/templatetags/facebook_tags.py
|
from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
next = context['next'] if 'next' in context else None
return dict(next=next, logged_in=logged_in)
|
from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
if 'next' in context:
next = context['next']
else:
next = None
return dict(next=next, logged_in=logged_in)
|
Use syntax compatible with Python 2.4
|
Use syntax compatible with Python 2.4
|
Python
|
mit
|
bopo/django-socialregistration,bopo/django-socialregistration,bopo/django-socialregistration,kapt/django-socialregistration,lgapontes/django-socialregistration,mark-adams/django-socialregistration,0101/django-socialregistration,praekelt/django-socialregistration,flashingpumpkin/django-socialregistration,itmustbejj/django-socialregistration,Soovox/django-socialregistration,minlex/django-socialregistration,brodie/django-socialregistration,minlex/django-socialregistration,mark-adams/django-socialregistration,aditweb/django-socialregistration,aditweb/django-socialregistration,flashingpumpkin/django-socialregistration,brodie/django-socialregistration,minlex/django-socialregistration,amakhnach/django-socialregistration,mark-adams/django-socialregistration,aditweb/django-socialregistration,lgapontes/django-socialregistration,lgapontes/django-socialregistration,kapt/django-socialregistration
|
python
|
## Code Before:
from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
next = context['next'] if 'next' in context else None
return dict(next=next, logged_in=logged_in)
## Instruction:
Use syntax compatible with Python 2.4
## Code After:
from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
if 'next' in context:
next = context['next']
else:
next = None
return dict(next=next, logged_in=logged_in)
|
// ... existing code ...
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
if 'next' in context:
next = context['next']
else:
next = None
return dict(next=next, logged_in=logged_in)
// ... rest of the code ...
|
5ada6a5084c25bcee71f7a1961f60c5decaed9d4
|
setup.py
|
setup.py
|
import codecs
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import carrot
setup(
name='carrot',
version=carrot.__version__,
description=carrot.__doc__,
author=carrot.__author__,
author_email=carrot.__contact__,
url=carrot.__homepage__,
platforms=["any"],
packages=find_packages(exclude=['ez_setup']),
test_suite="nose.collector",
install_requires=[
'amqplib',
],
classifiers=[
"Development Status :: 3 - Alpha",
"Framework :: Django",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
long_description=codecs.open('README.rst', "r", "utf-8").read(),
)
|
import codecs
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import carrot
setup(
name='carrot',
version=carrot.__version__,
description=carrot.__doc__,
author=carrot.__author__,
author_email=carrot.__contact__,
url=carrot.__homepage__,
platforms=["any"],
packages=find_packages(exclude=['ez_setup']),
test_suite="nose.collector",
install_requires=[
'amqplib',
],
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: Django",
"Operating System :: OS Independent",
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Intended Audience :: Developers",
"Topic :: Communications",
"Topic :: System :: Distributed Computing",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=codecs.open('README.rst', "r", "utf-8").read(),
)
|
Update development status trove classifier from Alpha to Beta
|
Update development status trove classifier from Alpha to Beta
|
Python
|
bsd-3-clause
|
runeh/carrot,ask/carrot,ask/carrot
|
python
|
## Code Before:
import codecs
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import carrot
setup(
name='carrot',
version=carrot.__version__,
description=carrot.__doc__,
author=carrot.__author__,
author_email=carrot.__contact__,
url=carrot.__homepage__,
platforms=["any"],
packages=find_packages(exclude=['ez_setup']),
test_suite="nose.collector",
install_requires=[
'amqplib',
],
classifiers=[
"Development Status :: 3 - Alpha",
"Framework :: Django",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
long_description=codecs.open('README.rst', "r", "utf-8").read(),
)
## Instruction:
Update development status trove classifier from Alpha to Beta
## Code After:
import codecs
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import carrot
setup(
name='carrot',
version=carrot.__version__,
description=carrot.__doc__,
author=carrot.__author__,
author_email=carrot.__contact__,
url=carrot.__homepage__,
platforms=["any"],
packages=find_packages(exclude=['ez_setup']),
test_suite="nose.collector",
install_requires=[
'amqplib',
],
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: Django",
"Operating System :: OS Independent",
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Intended Audience :: Developers",
"Topic :: Communications",
"Topic :: System :: Distributed Computing",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=codecs.open('README.rst', "r", "utf-8").read(),
)
|
# ... existing code ...
'amqplib',
],
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: Django",
"Operating System :: OS Independent",
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Intended Audience :: Developers",
"Topic :: Communications",
"Topic :: System :: Distributed Computing",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=codecs.open('README.rst', "r", "utf-8").read(),
)
# ... rest of the code ...
|
450f082237e5b302988cece5c6eb091a5d8503df
|
examples/img_server.py
|
examples/img_server.py
|
import io
import picamera
import time
from nuts import UDPAuthChannel
def take_single_picture():
# Create an in-memory stream
my_stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.start_preview()
# Camera warm-up time
time.sleep(2)
camera.capture(my_stream, 'jpeg')
my_stream.seek(0)
return my_stream.getvalue()
def ceildiv(dividend, divisor):
return (dividend + divisor - 1) // divisor
channel = UDPAuthChannel('secret')
channel.listen( ('10.0.0.1', 8001) )
while True:
msg = channel.receive()
print msg
img = take_single_picture()
num_chunks = ceildiv(len(img), msg.session.mtu)
channel.send(str(num_chunks), msg.sender)
for i in range(num_chunks):
chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu]
print('Sending chunk %d of %d' % (i, num_chunks))
channel.send(chunk, msg.sender)
time.sleep(0.1)
|
import io
import picamera
import time
from nuts import UDPAuthChannel
def take_single_picture():
# Create an in-memory stream
my_stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.start_preview()
# Camera warm-up time
time.sleep(2)
camera.capture(my_stream, 'jpeg')
my_stream.seek(0)
return my_stream.getvalue()
def ceildiv(dividend, divisor):
return (dividend + divisor - 1) // divisor
channel = UDPAuthChannel('secret')
channel.listen( ('10.0.0.1', 8001) )
while True:
msg = channel.receive()
print('%s said: %s' % (msg.sender, msg))
img = take_single_picture()
num_chunks = ceildiv(len(img), msg.session.mtu)
channel.send(str(num_chunks), msg.sender)
for i in range(num_chunks):
chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu]
print('Sending chunk %d of %d' % (i, num_chunks))
channel.send(chunk, msg.sender)
time.sleep(0.1)
|
Remove python2 print from img server
|
Remove python2 print from img server
|
Python
|
mit
|
thusoy/nuts-auth,thusoy/nuts-auth
|
python
|
## Code Before:
import io
import picamera
import time
from nuts import UDPAuthChannel
def take_single_picture():
# Create an in-memory stream
my_stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.start_preview()
# Camera warm-up time
time.sleep(2)
camera.capture(my_stream, 'jpeg')
my_stream.seek(0)
return my_stream.getvalue()
def ceildiv(dividend, divisor):
return (dividend + divisor - 1) // divisor
channel = UDPAuthChannel('secret')
channel.listen( ('10.0.0.1', 8001) )
while True:
msg = channel.receive()
print msg
img = take_single_picture()
num_chunks = ceildiv(len(img), msg.session.mtu)
channel.send(str(num_chunks), msg.sender)
for i in range(num_chunks):
chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu]
print('Sending chunk %d of %d' % (i, num_chunks))
channel.send(chunk, msg.sender)
time.sleep(0.1)
## Instruction:
Remove python2 print from img server
## Code After:
import io
import picamera
import time
from nuts import UDPAuthChannel
def take_single_picture():
# Create an in-memory stream
my_stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.start_preview()
# Camera warm-up time
time.sleep(2)
camera.capture(my_stream, 'jpeg')
my_stream.seek(0)
return my_stream.getvalue()
def ceildiv(dividend, divisor):
return (dividend + divisor - 1) // divisor
channel = UDPAuthChannel('secret')
channel.listen( ('10.0.0.1', 8001) )
while True:
msg = channel.receive()
print('%s said: %s' % (msg.sender, msg))
img = take_single_picture()
num_chunks = ceildiv(len(img), msg.session.mtu)
channel.send(str(num_chunks), msg.sender)
for i in range(num_chunks):
chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu]
print('Sending chunk %d of %d' % (i, num_chunks))
channel.send(chunk, msg.sender)
time.sleep(0.1)
|
...
channel.listen( ('10.0.0.1', 8001) )
while True:
msg = channel.receive()
print('%s said: %s' % (msg.sender, msg))
img = take_single_picture()
num_chunks = ceildiv(len(img), msg.session.mtu)
channel.send(str(num_chunks), msg.sender)
...
|
21f6d03449217952cb981719345eccfbb1ec84b3
|
isogram/isogram.py
|
isogram/isogram.py
|
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
|
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's marginally slower
|
Add note about str.isalpha() method as an alternative
|
Add note about str.isalpha() method as an alternative
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
python
|
## Code Before:
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
## Instruction:
Add note about str.isalpha() method as an alternative
## Code After:
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's marginally slower
|
# ... existing code ...
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's marginally slower
# ... rest of the code ...
|
8db7072cef4c5ddbf408cdf1740e926f4d78747b
|
Functions/echo-python/lambda_function.py
|
Functions/echo-python/lambda_function.py
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = False
verbose = False
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
return event
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
"""Define the structure of log events to match all other CloudWatch Log Events logged by AWS Lambda.
"""
def __init__(self, context):
"""Define the instance of the context object.
:param context: Lambda context object
"""
self.context = context
def event(self, message, event_prefix='LOG'):
# type: (any, str) -> None
"""Print an event into the CloudWatch Logs stream for the Function's invocation.
:param message: The information to be logged (required)
:param event_prefix: The prefix that appears before the 'RequestId' (default 'LOG')
:return:
"""
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
return None
def lambda_handler(event, context):
"""AWS Lambda executes the 'lambda_handler' function on invocation.
:param event: Ingested JSON event object provided at invocation
:param context: Lambda context object, containing information specific to the invocation and Function
:return: Final response to AWS Lambda, and passed to the invoker if the invocation type is RequestResponse
"""
# Instantiate our CloudWatch logging class
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
return event
def local_test():
"""Testing on a local development machine (outside of AWS Lambda) is made possible by...
"""
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
Add documentation, and modify default values
|
Add documentation, and modify default values
|
Python
|
apache-2.0
|
andrewdefilippis/aws-lambda
|
python
|
## Code Before:
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = False
verbose = False
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
return event
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
## Instruction:
Add documentation, and modify default values
## Code After:
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
"""Define the structure of log events to match all other CloudWatch Log Events logged by AWS Lambda.
"""
def __init__(self, context):
"""Define the instance of the context object.
:param context: Lambda context object
"""
self.context = context
def event(self, message, event_prefix='LOG'):
# type: (any, str) -> None
"""Print an event into the CloudWatch Logs stream for the Function's invocation.
:param message: The information to be logged (required)
:param event_prefix: The prefix that appears before the 'RequestId' (default 'LOG')
:return:
"""
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
return None
def lambda_handler(event, context):
"""AWS Lambda executes the 'lambda_handler' function on invocation.
:param event: Ingested JSON event object provided at invocation
:param context: Lambda context object, containing information specific to the invocation and Function
:return: Final response to AWS Lambda, and passed to the invoker if the invocation type is RequestResponse
"""
# Instantiate our CloudWatch logging class
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
return event
def local_test():
"""Testing on a local development machine (outside of AWS Lambda) is made possible by...
"""
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
# ... existing code ...
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
"""Define the structure of log events to match all other CloudWatch Log Events logged by AWS Lambda.
"""
def __init__(self, context):
"""Define the instance of the context object.
:param context: Lambda context object
"""
self.context = context
def event(self, message, event_prefix='LOG'):
# type: (any, str) -> None
"""Print an event into the CloudWatch Logs stream for the Function's invocation.
:param message: The information to be logged (required)
:param event_prefix: The prefix that appears before the 'RequestId' (default 'LOG')
:return:
"""
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
# ... modified code ...
message
))
return None
def lambda_handler(event, context):
"""AWS Lambda executes the 'lambda_handler' function on invocation.
:param event: Ingested JSON event object provided at invocation
:param context: Lambda context object, containing information specific to the invocation and Function
:return: Final response to AWS Lambda, and passed to the invoker if the invocation type is RequestResponse
"""
# Instantiate our CloudWatch logging class
log = CWLogs(context)
if verbose is True:
...
def local_test():
"""Testing on a local development machine (outside of AWS Lambda) is made possible by...
"""
import context
with open('event.json', 'r') as f:
# ... rest of the code ...
|
536c2067f61fc4e5bb9ff8fb3202ec8ef19874ff
|
graphalytics-core/src/main/java/nl/tudelft/graphalytics/util/UuidUtil.java
|
graphalytics-core/src/main/java/nl/tudelft/graphalytics/util/UuidUtil.java
|
/*
* Copyright 2015 Delft University of Technology
*
* 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 nl.tudelft.graphalytics.util;
import java.util.UUID;
/**
* @author Wing Lung Ngai
*/
public class UuidUtil {
public static String getRandomUUID() {
return String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
}
public static String getRandomUUID(String prefix, int length) {
return prefix + String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l).substring(0, length);
}
public static String getRandomUUID(int length) {
return getRandomUUID("", length);
}
}
|
/*
* Copyright 2015 Delft University of Technology
*
* 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 nl.tudelft.graphalytics.util;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* @author Wing Lung Ngai
*/
public class UuidUtil {
private static Set<String> usedUUIDs = new HashSet<>();
public static String getRandomUUID() {
String uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
while(usedUUIDs.contains(uuid)) {
uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(String prefix, int length) {
String uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
while(usedUUIDs.contains(uuid)) {
uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(int length) {
return getRandomUUID("", length);
}
}
|
Make sure short UUIDs are unique in the same benchmark.
|
Make sure short UUIDs are unique in the same benchmark.
|
Java
|
apache-2.0
|
ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics,ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics
|
java
|
## Code Before:
/*
* Copyright 2015 Delft University of Technology
*
* 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 nl.tudelft.graphalytics.util;
import java.util.UUID;
/**
* @author Wing Lung Ngai
*/
public class UuidUtil {
public static String getRandomUUID() {
return String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
}
public static String getRandomUUID(String prefix, int length) {
return prefix + String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l).substring(0, length);
}
public static String getRandomUUID(int length) {
return getRandomUUID("", length);
}
}
## Instruction:
Make sure short UUIDs are unique in the same benchmark.
## Code After:
/*
* Copyright 2015 Delft University of Technology
*
* 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 nl.tudelft.graphalytics.util;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* @author Wing Lung Ngai
*/
public class UuidUtil {
private static Set<String> usedUUIDs = new HashSet<>();
public static String getRandomUUID() {
String uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
while(usedUUIDs.contains(uuid)) {
uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(String prefix, int length) {
String uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
while(usedUUIDs.contains(uuid)) {
uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(int length) {
return getRandomUUID("", length);
}
}
|
# ... existing code ...
package nl.tudelft.graphalytics.util;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
# ... modified code ...
*/
public class UuidUtil {
private static Set<String> usedUUIDs = new HashSet<>();
public static String getRandomUUID() {
String uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
while(usedUUIDs.contains(uuid)) {
uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(String prefix, int length) {
String uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
while(usedUUIDs.contains(uuid)) {
uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
}
usedUUIDs.add(uuid);
return uuid;
}
public static String getRandomUUID(int length) {
# ... rest of the code ...
|
6d18ff715a5fa3059ddb609c1abdbbb06b15ad63
|
fuel/downloaders/celeba.py
|
fuel/downloaders/celeba.py
|
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
|
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
|
Update download links for CelebA files
|
Update download links for CelebA files
|
Python
|
mit
|
mila-udem/fuel,dmitriy-serdyuk/fuel,dmitriy-serdyuk/fuel,mila-udem/fuel,vdumoulin/fuel,vdumoulin/fuel
|
python
|
## Code Before:
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
## Instruction:
Update download links for CelebA files
## Code After:
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
|
...
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
...
|
cfb0bda6096378de428a1460823626f3dc4c9059
|
spyder_terminal/__init__.py
|
spyder_terminal/__init__.py
|
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 2, 1)
__version__ = '.'.join(map(str, VERSION_INFO))
|
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 3, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
|
Set package version info to 0.3.0.dev0
|
Set package version info to 0.3.0.dev0
|
Python
|
mit
|
spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal
|
python
|
## Code Before:
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 2, 1)
__version__ = '.'.join(map(str, VERSION_INFO))
## Instruction:
Set package version info to 0.3.0.dev0
## Code After:
"""Spyder Terminal Plugin."""
from .terminalplugin import TerminalPlugin as PLUGIN_CLASS
PLUGIN_CLASS
VERSION_INFO = (0, 3, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
|
# ... existing code ...
PLUGIN_CLASS
VERSION_INFO = (0, 3, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
# ... rest of the code ...
|
a17b3f1b84d9c87ef3e469a140896dc4dabf9a2b
|
examples/vhosts.py
|
examples/vhosts.py
|
from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
bp = Blueprint("bp", host="bp.example.com")
@app.route('/', host=["example.com",
"somethingelse.com",
"therestofyourdomains.com"])
async def hello(request):
return response.text("Some defaults")
@app.route('/', host="example.com")
async def hello(request):
return response.text("Answer")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
@bp.route("/question")
async def hello(request):
return response.text("What is the meaning of life?")
@bp.route("/answer")
async def hello(request):
return response.text("42")
app.register_blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
|
from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
bp = Blueprint("bp", host="bp.example.com")
@app.route('/', host=["example.com",
"somethingelse.com",
"therestofyourdomains.com"])
async def hello(request):
return response.text("Some defaults")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
@bp.route("/question")
async def hello(request):
return response.text("What is the meaning of life?")
@bp.route("/answer")
async def hello(request):
return response.text("42")
app.blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
|
Use of register_blueprint will be deprecated, why not upgrade?
|
Use of register_blueprint will be deprecated, why not upgrade?
|
Python
|
mit
|
channelcat/sanic,channelcat/sanic,Tim-Erwin/sanic,ashleysommer/sanic,yunstanford/sanic,ashleysommer/sanic,lixxu/sanic,Tim-Erwin/sanic,lixxu/sanic,r0fls/sanic,lixxu/sanic,channelcat/sanic,ashleysommer/sanic,jrocketfingers/sanic,r0fls/sanic,jrocketfingers/sanic,yunstanford/sanic,lixxu/sanic,channelcat/sanic,yunstanford/sanic,yunstanford/sanic
|
python
|
## Code Before:
from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
bp = Blueprint("bp", host="bp.example.com")
@app.route('/', host=["example.com",
"somethingelse.com",
"therestofyourdomains.com"])
async def hello(request):
return response.text("Some defaults")
@app.route('/', host="example.com")
async def hello(request):
return response.text("Answer")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
@bp.route("/question")
async def hello(request):
return response.text("What is the meaning of life?")
@bp.route("/answer")
async def hello(request):
return response.text("42")
app.register_blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
## Instruction:
Use of register_blueprint will be deprecated, why not upgrade?
## Code After:
from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
bp = Blueprint("bp", host="bp.example.com")
@app.route('/', host=["example.com",
"somethingelse.com",
"therestofyourdomains.com"])
async def hello(request):
return response.text("Some defaults")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
@bp.route("/question")
async def hello(request):
return response.text("What is the meaning of life?")
@bp.route("/answer")
async def hello(request):
return response.text("42")
app.blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
|
# ... existing code ...
async def hello(request):
return response.text("Some defaults")
@app.route('/', host="sub.example.com")
async def hello(request):
return response.text("42")
# ... modified code ...
async def hello(request):
return response.text("42")
app.blueprint(bp)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
# ... rest of the code ...
|
4b6d8af563f201208ac846da94dc94bd55348178
|
src/bakatxt/gui/FirstTaskBox.java
|
src/bakatxt/gui/FirstTaskBox.java
|
//@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
// TODO fix topRounded method
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height - UIHelper.WINDOW_ROUNDNESS);
curveTo(width, height, width, height, width - UIHelper.WINDOW_ROUNDNESS, height);
lineTo(UIHelper.WINDOW_ROUNDNESS, height);
curveTo(0, height, 0, height, 0, height - UIHelper.WINDOW_ROUNDNESS);
lineTo(0, 0);
closePath();
}
}
}
|
//@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, height);
lineTo(0, UIHelper.WINDOW_ROUNDNESS);
curveTo(0, 0, 0, 0, UIHelper.WINDOW_ROUNDNESS, 0);
lineTo(width - UIHelper.WINDOW_ROUNDNESS, 0);
curveTo(width, 0, width, 0, width, UIHelper.WINDOW_ROUNDNESS);
lineTo(width, height);
lineTo(0, height);
closePath();
}
}
}
|
Fix topRounded method to draw the correct shape
|
Fix topRounded method to draw the correct shape
|
Java
|
mit
|
cs2103aug2014-t09-4j/main
|
java
|
## Code Before:
//@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
// TODO fix topRounded method
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height - UIHelper.WINDOW_ROUNDNESS);
curveTo(width, height, width, height, width - UIHelper.WINDOW_ROUNDNESS, height);
lineTo(UIHelper.WINDOW_ROUNDNESS, height);
curveTo(0, height, 0, height, 0, height - UIHelper.WINDOW_ROUNDNESS);
lineTo(0, 0);
closePath();
}
}
}
## Instruction:
Fix topRounded method to draw the correct shape
## Code After:
//@author A0116538A
package bakatxt.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import bakatxt.core.Task;
/**
* This class dictates the color and shape of the box which the task will be put in.
* This box is specifically for a top most box.
*
*/
class FirstTaskBox extends TaskBox {
public FirstTaskBox(Task task, Color backgroundColor) {
super(task, backgroundColor);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setRenderingHints(UIHelper.antiAlias());
g2d.fill(new TopRounded(getWidth(), getHeight()));
g2d.dispose();
super.paintComponent(g);
}
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, height);
lineTo(0, UIHelper.WINDOW_ROUNDNESS);
curveTo(0, 0, 0, 0, UIHelper.WINDOW_ROUNDNESS, 0);
lineTo(width - UIHelper.WINDOW_ROUNDNESS, 0);
curveTo(width, 0, width, 0, width, UIHelper.WINDOW_ROUNDNESS);
lineTo(width, height);
lineTo(0, height);
closePath();
}
}
}
|
...
super.paintComponent(g);
}
class TopRounded extends Path2D.Double {
public TopRounded(double width, double height) {
moveTo(0, height);
lineTo(0, UIHelper.WINDOW_ROUNDNESS);
curveTo(0, 0, 0, 0, UIHelper.WINDOW_ROUNDNESS, 0);
lineTo(width - UIHelper.WINDOW_ROUNDNESS, 0);
curveTo(width, 0, width, 0, width, UIHelper.WINDOW_ROUNDNESS);
lineTo(width, height);
lineTo(0, height);
closePath();
}
}
...
|
b86c53c388c39baee1ddfe3a615cdad20d272055
|
antcolony/util.py
|
antcolony/util.py
|
import json
def avg(iterable):
return sum(iterable) / len(iterable)
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
|
import json
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
|
Make avg() work with iterators
|
Make avg() work with iterators
|
Python
|
bsd-3-clause
|
ppolewicz/ant-colony,ppolewicz/ant-colony
|
python
|
## Code Before:
import json
def avg(iterable):
return sum(iterable) / len(iterable)
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
## Instruction:
Make avg() work with iterators
## Code After:
import json
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
|
// ... existing code ...
import json
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
// ... rest of the code ...
|
81a5997227cb9c8086b3cebf305e539eb2bf1990
|
daas.py
|
daas.py
|
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*12, dl_interval=3600*6, max_downloads=5, to_imgur=True, to_tumblr=True):
"""Run periodic search/download/extract_and_upload operations"""
#print "Fetching new videos and consolidating queue..."
#yt.populate_queue()
#print "Downloading up to",max_downloads,"videos..."
#yt.dl(max_downloads)
extract_and_upload(vid_path, to_imgur, to_tumblr)
if search_interval:
search_timer = set_interval(search_interval, yt.populate_queue)
if dl_interval:
dl_timer = set_interval(dl_interval, yt.dl, max_downloads)
if post_interval:
post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr)
if __name__ == '__main__':
print "Running from console..."
death_as_a_service()
|
import os
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*6, dl_interval=3600*3, max_downloads=4, to_imgur=True, to_tumblr=True):
"""Run periodic search/download/extract_and_upload operations"""
print "Fetching new videos and consolidating queue..."
yt.populate_queue()
if len([file for file in os.listdir(vid_path) if not file.endswith('part') and not file.startswith('.')]) < 4:
print "Downloading up to",max_downloads,"videos..."
yt.dl(max_downloads)
extract_and_upload(vid_path, to_imgur, to_tumblr)
if search_interval:
search_timer = set_interval(search_interval, yt.populate_queue)
if dl_interval:
dl_timer = set_interval(dl_interval, yt.dl, max_downloads)
if post_interval:
post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr)
if __name__ == '__main__':
print "Running from console..."
death_as_a_service()
|
Stop getting videos every time script starts
|
Stop getting videos every time script starts
|
Python
|
mit
|
BooDoo/death_extractor
|
python
|
## Code Before:
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*12, dl_interval=3600*6, max_downloads=5, to_imgur=True, to_tumblr=True):
"""Run periodic search/download/extract_and_upload operations"""
#print "Fetching new videos and consolidating queue..."
#yt.populate_queue()
#print "Downloading up to",max_downloads,"videos..."
#yt.dl(max_downloads)
extract_and_upload(vid_path, to_imgur, to_tumblr)
if search_interval:
search_timer = set_interval(search_interval, yt.populate_queue)
if dl_interval:
dl_timer = set_interval(dl_interval, yt.dl, max_downloads)
if post_interval:
post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr)
if __name__ == '__main__':
print "Running from console..."
death_as_a_service()
## Instruction:
Stop getting videos every time script starts
## Code After:
import os
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*6, dl_interval=3600*3, max_downloads=4, to_imgur=True, to_tumblr=True):
"""Run periodic search/download/extract_and_upload operations"""
print "Fetching new videos and consolidating queue..."
yt.populate_queue()
if len([file for file in os.listdir(vid_path) if not file.endswith('part') and not file.startswith('.')]) < 4:
print "Downloading up to",max_downloads,"videos..."
yt.dl(max_downloads)
extract_and_upload(vid_path, to_imgur, to_tumblr)
if search_interval:
search_timer = set_interval(search_interval, yt.populate_queue)
if dl_interval:
dl_timer = set_interval(dl_interval, yt.dl, max_downloads)
if post_interval:
post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr)
if __name__ == '__main__':
print "Running from console..."
death_as_a_service()
|
# ... existing code ...
import os
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*6, dl_interval=3600*3, max_downloads=4, to_imgur=True, to_tumblr=True):
"""Run periodic search/download/extract_and_upload operations"""
print "Fetching new videos and consolidating queue..."
yt.populate_queue()
if len([file for file in os.listdir(vid_path) if not file.endswith('part') and not file.startswith('.')]) < 4:
print "Downloading up to",max_downloads,"videos..."
yt.dl(max_downloads)
extract_and_upload(vid_path, to_imgur, to_tumblr)
if search_interval:
# ... rest of the code ...
|
3ff6b8a2e8eecf48bfe74d5a0b0972e29ace15fd
|
imagetagger/imagetagger/annotations/admin.py
|
imagetagger/imagetagger/annotations/admin.py
|
from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
admin.site.register(Annotation)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(Verification)
admin.site.register(ExportFormat)
|
from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
@admin.register(Annotation)
class AnnotationAdmin(admin.ModelAdmin):
raw_id_fields = (
'image',
)
@admin.register(Verification)
class VerificationAdmin(admin.ModelAdmin):
raw_id_fields = (
'annotation',
)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(ExportFormat)
|
Use raw id fields for annotation and verification foreign keys
|
Use raw id fields for annotation and verification foreign keys
|
Python
|
mit
|
bit-bots/imagetagger,bit-bots/imagetagger,bit-bots/imagetagger,bit-bots/imagetagger
|
python
|
## Code Before:
from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
admin.site.register(Annotation)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(Verification)
admin.site.register(ExportFormat)
## Instruction:
Use raw id fields for annotation and verification foreign keys
## Code After:
from django.contrib import admin
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
@admin.register(Annotation)
class AnnotationAdmin(admin.ModelAdmin):
raw_id_fields = (
'image',
)
@admin.register(Verification)
class VerificationAdmin(admin.ModelAdmin):
raw_id_fields = (
'annotation',
)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(ExportFormat)
|
// ... existing code ...
from .models import Annotation, AnnotationType, Export, Verification, ExportFormat
@admin.register(Annotation)
class AnnotationAdmin(admin.ModelAdmin):
raw_id_fields = (
'image',
)
@admin.register(Verification)
class VerificationAdmin(admin.ModelAdmin):
raw_id_fields = (
'annotation',
)
admin.site.register(AnnotationType)
admin.site.register(Export)
admin.site.register(ExportFormat)
// ... rest of the code ...
|
48fa78cf488b227b33355362ee1d7110936a6671
|
compiler/modules/CommonMark/src/config.h
|
compiler/modules/CommonMark/src/config.h
|
typedef char bool;
# define true 1
# define false 0
#endif
#define CMARK_ATTRIBUTE(list)
#ifndef CHY_HAS_VA_COPY
#define va_copy(dest, src) ((dest) = (src))
#endif
|
typedef char bool;
# define true 1
# define false 0
#endif
#define CMARK_ATTRIBUTE(list)
#ifndef CHY_HAS_VA_COPY
#define va_copy(dest, src) ((dest) = (src))
#endif
#define inline CHY_INLINE
|
Use CHY_INLINE in CommonMark source
|
Use CHY_INLINE in CommonMark source
|
C
|
apache-2.0
|
rectang/lucy-clownfish,nwellnhof/lucy-clownfish,rectang/lucy-clownfish,rectang/lucy-clownfish,apache/lucy-clownfish,apache/lucy-clownfish,apache/lucy-clownfish,rectang/lucy-clownfish,rectang/lucy-clownfish,nwellnhof/lucy-clownfish,apache/lucy-clownfish,nwellnhof/lucy-clownfish,nwellnhof/lucy-clownfish,rectang/lucy-clownfish,rectang/lucy-clownfish,nwellnhof/lucy-clownfish,apache/lucy-clownfish,rectang/lucy-clownfish,apache/lucy-clownfish,apache/lucy-clownfish,nwellnhof/lucy-clownfish,nwellnhof/lucy-clownfish,rectang/lucy-clownfish,apache/lucy-clownfish,nwellnhof/lucy-clownfish
|
c
|
## Code Before:
typedef char bool;
# define true 1
# define false 0
#endif
#define CMARK_ATTRIBUTE(list)
#ifndef CHY_HAS_VA_COPY
#define va_copy(dest, src) ((dest) = (src))
#endif
## Instruction:
Use CHY_INLINE in CommonMark source
## Code After:
typedef char bool;
# define true 1
# define false 0
#endif
#define CMARK_ATTRIBUTE(list)
#ifndef CHY_HAS_VA_COPY
#define va_copy(dest, src) ((dest) = (src))
#endif
#define inline CHY_INLINE
|
# ... existing code ...
#ifndef CHY_HAS_VA_COPY
#define va_copy(dest, src) ((dest) = (src))
#endif
#define inline CHY_INLINE
# ... rest of the code ...
|
2fd5f0656434340763cc51c47238d4a40e61789b
|
modernrpc/__init__.py
|
modernrpc/__init__.py
|
from packaging.version import Version
import django
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
if Version(django.get_version()) < Version("3.2"):
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
# import pkg_resources; version = pkg_resources.get_distribution('django-modern-rpc').version
|
from distutils.version import StrictVersion
import django
# distutils.version, overridden by setuptools._distutils.version in recent python releases, is deprecated
# and will be removed in Python 3.12. We will probably drop Django < 3.2 until then, so this should be fine
if StrictVersion(django.get_version()) < StrictVersion("3.2"):
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
# import pkg_resources; version = pkg_resources.get_distribution('django-modern-rpc').version
|
Remove unwanted dependency to 'packaging'
|
Remove unwanted dependency to 'packaging'
|
Python
|
mit
|
alorence/django-modern-rpc,alorence/django-modern-rpc
|
python
|
## Code Before:
from packaging.version import Version
import django
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
if Version(django.get_version()) < Version("3.2"):
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
# import pkg_resources; version = pkg_resources.get_distribution('django-modern-rpc').version
## Instruction:
Remove unwanted dependency to 'packaging'
## Code After:
from distutils.version import StrictVersion
import django
# distutils.version, overridden by setuptools._distutils.version in recent python releases, is deprecated
# and will be removed in Python 3.12. We will probably drop Django < 3.2 until then, so this should be fine
if StrictVersion(django.get_version()) < StrictVersion("3.2"):
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
# import pkg_resources; version = pkg_resources.get_distribution('django-modern-rpc').version
|
// ... existing code ...
from distutils.version import StrictVersion
import django
# distutils.version, overridden by setuptools._distutils.version in recent python releases, is deprecated
# and will be removed in Python 3.12. We will probably drop Django < 3.2 until then, so this should be fine
if StrictVersion(django.get_version()) < StrictVersion("3.2"):
# Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases
# See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery
default_app_config = "modernrpc.apps.ModernRpcConfig"
# Package version is now stored in pyproject.toml only. To retrieve it from code, use:
// ... rest of the code ...
|
1eb23656da87950e1a3f1ebed1aad05dfa0da13c
|
modules/Core/src/main/java/jpower/core/config/ConfigFile.java
|
modules/Core/src/main/java/jpower/core/config/ConfigFile.java
|
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final Path path;
private final Configuration configuration = new Configuration();
/**
* Creates a ConfigFile from the path
*
* @param path path
*/
public ConfigFile(Path path)
{
this.path = path;
}
/**
* Creates a ConfigFile from the file
* @param file file
*/
public ConfigFile(File file)
{
this.path = file.toPath();
}
/**
* Loads the Configuration File
*/
@Override
public void load()
{
try
{
configuration.load(path.toFile());
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the Configuration File
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the Configuration from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
|
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final File file;
private final Configuration configuration = new Configuration();
/**
* Creates a @link{ConfigFile} from the Path
*
* @param path the path to load the configuration from
*/
public ConfigFile(Path path)
{
this(path.toFile());
}
/**
* Creates a {@link ConfigFile} from the file
* @param file the file to load the configuration from
*/
public ConfigFile(File file)
{
this.file = file;
}
/**
* Loads the configuration file
*/
@Override
public void load()
{
try
{
configuration.load(file);
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the configuration file
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the {@link Configuration} from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
|
Fix Silly Code and cleanup JavaDoc
|
Configuration: Fix Silly Code and cleanup JavaDoc
|
Java
|
mit
|
DirectMyFile/JPower
|
java
|
## Code Before:
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final Path path;
private final Configuration configuration = new Configuration();
/**
* Creates a ConfigFile from the path
*
* @param path path
*/
public ConfigFile(Path path)
{
this.path = path;
}
/**
* Creates a ConfigFile from the file
* @param file file
*/
public ConfigFile(File file)
{
this.path = file.toPath();
}
/**
* Loads the Configuration File
*/
@Override
public void load()
{
try
{
configuration.load(path.toFile());
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the Configuration File
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the Configuration from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
## Instruction:
Configuration: Fix Silly Code and cleanup JavaDoc
## Code After:
package jpower.core.config;
import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
* Configuration File Wrapper
*/
public class ConfigFile implements Loadable, Reloadable
{
private final File file;
private final Configuration configuration = new Configuration();
/**
* Creates a @link{ConfigFile} from the Path
*
* @param path the path to load the configuration from
*/
public ConfigFile(Path path)
{
this(path.toFile());
}
/**
* Creates a {@link ConfigFile} from the file
* @param file the file to load the configuration from
*/
public ConfigFile(File file)
{
this.file = file;
}
/**
* Loads the configuration file
*/
@Override
public void load()
{
try
{
configuration.load(file);
}
catch (IOException e)
{
ExceptionUtils.throwUnchecked(e);
}
}
/**
* Reloads the configuration file
*/
@Override
public void reload()
{
configuration.reset();
load();
}
/**
* Gets the {@link Configuration} from the File
* @return configuration
*/
public Configuration getConfiguration()
{
return configuration;
}
}
|
# ... existing code ...
*/
public class ConfigFile implements Loadable, Reloadable
{
private final File file;
private final Configuration configuration = new Configuration();
/**
* Creates a @link{ConfigFile} from the Path
*
* @param path the path to load the configuration from
*/
public ConfigFile(Path path)
{
this(path.toFile());
}
/**
* Creates a {@link ConfigFile} from the file
* @param file the file to load the configuration from
*/
public ConfigFile(File file)
{
this.file = file;
}
/**
* Loads the configuration file
*/
@Override
public void load()
# ... modified code ...
{
try
{
configuration.load(file);
}
catch (IOException e)
{
...
}
/**
* Reloads the configuration file
*/
@Override
public void reload()
...
}
/**
* Gets the {@link Configuration} from the File
* @return configuration
*/
public Configuration getConfiguration()
# ... rest of the code ...
|
0d73f5d18a927ffebc3fa32180b608f0c96dcdf1
|
Exe_04.py
|
Exe_04.py
|
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
|
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
# Upgrade part
my_name = 'Binh D. Nguyen'
my_age = 22
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'
#print "Let's talk about %s." % my_name
print(f"Let's talk about {my_name:}.")
#print "He's %d inches tall." % my_height
print("He's {:d} inches tall.".format(my_height))
#print "He's %d pounds heavy." % my_weight
#print "Actually that's not too heavy."
#print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print(f"He's got { my_eyes:} eyes and {my_hair:} hair.")
#print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
#print "If I add %d, %d, and %d I get %d." % (
# my_age, my_height, my_weight, my_age + my_height + my_weight)
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {my_age + my_height + my_weight}.")
|
Update exercise of variables and names
|
Update exercise of variables and names
|
Python
|
mit
|
Oreder/PythonSelfStudy
|
python
|
## Code Before:
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
## Instruction:
Update exercise of variables and names
## Code After:
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
# Upgrade part
my_name = 'Binh D. Nguyen'
my_age = 22
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'
#print "Let's talk about %s." % my_name
print(f"Let's talk about {my_name:}.")
#print "He's %d inches tall." % my_height
print("He's {:d} inches tall.".format(my_height))
#print "He's %d pounds heavy." % my_weight
#print "Actually that's not too heavy."
#print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print(f"He's got { my_eyes:} eyes and {my_hair:} hair.")
#print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
#print "If I add %d, %d, and %d I get %d." % (
# my_age, my_height, my_weight, my_age + my_height + my_weight)
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {my_age + my_height + my_weight}.")
|
...
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
# Upgrade part
my_name = 'Binh D. Nguyen'
my_age = 22
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'
#print "Let's talk about %s." % my_name
print(f"Let's talk about {my_name:}.")
#print "He's %d inches tall." % my_height
print("He's {:d} inches tall.".format(my_height))
#print "He's %d pounds heavy." % my_weight
#print "Actually that's not too heavy."
#print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print(f"He's got { my_eyes:} eyes and {my_hair:} hair.")
#print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
#print "If I add %d, %d, and %d I get %d." % (
# my_age, my_height, my_weight, my_age + my_height + my_weight)
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {my_age + my_height + my_weight}.")
...
|
f90467edaf02ae66cdfd01a34f7e03f20073c12d
|
tests/__init__.py
|
tests/__init__.py
|
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
os.mkdir(yvs.ALFRED_DATA_DIR)
def mock_open(path, mode):
if path.endswith('preferences.json'):
path = yvs.PREFS_PATH
return open(path, mode)
patch_open = patch('yvs.shared.open', mock_open, create=True)
def setup():
patch_open.start()
def teardown():
patch_open.stop()
shutil.rmtree(yvs.ALFRED_DATA_DIR)
|
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
def mock_open(path, mode):
if path.endswith('preferences.json'):
path = yvs.PREFS_PATH
return open(path, mode)
patch_open = patch('yvs.shared.open', mock_open, create=True)
def setup():
os.mkdir(yvs.ALFRED_DATA_DIR)
patch_open.start()
def teardown():
patch_open.stop()
shutil.rmtree(yvs.ALFRED_DATA_DIR)
|
Create Alfred data dir on test setup
|
Create Alfred data dir on test setup
|
Python
|
mit
|
caleb531/youversion-suggest,caleb531/youversion-suggest
|
python
|
## Code Before:
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
os.mkdir(yvs.ALFRED_DATA_DIR)
def mock_open(path, mode):
if path.endswith('preferences.json'):
path = yvs.PREFS_PATH
return open(path, mode)
patch_open = patch('yvs.shared.open', mock_open, create=True)
def setup():
patch_open.start()
def teardown():
patch_open.stop()
shutil.rmtree(yvs.ALFRED_DATA_DIR)
## Instruction:
Create Alfred data dir on test setup
## Code After:
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
def mock_open(path, mode):
if path.endswith('preferences.json'):
path = yvs.PREFS_PATH
return open(path, mode)
patch_open = patch('yvs.shared.open', mock_open, create=True)
def setup():
os.mkdir(yvs.ALFRED_DATA_DIR)
patch_open.start()
def teardown():
patch_open.stop()
shutil.rmtree(yvs.ALFRED_DATA_DIR)
|
// ... existing code ...
yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs')
yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json')
def mock_open(path, mode):
// ... modified code ...
def setup():
os.mkdir(yvs.ALFRED_DATA_DIR)
patch_open.start()
// ... rest of the code ...
|
8df7c4b2c008ce6c7735106c28bad1f7326f7012
|
tests/smoketests/test_twisted.py
|
tests/smoketests/test_twisted.py
|
from twisted.internet import reactor, task
def test_deferred():
return task.deferLater(reactor, 0.05, lambda: None)
|
from twisted.internet import reactor, task
from twisted.internet.defer import Deferred, succeed
from twisted.python.failure import Failure
def test_deferred():
return task.deferLater(reactor, 0.05, lambda: None)
def test_failure():
"""
Test that we can check for a failure in an asynchronously-called function.
"""
# Create one Deferred for the result of the test function.
deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails)
# Create another Deferred, which will give the opposite result of
# deferredThatFails (that is, which will succeed if deferredThatFails fails
# and vice versa).
deferredThatSucceeds = Deferred()
# It's tempting to just write something like:
#
# deferredThatFails.addCallback(deferredThatSucceeds.errback)
# deferredThatFails.addErrback (deferredThatSucceeds.callback)
#
# Unfortunately, that doesn't work. The problem is that each callbacks or
# errbacks in a Deferred's callback/errback chain is passed the result of
# the previous callback/errback, and execution switches between those
# chains depending on whether that result is a failure or not. So if a
# callback returns a failure, we switch to the errbacks, and if an errback
# doesn't return a failure, we switch to the callbacks. If we use the
# above, then when deferredThatFails fails, the following will happen:
#
# - deferredThatFails' first (and only) errback is called: the function
# deferredThatSucceeds.callback. It is passed some sort of failure
# object.
# - This causes deferredThatSucceeds to fire. We start its callback
# chain, passing in that same failure object that was passed to
# deferredThatFails' errback chain.
# - Since this is a failure object, we switch to the errback chain of
# deferredThatSucceeds. I believe this happens before the first
# callback is executed, because that callback is probably something
# setup by pytest that would cause the test to pass. So it looks like
# what's happening is we're bypassing that function entirely, and going
# straight to the errback, which causes the test to fail.
#
# The solution is to instead create two functions of our own, which call
# deferredThatSucceeds.callback and .errback but change whether the
# argument is a failure so that it won't cause us to switch between the
# callback and errback chains.
def passTest(arg):
# arg is a failure object of some sort. Don't pass it to callback
# because otherwise it'll trigger the errback, which will cause the
# test to fail.
deferredThatSucceeds.callback(None)
def failTest(arg):
# Manufacture a failure to pass to errback because otherwise twisted
# will switch to the callback chain, causing the test to pass.
theFailure = Failure(AssertionError("functionThatFails didn't fail"))
deferredThatSucceeds.errback(theFailure)
deferredThatFails.addCallbacks(failTest, passTest)
return deferredThatSucceeds
def functionThatFails():
assert False
|
Add an example Twisted test that expects failure.
|
Add an example Twisted test that expects failure.
|
Python
|
mit
|
CheeseLord/warts,CheeseLord/warts
|
python
|
## Code Before:
from twisted.internet import reactor, task
def test_deferred():
return task.deferLater(reactor, 0.05, lambda: None)
## Instruction:
Add an example Twisted test that expects failure.
## Code After:
from twisted.internet import reactor, task
from twisted.internet.defer import Deferred, succeed
from twisted.python.failure import Failure
def test_deferred():
return task.deferLater(reactor, 0.05, lambda: None)
def test_failure():
"""
Test that we can check for a failure in an asynchronously-called function.
"""
# Create one Deferred for the result of the test function.
deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails)
# Create another Deferred, which will give the opposite result of
# deferredThatFails (that is, which will succeed if deferredThatFails fails
# and vice versa).
deferredThatSucceeds = Deferred()
# It's tempting to just write something like:
#
# deferredThatFails.addCallback(deferredThatSucceeds.errback)
# deferredThatFails.addErrback (deferredThatSucceeds.callback)
#
# Unfortunately, that doesn't work. The problem is that each callbacks or
# errbacks in a Deferred's callback/errback chain is passed the result of
# the previous callback/errback, and execution switches between those
# chains depending on whether that result is a failure or not. So if a
# callback returns a failure, we switch to the errbacks, and if an errback
# doesn't return a failure, we switch to the callbacks. If we use the
# above, then when deferredThatFails fails, the following will happen:
#
# - deferredThatFails' first (and only) errback is called: the function
# deferredThatSucceeds.callback. It is passed some sort of failure
# object.
# - This causes deferredThatSucceeds to fire. We start its callback
# chain, passing in that same failure object that was passed to
# deferredThatFails' errback chain.
# - Since this is a failure object, we switch to the errback chain of
# deferredThatSucceeds. I believe this happens before the first
# callback is executed, because that callback is probably something
# setup by pytest that would cause the test to pass. So it looks like
# what's happening is we're bypassing that function entirely, and going
# straight to the errback, which causes the test to fail.
#
# The solution is to instead create two functions of our own, which call
# deferredThatSucceeds.callback and .errback but change whether the
# argument is a failure so that it won't cause us to switch between the
# callback and errback chains.
def passTest(arg):
# arg is a failure object of some sort. Don't pass it to callback
# because otherwise it'll trigger the errback, which will cause the
# test to fail.
deferredThatSucceeds.callback(None)
def failTest(arg):
# Manufacture a failure to pass to errback because otherwise twisted
# will switch to the callback chain, causing the test to pass.
theFailure = Failure(AssertionError("functionThatFails didn't fail"))
deferredThatSucceeds.errback(theFailure)
deferredThatFails.addCallbacks(failTest, passTest)
return deferredThatSucceeds
def functionThatFails():
assert False
|
// ... existing code ...
from twisted.internet import reactor, task
from twisted.internet.defer import Deferred, succeed
from twisted.python.failure import Failure
def test_deferred():
return task.deferLater(reactor, 0.05, lambda: None)
def test_failure():
"""
Test that we can check for a failure in an asynchronously-called function.
"""
# Create one Deferred for the result of the test function.
deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails)
# Create another Deferred, which will give the opposite result of
# deferredThatFails (that is, which will succeed if deferredThatFails fails
# and vice versa).
deferredThatSucceeds = Deferred()
# It's tempting to just write something like:
#
# deferredThatFails.addCallback(deferredThatSucceeds.errback)
# deferredThatFails.addErrback (deferredThatSucceeds.callback)
#
# Unfortunately, that doesn't work. The problem is that each callbacks or
# errbacks in a Deferred's callback/errback chain is passed the result of
# the previous callback/errback, and execution switches between those
# chains depending on whether that result is a failure or not. So if a
# callback returns a failure, we switch to the errbacks, and if an errback
# doesn't return a failure, we switch to the callbacks. If we use the
# above, then when deferredThatFails fails, the following will happen:
#
# - deferredThatFails' first (and only) errback is called: the function
# deferredThatSucceeds.callback. It is passed some sort of failure
# object.
# - This causes deferredThatSucceeds to fire. We start its callback
# chain, passing in that same failure object that was passed to
# deferredThatFails' errback chain.
# - Since this is a failure object, we switch to the errback chain of
# deferredThatSucceeds. I believe this happens before the first
# callback is executed, because that callback is probably something
# setup by pytest that would cause the test to pass. So it looks like
# what's happening is we're bypassing that function entirely, and going
# straight to the errback, which causes the test to fail.
#
# The solution is to instead create two functions of our own, which call
# deferredThatSucceeds.callback and .errback but change whether the
# argument is a failure so that it won't cause us to switch between the
# callback and errback chains.
def passTest(arg):
# arg is a failure object of some sort. Don't pass it to callback
# because otherwise it'll trigger the errback, which will cause the
# test to fail.
deferredThatSucceeds.callback(None)
def failTest(arg):
# Manufacture a failure to pass to errback because otherwise twisted
# will switch to the callback chain, causing the test to pass.
theFailure = Failure(AssertionError("functionThatFails didn't fail"))
deferredThatSucceeds.errback(theFailure)
deferredThatFails.addCallbacks(failTest, passTest)
return deferredThatSucceeds
def functionThatFails():
assert False
// ... rest of the code ...
|
c4f2946f67784c24c2364821a2ba93773ac96e88
|
setup.py
|
setup.py
|
try:
from setuptools import setup
except:
from distutils.core import setup
import forms
setup(
name='forms',
version=forms.version,
description='HTML forms framework for Nevow',
author='Matt Goodall',
author_email='[email protected]',
packages=['forms', 'forms.test'],
)
|
try:
from setuptools import setup
except:
from distutils.core import setup
from distutils.command import install
import forms
for scheme in install.INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
setup(
name='forms',
version=forms.version,
description='HTML forms framework for Nevow',
author='Matt Goodall',
author_email='[email protected]',
packages=['forms', 'forms.test'],
data_files=[
['forms', ['forms/forms.css']],
]
)
|
Include forms.css in the package
|
Include forms.css in the package
|
Python
|
mit
|
emgee/formal,emgee/formal,emgee/formal
|
python
|
## Code Before:
try:
from setuptools import setup
except:
from distutils.core import setup
import forms
setup(
name='forms',
version=forms.version,
description='HTML forms framework for Nevow',
author='Matt Goodall',
author_email='[email protected]',
packages=['forms', 'forms.test'],
)
## Instruction:
Include forms.css in the package
## Code After:
try:
from setuptools import setup
except:
from distutils.core import setup
from distutils.command import install
import forms
for scheme in install.INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
setup(
name='forms',
version=forms.version,
description='HTML forms framework for Nevow',
author='Matt Goodall',
author_email='[email protected]',
packages=['forms', 'forms.test'],
data_files=[
['forms', ['forms/forms.css']],
]
)
|
// ... existing code ...
from setuptools import setup
except:
from distutils.core import setup
from distutils.command import install
import forms
for scheme in install.INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
setup(
name='forms',
// ... modified code ...
author='Matt Goodall',
author_email='[email protected]',
packages=['forms', 'forms.test'],
data_files=[
['forms', ['forms/forms.css']],
]
)
// ... rest of the code ...
|
db1b80e123ba63d1dda257b442c78df2a3d394f1
|
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeType.java
|
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeType.java
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;
/**
* The possible types of nodes in the node repository
*
* @author bjorncs
*/
public enum NodeType {
/** A node to be assigned to a tenant to run application workloads */
tenant,
/** A host of a set of (docker) tenant nodes */
host,
/** Nodes running the shared proxy layer */
proxy,
/** A host of a (docker) proxy node */
proxyhost,
/** A config server */
config,
/** A host of a (docker) config server node */
confighost
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;
/**
* The possible types of nodes in the node repository
*
* @author bjorncs
*/
public enum NodeType {
/** A node to be assigned to a tenant to run application workloads */
tenant,
/** A host of a set of (docker) tenant nodes */
host,
/** Nodes running the shared proxy layer */
proxy,
/** A host of a (docker) proxy node */
proxyhost,
/** A config server */
config,
/** A host of a (docker) config server node */
confighost,
/** A host of a (docker) controller node */
controllerhost
}
|
Add controllerhost node type to controller-api
|
Add controllerhost node type to controller-api
|
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.vespa.hosted.controller.api.integration.noderepository;
/**
* The possible types of nodes in the node repository
*
* @author bjorncs
*/
public enum NodeType {
/** A node to be assigned to a tenant to run application workloads */
tenant,
/** A host of a set of (docker) tenant nodes */
host,
/** Nodes running the shared proxy layer */
proxy,
/** A host of a (docker) proxy node */
proxyhost,
/** A config server */
config,
/** A host of a (docker) config server node */
confighost
}
## Instruction:
Add controllerhost node type to controller-api
## 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.vespa.hosted.controller.api.integration.noderepository;
/**
* The possible types of nodes in the node repository
*
* @author bjorncs
*/
public enum NodeType {
/** A node to be assigned to a tenant to run application workloads */
tenant,
/** A host of a set of (docker) tenant nodes */
host,
/** Nodes running the shared proxy layer */
proxy,
/** A host of a (docker) proxy node */
proxyhost,
/** A config server */
config,
/** A host of a (docker) config server node */
confighost,
/** A host of a (docker) controller node */
controllerhost
}
|
// ... existing code ...
config,
/** A host of a (docker) config server node */
confighost,
/** A host of a (docker) controller node */
controllerhost
}
// ... rest of the code ...
|
74a6a6671adf43987f017e83bf2de55a2c29fc0e
|
src/libclientserver/ThreadPool.h
|
src/libclientserver/ThreadPool.h
|
class ThreadPoolThread;
class ThreadPool {
public:
ThreadPool();
ThreadPool(int nthread);
ThreadPool(int nthread, size_t maxqueue);
~ThreadPool();
void Add(std::function<void()> func);
void Flush();
void Execute();
size_t GetCount();
size_t GetHWCount();
protected:
void Init(int nthread, size_t maxqueue);
private:
std::atomic<uint64_t> m_totalqueued;
std::atomic<uint64_t> m_totalexecuted;
Queue<std::function<void()> > m_queue;
std::list<ThreadPoolThread *> m_threads;
};
|
class ThreadPoolThread;
class ThreadPool {
public:
ThreadPool();
ThreadPool(int nthread);
ThreadPool(int nthread, size_t maxqueue);
~ThreadPool();
void Add(std::function<void()> func);
void Flush();
void Execute();
size_t GetCount();
size_t GetHWCount();
protected:
void Init(int nthread, size_t maxqueue);
private:
std::atomic<uint64_t> m_totalqueued;
std::atomic<uint64_t> m_totalexecuted;
Queue<std::function<void()> > m_queue;
std::list<ThreadPoolThread *> m_threads;
};
|
Convert from tabs -> spaces
|
Convert from tabs -> spaces
|
C
|
mit
|
mistralol/libclientserver,mistralol/libclientserver
|
c
|
## Code Before:
class ThreadPoolThread;
class ThreadPool {
public:
ThreadPool();
ThreadPool(int nthread);
ThreadPool(int nthread, size_t maxqueue);
~ThreadPool();
void Add(std::function<void()> func);
void Flush();
void Execute();
size_t GetCount();
size_t GetHWCount();
protected:
void Init(int nthread, size_t maxqueue);
private:
std::atomic<uint64_t> m_totalqueued;
std::atomic<uint64_t> m_totalexecuted;
Queue<std::function<void()> > m_queue;
std::list<ThreadPoolThread *> m_threads;
};
## Instruction:
Convert from tabs -> spaces
## Code After:
class ThreadPoolThread;
class ThreadPool {
public:
ThreadPool();
ThreadPool(int nthread);
ThreadPool(int nthread, size_t maxqueue);
~ThreadPool();
void Add(std::function<void()> func);
void Flush();
void Execute();
size_t GetCount();
size_t GetHWCount();
protected:
void Init(int nthread, size_t maxqueue);
private:
std::atomic<uint64_t> m_totalqueued;
std::atomic<uint64_t> m_totalexecuted;
Queue<std::function<void()> > m_queue;
std::list<ThreadPoolThread *> m_threads;
};
|
...
class ThreadPoolThread;
class ThreadPool {
public:
ThreadPool();
ThreadPool(int nthread);
ThreadPool(int nthread, size_t maxqueue);
~ThreadPool();
void Add(std::function<void()> func);
void Flush();
void Execute();
size_t GetCount();
size_t GetHWCount();
protected:
void Init(int nthread, size_t maxqueue);
private:
std::atomic<uint64_t> m_totalqueued;
std::atomic<uint64_t> m_totalexecuted;
Queue<std::function<void()> > m_queue;
std::list<ThreadPoolThread *> m_threads;
};
...
|
23e3470cbd7b9d5740c949fe8f5b8f7fe80348d1
|
src/main/java/com/maxmind/geoip2/record/RecordWithNames.java
|
src/main/java/com/maxmind/geoip2/record/RecordWithNames.java
|
package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.getInt("geoname_id");
names = new HashMap<String, String>();
if (json.has("names")) {
JSONObject jnames = json.getJSONObject("names");
for (Iterator<String> i = jnames.keys(); i.hasNext();) {
String key = i.next();
String value = jnames.getString(key);
names.put(key, value);
}
}
if (json.has("confidence")) {
confidence = new Integer(json.getInt("confidence"));
}
}
protected RecordWithNames() {
names = new HashMap<String, String>();
}
public String getName(String l) {
return names.get(l);
}
public int getGeoNameId() {
return geoNameId;
}
public Integer getConfidence() {
return confidence;
}
}
|
package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.getInt("geoname_id");
names = new HashMap<String, String>();
if (json.has("names")) {
JSONObject jnames = json.getJSONObject("names");
Iterator<?> i = jnames.keys();
while (i.hasNext()){
String key = (String) i.next();
String value = jnames.getString(key);
names.put(key, value);
}
}
if (json.has("confidence")) {
confidence = new Integer(json.getInt("confidence"));
}
}
protected RecordWithNames() {
names = new HashMap<String, String>();
}
public String getName(String l) {
return names.get(l);
}
public int getGeoNameId() {
return geoNameId;
}
public Integer getConfidence() {
return confidence;
}
}
|
Use a while loop rather than a c-style for loop
|
Use a while loop rather than a c-style for loop
|
Java
|
apache-2.0
|
maxmind/GeoIP2-java,CASPED/GeoIP2-java,maxmind/GeoIP2-java,CASPED/GeoIP2-java,ecliptical/GeoIP2-java,ecliptical/GeoIP2-java
|
java
|
## Code Before:
package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.getInt("geoname_id");
names = new HashMap<String, String>();
if (json.has("names")) {
JSONObject jnames = json.getJSONObject("names");
for (Iterator<String> i = jnames.keys(); i.hasNext();) {
String key = i.next();
String value = jnames.getString(key);
names.put(key, value);
}
}
if (json.has("confidence")) {
confidence = new Integer(json.getInt("confidence"));
}
}
protected RecordWithNames() {
names = new HashMap<String, String>();
}
public String getName(String l) {
return names.get(l);
}
public int getGeoNameId() {
return geoNameId;
}
public Integer getConfidence() {
return confidence;
}
}
## Instruction:
Use a while loop rather than a c-style for loop
## Code After:
package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.getInt("geoname_id");
names = new HashMap<String, String>();
if (json.has("names")) {
JSONObject jnames = json.getJSONObject("names");
Iterator<?> i = jnames.keys();
while (i.hasNext()){
String key = (String) i.next();
String value = jnames.getString(key);
names.put(key, value);
}
}
if (json.has("confidence")) {
confidence = new Integer(json.getInt("confidence"));
}
}
protected RecordWithNames() {
names = new HashMap<String, String>();
}
public String getName(String l) {
return names.get(l);
}
public int getGeoNameId() {
return geoNameId;
}
public Integer getConfidence() {
return confidence;
}
}
|
// ... existing code ...
names = new HashMap<String, String>();
if (json.has("names")) {
JSONObject jnames = json.getJSONObject("names");
Iterator<?> i = jnames.keys();
while (i.hasNext()){
String key = (String) i.next();
String value = jnames.getString(key);
names.put(key, value);
}
// ... rest of the code ...
|
cf4cd85ba9723854d73a9e88a07043e95bbd5aac
|
src/main/java/org/mydalayer/parsing/builder/BaseBuilder.java
|
src/main/java/org/mydalayer/parsing/builder/BaseBuilder.java
|
package org.mydalayer.parsing.builder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.mydalayer.client.support.Configuration;
/**
*
* @author mydalayer#gmail.com
* @version 1.0.0
*/
public abstract class BaseBuilder {
protected final Configuration configuration;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
}
public Configuration getConfiguration() {
return configuration;
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Boolean <说明>
*/
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Integer <说明>
*/
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Set<String> <说明>
*/
protected Set<String> stringSetValueOf(String value, String defaultValue) {
String value1 = value == null ? defaultValue : value;
return new HashSet<String>(Arrays.asList(value1.split(",")));
}
}
|
package org.mydalayer.parsing.builder;
import org.mydalayer.client.support.Configuration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author mydalayer#gmail.com
* @version 1.0.0
*/
public abstract class BaseBuilder {
protected final Configuration configuration;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
}
public Configuration getConfiguration() {
return configuration;
}
/**
* String "true"/"false" to Boolean Obj.<br>
*
* @return Boolean
*/
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
}
/**
* String number to Integer Obj.<br>
*
* @return Integer
*/
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
}
/**
* String str split by "," to Set Obj.<br>
*
* @return Set type String
*/
protected Set<String> stringSetValueOf(String value, String defaultValue) {
String value1 = value == null ? defaultValue : value;
return new HashSet<String>(Arrays.asList(value1.split(",")));
}
}
|
Modify using Google Java code style and format
|
Modify using Google Java code style and format
|
Java
|
mit
|
mydalayer/code
|
java
|
## Code Before:
package org.mydalayer.parsing.builder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.mydalayer.client.support.Configuration;
/**
*
* @author mydalayer#gmail.com
* @version 1.0.0
*/
public abstract class BaseBuilder {
protected final Configuration configuration;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
}
public Configuration getConfiguration() {
return configuration;
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Boolean <说明>
*/
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Integer <说明>
*/
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
}
/**
* 功能描述:是否为空,为空则赋默认值<br>
* 返回值: Set<String> <说明>
*/
protected Set<String> stringSetValueOf(String value, String defaultValue) {
String value1 = value == null ? defaultValue : value;
return new HashSet<String>(Arrays.asList(value1.split(",")));
}
}
## Instruction:
Modify using Google Java code style and format
## Code After:
package org.mydalayer.parsing.builder;
import org.mydalayer.client.support.Configuration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author mydalayer#gmail.com
* @version 1.0.0
*/
public abstract class BaseBuilder {
protected final Configuration configuration;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
}
public Configuration getConfiguration() {
return configuration;
}
/**
* String "true"/"false" to Boolean Obj.<br>
*
* @return Boolean
*/
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
}
/**
* String number to Integer Obj.<br>
*
* @return Integer
*/
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
}
/**
* String str split by "," to Set Obj.<br>
*
* @return Set type String
*/
protected Set<String> stringSetValueOf(String value, String defaultValue) {
String value1 = value == null ? defaultValue : value;
return new HashSet<String>(Arrays.asList(value1.split(",")));
}
}
|
// ... existing code ...
package org.mydalayer.parsing.builder;
import org.mydalayer.client.support.Configuration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
// ... modified code ...
}
/**
* String "true"/"false" to Boolean Obj.<br>
*
* @return Boolean
*/
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
...
}
/**
* String number to Integer Obj.<br>
*
* @return Integer
*/
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
...
}
/**
* String str split by "," to Set Obj.<br>
*
* @return Set type String
*/
protected Set<String> stringSetValueOf(String value, String defaultValue) {
String value1 = value == null ? defaultValue : value;
// ... rest of the code ...
|
cf12d0560e8eaedae054c3276857be84c425a89c
|
ir/__init__.py
|
ir/__init__.py
|
from aqt import mw
from .main import ReadingManager
__version__ = '4.3.1'
mw.readingManager = ReadingManager()
|
from aqt import mw
from .main import ReadingManager
mw.readingManager = ReadingManager()
|
Remove version number from init
|
Remove version number from init
|
Python
|
isc
|
luoliyan/incremental-reading-for-anki,luoliyan/incremental-reading-for-anki
|
python
|
## Code Before:
from aqt import mw
from .main import ReadingManager
__version__ = '4.3.1'
mw.readingManager = ReadingManager()
## Instruction:
Remove version number from init
## Code After:
from aqt import mw
from .main import ReadingManager
mw.readingManager = ReadingManager()
|
...
from .main import ReadingManager
mw.readingManager = ReadingManager()
...
|
2a1b1a4cc8a1da74d35401adc5713f63ff93f5b6
|
bindings/ios/Private/MEGAHandleList+init.h
|
bindings/ios/Private/MEGAHandleList+init.h
|
/**
* @file MEGAHandleList+init
* @brief Private functions of MEGAHandleList
*
* (c) 2013-2017 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#import "MEGAHandleList.h"
#import "megaapi.h"
@interface MEGAHandleList (init)
- (mega::MegaHandleList *)getCPtr;
@end
|
/**
* @file MEGAHandleList+init
* @brief Private functions of MEGAHandleList
*
* (c) 2013-2017 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#import "MEGAHandleList.h"
#import "megaapi.h"
@interface MEGAHandleList (init)
- (instancetype)initWithMegaHandleList:(mega::MegaHandleList *)megaHandleList cMemoryOwn:(BOOL)cMemoryOwn;
- (mega::MegaHandleList *)getCPtr;
@end
|
Add the ctor for MEGAHandleList (Obj-C)
|
Add the ctor for MEGAHandleList (Obj-C)
|
C
|
bsd-2-clause
|
Acidburn0zzz/sdk,meganz/sdk,Acidburn0zzz/sdk,meganz/sdk,meganz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,meganz/sdk,Acidburn0zzz/sdk,meganz/sdk,meganz/sdk,meganz/sdk,Acidburn0zzz/sdk
|
c
|
## Code Before:
/**
* @file MEGAHandleList+init
* @brief Private functions of MEGAHandleList
*
* (c) 2013-2017 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#import "MEGAHandleList.h"
#import "megaapi.h"
@interface MEGAHandleList (init)
- (mega::MegaHandleList *)getCPtr;
@end
## Instruction:
Add the ctor for MEGAHandleList (Obj-C)
## Code After:
/**
* @file MEGAHandleList+init
* @brief Private functions of MEGAHandleList
*
* (c) 2013-2017 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#import "MEGAHandleList.h"
#import "megaapi.h"
@interface MEGAHandleList (init)
- (instancetype)initWithMegaHandleList:(mega::MegaHandleList *)megaHandleList cMemoryOwn:(BOOL)cMemoryOwn;
- (mega::MegaHandleList *)getCPtr;
@end
|
# ... existing code ...
@interface MEGAHandleList (init)
- (instancetype)initWithMegaHandleList:(mega::MegaHandleList *)megaHandleList cMemoryOwn:(BOOL)cMemoryOwn;
- (mega::MegaHandleList *)getCPtr;
@end
# ... rest of the code ...
|
dc0f76c676ec142fa6381fa4d6ac45e6f6127edf
|
common/util/update_wf_lib.py
|
common/util/update_wf_lib.py
|
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
Choose the pulses to update depending on library
|
Choose the pulses to update depending on library
|
Python
|
apache-2.0
|
BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab
|
python
|
## Code Before:
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
## Instruction:
Choose the pulses to update depending on library
## Code After:
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
...
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
...
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
...
|
abfc91a687b33dda2659025af254bc9f50c077b5
|
publishers/migrations/0008_fix_name_indices.py
|
publishers/migrations/0008_fix_name_indices.py
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
"""
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
"""
),
]
|
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
"""
),
]
|
Mark index migration as non atomic
|
Mark index migration as non atomic
|
Python
|
agpl-3.0
|
dissemin/dissemin,wetneb/dissemin,wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin
|
python
|
## Code Before:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
"""
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
"""
),
]
## Instruction:
Mark index migration as non atomic
## Code After:
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
"""
),
]
|
...
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
...
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
...
|
f495ecb5f9131c2c13c41e78cc3fc2e182bdc8fc
|
hotline/db/db_redis.py
|
hotline/db/db_redis.py
|
import os
import redis
from urllib.parse import urlparse
redis_url = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379')
redis_url_parse = urlparse(redis_url)
redis_client = redis.StrictRedis(host=redis_url_parse.hostname, port=redis_url_parse.port)
|
from db.db_abstract import AbstractClient
from redis import StrictRedis
from urllib.parse import urlparse
class RedisClient(AbstractClient):
def __init__(self, url):
self.url = url
self.client = None
def connect(self):
redis_url = urlparse(self.url)
self.client = StrictRedis(host=url.hostname, port=url.port, password=url.password)
def get(self, **kwargs):
pass
def set(self, **kwargs):
pass
def update(self, **kwargs):
pass
def delete(self, **kwargs):
pass
|
Update to inherit from abstract class
|
Update to inherit from abstract class
|
Python
|
mit
|
wearhacks/hackathon_hotline
|
python
|
## Code Before:
import os
import redis
from urllib.parse import urlparse
redis_url = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379')
redis_url_parse = urlparse(redis_url)
redis_client = redis.StrictRedis(host=redis_url_parse.hostname, port=redis_url_parse.port)
## Instruction:
Update to inherit from abstract class
## Code After:
from db.db_abstract import AbstractClient
from redis import StrictRedis
from urllib.parse import urlparse
class RedisClient(AbstractClient):
def __init__(self, url):
self.url = url
self.client = None
def connect(self):
redis_url = urlparse(self.url)
self.client = StrictRedis(host=url.hostname, port=url.port, password=url.password)
def get(self, **kwargs):
pass
def set(self, **kwargs):
pass
def update(self, **kwargs):
pass
def delete(self, **kwargs):
pass
|
...
from db.db_abstract import AbstractClient
from redis import StrictRedis
from urllib.parse import urlparse
class RedisClient(AbstractClient):
def __init__(self, url):
self.url = url
self.client = None
def connect(self):
redis_url = urlparse(self.url)
self.client = StrictRedis(host=url.hostname, port=url.port, password=url.password)
def get(self, **kwargs):
pass
def set(self, **kwargs):
pass
def update(self, **kwargs):
pass
def delete(self, **kwargs):
pass
...
|
e0ff9ec98c4174b08623c5589cb9e5c407819cfb
|
src/test/java/com/adaptionsoft/games/uglytrivia/GameCorrectAnswerTest.java
|
src/test/java/com/adaptionsoft/games/uglytrivia/GameCorrectAnswerTest.java
|
package com.adaptionsoft.games.uglytrivia;
import org.junit.Test;
import static org.junit.Assert.fail;
public class GameCorrectAnswerTest {
@Test
public void placeMeUnderTest(){
fail("Place Game.correctAnswer under test");
}
}
|
package com.adaptionsoft.games.uglytrivia;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class GameCorrectAnswerTest {
@Test
public void correctAnswerShouldGetACoin() {
Player player = mock(Player.class);
Game game = createGameWithSinglePlayer(player);
game.correctAnswer();
verify(player, times(1)).answeredCorrect();
}
private Game createGameWithSinglePlayer(Player player) {
Players players = new Players();
players.add(player);
return new Game(players, null);
}
}
|
Test that correct answer gets a coin
|
Test that correct answer gets a coin
|
Java
|
bsd-3-clause
|
codecop/ugly-trivia-kata
|
java
|
## Code Before:
package com.adaptionsoft.games.uglytrivia;
import org.junit.Test;
import static org.junit.Assert.fail;
public class GameCorrectAnswerTest {
@Test
public void placeMeUnderTest(){
fail("Place Game.correctAnswer under test");
}
}
## Instruction:
Test that correct answer gets a coin
## Code After:
package com.adaptionsoft.games.uglytrivia;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class GameCorrectAnswerTest {
@Test
public void correctAnswerShouldGetACoin() {
Player player = mock(Player.class);
Game game = createGameWithSinglePlayer(player);
game.correctAnswer();
verify(player, times(1)).answeredCorrect();
}
private Game createGameWithSinglePlayer(Player player) {
Players players = new Players();
players.add(player);
return new Game(players, null);
}
}
|
// ... existing code ...
package com.adaptionsoft.games.uglytrivia;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class GameCorrectAnswerTest {
@Test
public void correctAnswerShouldGetACoin() {
Player player = mock(Player.class);
Game game = createGameWithSinglePlayer(player);
game.correctAnswer();
verify(player, times(1)).answeredCorrect();
}
private Game createGameWithSinglePlayer(Player player) {
Players players = new Players();
players.add(player);
return new Game(players, null);
}
}
// ... rest of the code ...
|
ff1c18b1128f1f8a9d99a4ecb8d7cbb0e2d68edc
|
src/main/java/io/github/jacobmarshall/meloooncensor/lang/Translation.java
|
src/main/java/io/github/jacobmarshall/meloooncensor/lang/Translation.java
|
package io.github.jacobmarshall.meloooncensor.lang;
import io.github.jacobmarshall.meloooncensor.config.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Translation {
public static final Translation DEFAULT_TRANSLATION = new Translation(Configuration.DEFAULT_LANGUAGE, false);
private boolean allowFallback;
protected String language;
protected Properties translations;
public Translation (String language) {
this(language, true);
}
private Translation (String language, boolean allowFallback) {
this.language = language;
this.translations = getTranslations(language);
this.allowFallback = allowFallback;
}
public String getText (String key) {
return this.translations.getProperty(key, this.allowFallback ?
DEFAULT_TRANSLATION.getText(key) : "i18n:" + key);
}
private static Properties getTranslations (String language) {
Properties properties = new Properties();
InputStream inputStream = Translation.class.getResourceAsStream("/lang/" + language + ".properties");
try {
properties.load(inputStream);
} catch (IOException err) {
// Ignore (load the defaults)
}
return properties;
}
}
|
package io.github.jacobmarshall.meloooncensor.lang;
import io.github.jacobmarshall.meloooncensor.config.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Translation {
public static final Translation DEFAULT_TRANSLATION = new Translation(Configuration.DEFAULT_LANGUAGE, false);
private boolean allowFallback;
protected String language;
protected Properties translations;
public Translation (String language) {
this(language, true);
}
private Translation (String language, boolean allowFallback) {
this.language = language;
this.translations = getTranslations(language);
this.allowFallback = allowFallback;
}
public String getText (String key) {
String text = this.translations.getProperty(key, this.allowFallback ?
DEFAULT_TRANSLATION.getText(key) : "i18n:" + key);
try {
text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
} catch(Exception e) {
// Ignore, keep old encoding
}
return text;
}
private static Properties getTranslations (String language) {
Properties properties = new Properties();
InputStream inputStream = Translation.class.getResourceAsStream("/lang/" + language + ".properties");
try {
properties.load(inputStream);
} catch (IOException err) {
// Ignore (load the defaults)
}
return properties;
}
}
|
Fix encoding issue with extended character set
|
Fix encoding issue with extended character set
|
Java
|
mit
|
Behoston/meloooncensor,jacobmarshall/meloooncensor
|
java
|
## Code Before:
package io.github.jacobmarshall.meloooncensor.lang;
import io.github.jacobmarshall.meloooncensor.config.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Translation {
public static final Translation DEFAULT_TRANSLATION = new Translation(Configuration.DEFAULT_LANGUAGE, false);
private boolean allowFallback;
protected String language;
protected Properties translations;
public Translation (String language) {
this(language, true);
}
private Translation (String language, boolean allowFallback) {
this.language = language;
this.translations = getTranslations(language);
this.allowFallback = allowFallback;
}
public String getText (String key) {
return this.translations.getProperty(key, this.allowFallback ?
DEFAULT_TRANSLATION.getText(key) : "i18n:" + key);
}
private static Properties getTranslations (String language) {
Properties properties = new Properties();
InputStream inputStream = Translation.class.getResourceAsStream("/lang/" + language + ".properties");
try {
properties.load(inputStream);
} catch (IOException err) {
// Ignore (load the defaults)
}
return properties;
}
}
## Instruction:
Fix encoding issue with extended character set
## Code After:
package io.github.jacobmarshall.meloooncensor.lang;
import io.github.jacobmarshall.meloooncensor.config.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Translation {
public static final Translation DEFAULT_TRANSLATION = new Translation(Configuration.DEFAULT_LANGUAGE, false);
private boolean allowFallback;
protected String language;
protected Properties translations;
public Translation (String language) {
this(language, true);
}
private Translation (String language, boolean allowFallback) {
this.language = language;
this.translations = getTranslations(language);
this.allowFallback = allowFallback;
}
public String getText (String key) {
String text = this.translations.getProperty(key, this.allowFallback ?
DEFAULT_TRANSLATION.getText(key) : "i18n:" + key);
try {
text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
} catch(Exception e) {
// Ignore, keep old encoding
}
return text;
}
private static Properties getTranslations (String language) {
Properties properties = new Properties();
InputStream inputStream = Translation.class.getResourceAsStream("/lang/" + language + ".properties");
try {
properties.load(inputStream);
} catch (IOException err) {
// Ignore (load the defaults)
}
return properties;
}
}
|
...
}
public String getText (String key) {
String text = this.translations.getProperty(key, this.allowFallback ?
DEFAULT_TRANSLATION.getText(key) : "i18n:" + key);
try {
text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
} catch(Exception e) {
// Ignore, keep old encoding
}
return text;
}
private static Properties getTranslations (String language) {
...
|
7bcc96fc05bc1756288b35e139406c1ef35480d8
|
demo-simple/src/main/java/com/novoda/downloadmanager/demo/simple/Download.java
|
demo-simple/src/main/java/com/novoda/downloadmanager/demo/simple/Download.java
|
package com.novoda.downloadmanager.demo.simple;
import com.novoda.downloadmanager.lib.DownloadManager;
class Download {
private final String title;
private final String fileName;
private final int downloadStatus;
public Download(String title, String fileName, int downloadStatus) {
this.title = title;
this.fileName = fileName;
this.downloadStatus = downloadStatus;
}
public String getTitle() {
return title;
}
public String getFileName() {
return fileName;
}
public String getDownloadStatusText() {
if (downloadStatus == DownloadManager.STATUS_RUNNING) {
return "Downloading";
} else if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
return "Complete";
} else if (downloadStatus == DownloadManager.STATUS_FAILED) {
return "Failed";
} else if (downloadStatus == DownloadManager.STATUS_PENDING) {
return "Queued";
} else if (downloadStatus == DownloadManager.STATUS_PAUSED) {
return "Paused";
} else {
return "WTH";
}
}
}
|
package com.novoda.downloadmanager.demo.simple;
import com.novoda.downloadmanager.lib.DownloadManager;
class Download {
private final String title;
private final String fileName;
private final int downloadStatus;
public Download(String title, String fileName, int downloadStatus) {
this.title = title;
this.fileName = fileName;
this.downloadStatus = downloadStatus;
}
public String getTitle() {
return title;
}
public String getFileName() {
return fileName;
}
public String getDownloadStatusText() {
if (downloadStatus == DownloadManager.STATUS_RUNNING) {
return "Downloading";
} else if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
return "Complete";
} else if (downloadStatus == DownloadManager.STATUS_FAILED) {
return "Failed";
} else if (downloadStatus == DownloadManager.STATUS_PENDING) {
return "Queued";
} else if (downloadStatus == DownloadManager.STATUS_PAUSED) {
return "Paused";
} else if (downloadStatus == DownloadManager.STATUS_DELETING) {
return "Deleting";
} else {
return "WTH";
}
}
}
|
Add deleting status text to the demo adapter
|
Add deleting status text to the demo adapter
|
Java
|
apache-2.0
|
xufeifandj/download-manager,novoda/download-manager
|
java
|
## Code Before:
package com.novoda.downloadmanager.demo.simple;
import com.novoda.downloadmanager.lib.DownloadManager;
class Download {
private final String title;
private final String fileName;
private final int downloadStatus;
public Download(String title, String fileName, int downloadStatus) {
this.title = title;
this.fileName = fileName;
this.downloadStatus = downloadStatus;
}
public String getTitle() {
return title;
}
public String getFileName() {
return fileName;
}
public String getDownloadStatusText() {
if (downloadStatus == DownloadManager.STATUS_RUNNING) {
return "Downloading";
} else if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
return "Complete";
} else if (downloadStatus == DownloadManager.STATUS_FAILED) {
return "Failed";
} else if (downloadStatus == DownloadManager.STATUS_PENDING) {
return "Queued";
} else if (downloadStatus == DownloadManager.STATUS_PAUSED) {
return "Paused";
} else {
return "WTH";
}
}
}
## Instruction:
Add deleting status text to the demo adapter
## Code After:
package com.novoda.downloadmanager.demo.simple;
import com.novoda.downloadmanager.lib.DownloadManager;
class Download {
private final String title;
private final String fileName;
private final int downloadStatus;
public Download(String title, String fileName, int downloadStatus) {
this.title = title;
this.fileName = fileName;
this.downloadStatus = downloadStatus;
}
public String getTitle() {
return title;
}
public String getFileName() {
return fileName;
}
public String getDownloadStatusText() {
if (downloadStatus == DownloadManager.STATUS_RUNNING) {
return "Downloading";
} else if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
return "Complete";
} else if (downloadStatus == DownloadManager.STATUS_FAILED) {
return "Failed";
} else if (downloadStatus == DownloadManager.STATUS_PENDING) {
return "Queued";
} else if (downloadStatus == DownloadManager.STATUS_PAUSED) {
return "Paused";
} else if (downloadStatus == DownloadManager.STATUS_DELETING) {
return "Deleting";
} else {
return "WTH";
}
}
}
|
// ... existing code ...
return "Queued";
} else if (downloadStatus == DownloadManager.STATUS_PAUSED) {
return "Paused";
} else if (downloadStatus == DownloadManager.STATUS_DELETING) {
return "Deleting";
} else {
return "WTH";
}
// ... rest of the code ...
|
32f5090deea042b9ca1acd81570bead7d305e146
|
src/main/java/seedu/geekeep/ui/TaskCard.java
|
src/main/java/seedu/geekeep/ui/TaskCard.java
|
package seedu.geekeep.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.geekeep.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask person, int displayedIndex) {
super(FXML);
name.setText(person.getTitle().fullTitle);
id.setText(displayedIndex + ". ");
phone.setText(person.getEndDateTime().value);
address.setText(person.getLocation().value);
email.setText(person.getStartDateTime().value);
initTags(person);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
|
package seedu.geekeep.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.geekeep.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask person, int displayedIndex) {
super(FXML);
name.setText(person.getTitle().fullTitle);
id.setText("#" + displayedIndex + " ");
if (person.getEndDateTime() != null && person.getStartDateTime() != null) {
phone.setText(person.getStartDateTime() + " until " + person.getEndDateTime());
} else if (person.getEndDateTime() != null && person.getStartDateTime() == null) {
phone.setText(person.getEndDateTime().value);
} else {
phone.setText(null);
}
if (person.getLocation() == null) {
address.setText("");
} else {
address.setText(person.getLocation().value);
}
initTags(person);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
|
Update display of task card
|
Update display of task card
|
Java
|
mit
|
CS2103JAN2017-W15-B4/main,CS2103JAN2017-W15-B4/main
|
java
|
## Code Before:
package seedu.geekeep.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.geekeep.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask person, int displayedIndex) {
super(FXML);
name.setText(person.getTitle().fullTitle);
id.setText(displayedIndex + ". ");
phone.setText(person.getEndDateTime().value);
address.setText(person.getLocation().value);
email.setText(person.getStartDateTime().value);
initTags(person);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
## Instruction:
Update display of task card
## Code After:
package seedu.geekeep.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.geekeep.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "PersonListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label address;
@FXML
private Label email;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask person, int displayedIndex) {
super(FXML);
name.setText(person.getTitle().fullTitle);
id.setText("#" + displayedIndex + " ");
if (person.getEndDateTime() != null && person.getStartDateTime() != null) {
phone.setText(person.getStartDateTime() + " until " + person.getEndDateTime());
} else if (person.getEndDateTime() != null && person.getStartDateTime() == null) {
phone.setText(person.getEndDateTime().value);
} else {
phone.setText(null);
}
if (person.getLocation() == null) {
address.setText("");
} else {
address.setText(person.getLocation().value);
}
initTags(person);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
|
...
public TaskCard(ReadOnlyTask person, int displayedIndex) {
super(FXML);
name.setText(person.getTitle().fullTitle);
id.setText("#" + displayedIndex + " ");
if (person.getEndDateTime() != null && person.getStartDateTime() != null) {
phone.setText(person.getStartDateTime() + " until " + person.getEndDateTime());
} else if (person.getEndDateTime() != null && person.getStartDateTime() == null) {
phone.setText(person.getEndDateTime().value);
} else {
phone.setText(null);
}
if (person.getLocation() == null) {
address.setText("");
} else {
address.setText(person.getLocation().value);
}
initTags(person);
}
...
|
b034eeda25fcf55e7da018f3c91a23a5e252ae2f
|
bm/app/models.py
|
bm/app/models.py
|
from django.db import models
from django.conf import settings
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=21)
row_number = models.IntegerField(default=0)
column_number = models.IntegerField(default=0)
progress_bar_color = models.CharField(max_length=6, default="335544")
# hidden = models.BooleanField(default=False)
# trash = models.BooleanField(default=False)
def __str__(self):
return str(self.user) + ' ' + str(self.name)
class Bookmark(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
row_number = models.IntegerField(default=0)
glyphicon = models.CharField(max_length=30, default="asterisk")
def __str__(self):
return str(self.category) + ' ' + str(self.name)
class Trash(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
glyphicon = models.CharField(max_length=30)
def __str__(self):
return str(self.category) + ' ' + str(self.name)
|
from django.db import models
from django.conf import settings
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=21)
row_number = models.IntegerField(default=0)
column_number = models.IntegerField(default=0)
progress_bar_color = models.CharField(max_length=6, default="335544")
# hidden = models.BooleanField(default=False)
# trash = models.BooleanField(default=False)
def __str__(self):
return str(self.name)
class Bookmark(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
row_number = models.IntegerField(default=0)
glyphicon = models.CharField(max_length=30, default="asterisk")
def __str__(self):
return str(self.category) + ' ' + str(self.name)
class Trash(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
glyphicon = models.CharField(max_length=30)
def __str__(self):
return str(self.category) + ' ' + str(self.name)
|
Change str() of Category for easier form handling
|
Change str() of Category for easier form handling
|
Python
|
mit
|
GSC-RNSIT/bookmark-manager,rohithpr/bookmark-manager,rohithpr/bookmark-manager,GSC-RNSIT/bookmark-manager
|
python
|
## Code Before:
from django.db import models
from django.conf import settings
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=21)
row_number = models.IntegerField(default=0)
column_number = models.IntegerField(default=0)
progress_bar_color = models.CharField(max_length=6, default="335544")
# hidden = models.BooleanField(default=False)
# trash = models.BooleanField(default=False)
def __str__(self):
return str(self.user) + ' ' + str(self.name)
class Bookmark(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
row_number = models.IntegerField(default=0)
glyphicon = models.CharField(max_length=30, default="asterisk")
def __str__(self):
return str(self.category) + ' ' + str(self.name)
class Trash(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
glyphicon = models.CharField(max_length=30)
def __str__(self):
return str(self.category) + ' ' + str(self.name)
## Instruction:
Change str() of Category for easier form handling
## Code After:
from django.db import models
from django.conf import settings
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=21)
row_number = models.IntegerField(default=0)
column_number = models.IntegerField(default=0)
progress_bar_color = models.CharField(max_length=6, default="335544")
# hidden = models.BooleanField(default=False)
# trash = models.BooleanField(default=False)
def __str__(self):
return str(self.name)
class Bookmark(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
row_number = models.IntegerField(default=0)
glyphicon = models.CharField(max_length=30, default="asterisk")
def __str__(self):
return str(self.category) + ' ' + str(self.name)
class Trash(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
link = models.TextField()
glyphicon = models.CharField(max_length=30)
def __str__(self):
return str(self.category) + ' ' + str(self.name)
|
// ... existing code ...
# trash = models.BooleanField(default=False)
def __str__(self):
return str(self.name)
class Bookmark(models.Model):
category = models.ForeignKey(Category)
// ... rest of the code ...
|
e6bba5feec294deb762bba5b53f6b0440ff81cd7
|
strsplit.h
|
strsplit.h
|
int
strsplit (char *str, char *parts[], char *delimiter) {
char *pch;
int i = 0;
pch = strtok(str, delimiter);
parts[i++] = strdup(pch);
while (pch) {
pch = strtok(NULL, delimiter);
if (NULL == pch) break;
parts[i++] = strdup(pch);
}
free(pch);
return i;
}
#endif
|
int
strsplit (char *str, char *parts[], char *delimiter) {
char *pch;
int i = 0;
char *tmp = strdup(str);
pch = strtok(tmp, delimiter);
parts[i++] = strdup(pch);
while (pch) {
pch = strtok(NULL, delimiter);
if (NULL == pch) break;
parts[i++] = strdup(pch);
}
free(tmp);
free(pch);
return i;
}
#endif
|
Fix bad results when compiling with Apple’s LLVM 5
|
Fix bad results when compiling with Apple’s LLVM 5
|
C
|
mit
|
jwerle/strsplit.c
|
c
|
## Code Before:
int
strsplit (char *str, char *parts[], char *delimiter) {
char *pch;
int i = 0;
pch = strtok(str, delimiter);
parts[i++] = strdup(pch);
while (pch) {
pch = strtok(NULL, delimiter);
if (NULL == pch) break;
parts[i++] = strdup(pch);
}
free(pch);
return i;
}
#endif
## Instruction:
Fix bad results when compiling with Apple’s LLVM 5
## Code After:
int
strsplit (char *str, char *parts[], char *delimiter) {
char *pch;
int i = 0;
char *tmp = strdup(str);
pch = strtok(tmp, delimiter);
parts[i++] = strdup(pch);
while (pch) {
pch = strtok(NULL, delimiter);
if (NULL == pch) break;
parts[i++] = strdup(pch);
}
free(tmp);
free(pch);
return i;
}
#endif
|
// ... existing code ...
strsplit (char *str, char *parts[], char *delimiter) {
char *pch;
int i = 0;
char *tmp = strdup(str);
pch = strtok(tmp, delimiter);
parts[i++] = strdup(pch);
// ... modified code ...
parts[i++] = strdup(pch);
}
free(tmp);
free(pch);
return i;
}
// ... rest of the code ...
|
26672e83ab1bd1a932d275dfd244fe20749e3b1e
|
tripleo_common/utils/safe_import.py
|
tripleo_common/utils/safe_import.py
|
import eventlet
from eventlet.green import subprocess
# Due to an eventlet issue subprocess is not being correctly patched
# on git module so it has to be done manually
git = eventlet.import_patched('git', ('subprocess', subprocess))
Repo = git.Repo
# git.refs is lazy loaded when there's a new commit, this needs to be
# patched as well.
eventlet.import_patched('git.refs')
|
from eventlet.green import subprocess
import eventlet.patcher as patcher
# Due to an eventlet issue subprocess is not being correctly patched
# on git.refs
patcher.inject('git.refs', None, ('subprocess', subprocess), )
# this has to be loaded after the inject.
import git # noqa: E402
Repo = git.Repo
|
Make gitpython and eventlet work with eventlet 0.25.1
|
Make gitpython and eventlet work with eventlet 0.25.1
Version 0.25 is having a bad interaction with python git.
that is due to the way that eventlet unloads some modules now.
Changed to use the inject method that supports what we need intead
of the imported_patched that was having the problem
Change-Id: I79894d4f711c64f536593fffcb6959df97c38838
Closes-bug: #1845181
|
Python
|
apache-2.0
|
openstack/tripleo-common,openstack/tripleo-common
|
python
|
## Code Before:
import eventlet
from eventlet.green import subprocess
# Due to an eventlet issue subprocess is not being correctly patched
# on git module so it has to be done manually
git = eventlet.import_patched('git', ('subprocess', subprocess))
Repo = git.Repo
# git.refs is lazy loaded when there's a new commit, this needs to be
# patched as well.
eventlet.import_patched('git.refs')
## Instruction:
Make gitpython and eventlet work with eventlet 0.25.1
Version 0.25 is having a bad interaction with python git.
that is due to the way that eventlet unloads some modules now.
Changed to use the inject method that supports what we need intead
of the imported_patched that was having the problem
Change-Id: I79894d4f711c64f536593fffcb6959df97c38838
Closes-bug: #1845181
## Code After:
from eventlet.green import subprocess
import eventlet.patcher as patcher
# Due to an eventlet issue subprocess is not being correctly patched
# on git.refs
patcher.inject('git.refs', None, ('subprocess', subprocess), )
# this has to be loaded after the inject.
import git # noqa: E402
Repo = git.Repo
|
// ... existing code ...
from eventlet.green import subprocess
import eventlet.patcher as patcher
# Due to an eventlet issue subprocess is not being correctly patched
# on git.refs
patcher.inject('git.refs', None, ('subprocess', subprocess), )
# this has to be loaded after the inject.
import git # noqa: E402
Repo = git.Repo
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.