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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
bbe835c8aa561d8db58e116f0e55a5b19c4f9ca4
|
firecares/sitemaps.py
|
firecares/sitemaps.py
|
from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us',
'firedepartment_list']
def priority(self, item):
return 1
def location(self, item):
return reverse(item)
class DepartmentsSitemap(sitemaps.Sitemap):
protocol = 'https'
max_population = 1
def items(self):
queryset = FireDepartment.objects.filter(archived=False)
self.max_population = queryset.aggregate(Max('population'))['population__max']
return queryset
def location(self, item):
return item.get_absolute_url()
def priority(self, item):
if item.featured is True:
return 1
if item.population is None:
return 0
# adding a bit to the total so featured items are always above others
priority = item.population / float(self.max_population + 0.1)
return priority
def lastmod(self, item):
return item.modified
|
from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us',
'firedepartment_list']
def priority(self, item):
return 1
def location(self, item):
return reverse(item)
class DepartmentsSitemap(sitemaps.Sitemap):
protocol = 'https'
max_population = 1
def items(self):
queryset = FireDepartment.objects.filter(archived=False).only('population', 'featured', 'name')
self.max_population = queryset.aggregate(Max('population'))['population__max']
return queryset
def location(self, item):
return item.get_absolute_url()
def priority(self, item):
if item.featured is True:
return 1
if item.population is None:
return 0
# adding a bit to the total so featured items are always above others
priority = item.population / float(self.max_population + 0.1)
return priority
def lastmod(self, item):
return item.modified
|
Fix sitemap memory consumption during generation
|
Fix sitemap memory consumption during generation
- Defer ALL FireDepartment fields except for those required to create a sitemap
- Was causing node startup to hang
see #321
|
Python
|
mit
|
FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares
|
python
|
## Code Before:
from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us',
'firedepartment_list']
def priority(self, item):
return 1
def location(self, item):
return reverse(item)
class DepartmentsSitemap(sitemaps.Sitemap):
protocol = 'https'
max_population = 1
def items(self):
queryset = FireDepartment.objects.filter(archived=False)
self.max_population = queryset.aggregate(Max('population'))['population__max']
return queryset
def location(self, item):
return item.get_absolute_url()
def priority(self, item):
if item.featured is True:
return 1
if item.population is None:
return 0
# adding a bit to the total so featured items are always above others
priority = item.population / float(self.max_population + 0.1)
return priority
def lastmod(self, item):
return item.modified
## Instruction:
Fix sitemap memory consumption during generation
- Defer ALL FireDepartment fields except for those required to create a sitemap
- Was causing node startup to hang
see #321
## Code After:
from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us',
'firedepartment_list']
def priority(self, item):
return 1
def location(self, item):
return reverse(item)
class DepartmentsSitemap(sitemaps.Sitemap):
protocol = 'https'
max_population = 1
def items(self):
queryset = FireDepartment.objects.filter(archived=False).only('population', 'featured', 'name')
self.max_population = queryset.aggregate(Max('population'))['population__max']
return queryset
def location(self, item):
return item.get_absolute_url()
def priority(self, item):
if item.featured is True:
return 1
if item.population is None:
return 0
# adding a bit to the total so featured items are always above others
priority = item.population / float(self.max_population + 0.1)
return priority
def lastmod(self, item):
return item.modified
|
# ... existing code ...
max_population = 1
def items(self):
queryset = FireDepartment.objects.filter(archived=False).only('population', 'featured', 'name')
self.max_population = queryset.aggregate(Max('population'))['population__max']
return queryset
# ... rest of the code ...
|
fffe7392cb486f7218fc8afd2d42769660a1f558
|
tests/test_main.py
|
tests/test_main.py
|
from subprocess import check_call
from pytest import raises
from csft import __main__ as main
def test_call():
check_call(['python', '-m', 'csft', '.'])
def test_main():
main.main(argv=['.'])
with raises(SystemExit):
main.main(argv=[])
|
from subprocess import check_call
from pytest import raises
from csft import __main__ as main
def test_call():
check_call(['python', '-m', 'csft', '.'])
def test_main():
main.main(argv=['.'])
with raises(SystemExit):
main.main(argv=[])
with raises(TypeError):
main.main(argv=['path/is/not/a/directory'])
|
Test when path not is a directory.
|
Test when path not is a directory.
|
Python
|
mit
|
yanqd0/csft
|
python
|
## Code Before:
from subprocess import check_call
from pytest import raises
from csft import __main__ as main
def test_call():
check_call(['python', '-m', 'csft', '.'])
def test_main():
main.main(argv=['.'])
with raises(SystemExit):
main.main(argv=[])
## Instruction:
Test when path not is a directory.
## Code After:
from subprocess import check_call
from pytest import raises
from csft import __main__ as main
def test_call():
check_call(['python', '-m', 'csft', '.'])
def test_main():
main.main(argv=['.'])
with raises(SystemExit):
main.main(argv=[])
with raises(TypeError):
main.main(argv=['path/is/not/a/directory'])
|
...
with raises(SystemExit):
main.main(argv=[])
with raises(TypeError):
main.main(argv=['path/is/not/a/directory'])
...
|
8402d0d7aedac9147e3c9cfb24385ab0ebd84403
|
dbpool/src/main/java/com/proofpoint/dbpool/MySqlDataSource.java
|
dbpool/src/main/java/com/proofpoint/dbpool/MySqlDataSource.java
|
package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setSocketTimeout((int) ceil(config.getMaxConnectionWait().toMillis()));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
|
package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setUser(config.getUsername());
dataSource.setPassword(config.getPassword());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
|
Set username, password and don't set socket timeout
|
Set username, password and don't set socket timeout
|
Java
|
apache-2.0
|
electrum/airlift,martint/airlift,electrum/airlift,airlift/airlift-rack,johngmyers/platform-rack,johngmyers/airlift,mono-plane/airlift,johngmyers/platform,gwittel/platform,dain/airlift,johngmyers/platform,haozhun/airlift,electrum/airlift,dain/airlift,cberner/airlift,airlift/airlift,haozhun/airlift,airlift/airlift-rack,daququ/airlift,johngmyers/platform-rack,daququ/airlift,johngmyers/airlift,airlift/airlift,johngmyers/platform-rack,cberner/airlift,zhenyuy-fb/airlift,electrum/airlift,johngmyers/platform-rack,gwittel/platform,zhenyuy-fb/airlift,airlift/airlift,dain/airlift,zhenyuy-fb/airlift,mono-plane/airlift,daququ/airlift,proofpoint/platform,haozhun/airlift,erichwang/airlift,johngmyers/airlift,johngmyers/platform-rack,erichwang/airlift,martint/airlift,dain/airlift,haozhun/airlift,mono-plane/airlift,airlift/airlift,cberner/airlift,cberner/airlift,gwittel/platform,johngmyers/platform,martint/airlift,daququ/airlift,johngmyers/airlift,proofpoint/platform,proofpoint/platform,mono-plane/airlift,erichwang/airlift,zhenyuy-fb/airlift,johngmyers/platform-rack
|
java
|
## Code Before:
package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setSocketTimeout((int) ceil(config.getMaxConnectionWait().toMillis()));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
## Instruction:
Set username, password and don't set socket timeout
## Code After:
package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setUser(config.getUsername());
dataSource.setPassword(config.getPassword());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
|
# ... existing code ...
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setUser(config.getUsername());
dataSource.setPassword(config.getPassword());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
# ... rest of the code ...
|
0377980a382256bbdb7f148badac0d96c150644a
|
src/main/java/bj/pranie/controller/IndexController.java
|
src/main/java/bj/pranie/controller/IndexController.java
|
package bj.pranie.controller;
import bj.pranie.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Calendar;
/**
* Created by Sebastian Sokolowski on 12.10.16.
*/
@Controller
public class IndexController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(Model model) {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("time", TimeUtil.getTime());
log.debug("time" + Calendar.getInstance().getTime().toString());
return modelAndView;
}
}
|
package bj.pranie.controller;
import bj.pranie.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Sebastian Sokolowski on 12.10.16.
*/
@Controller
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
if (isAuthenticatedUser()) {
return "redirect:/week";
}
return "index";
}
private boolean isAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof User) {
return true;
}
return false;
}
}
|
Implement auto redirect authenticated user to week page.
|
Implement auto redirect authenticated user to week page.
|
Java
|
apache-2.0
|
sebastiansokolowski/ReservationSystem-BJ,sebastiansokolowski/ReservationSystem-BJ
|
java
|
## Code Before:
package bj.pranie.controller;
import bj.pranie.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Calendar;
/**
* Created by Sebastian Sokolowski on 12.10.16.
*/
@Controller
public class IndexController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(Model model) {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("time", TimeUtil.getTime());
log.debug("time" + Calendar.getInstance().getTime().toString());
return modelAndView;
}
}
## Instruction:
Implement auto redirect authenticated user to week page.
## Code After:
package bj.pranie.controller;
import bj.pranie.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Sebastian Sokolowski on 12.10.16.
*/
@Controller
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
if (isAuthenticatedUser()) {
return "redirect:/week";
}
return "index";
}
private boolean isAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof User) {
return true;
}
return false;
}
}
|
...
package bj.pranie.controller;
import bj.pranie.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Sebastian Sokolowski on 12.10.16.
...
@Controller
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
if (isAuthenticatedUser()) {
return "redirect:/week";
}
return "index";
}
private boolean isAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof User) {
return true;
}
return false;
}
}
...
|
f7faebbd91b4dc0fcd11e10d215d752badc899d6
|
aspc/senate/views.py
|
aspc/senate/views.py
|
from django.views.generic import ListView
from aspc.senate.models import Document, Appointment
import datetime
class DocumentList(ListView):
model = Document
context_object_name = 'documents'
paginate_by = 20
class AppointmentList(ListView):
model = Appointment
context_object_name = 'appointments'
def get_queryset(self, *args, **kwargs):
qs = super(AppointmentList, self).get_queryset(*args, **kwargs)
qs = qs.filter(end__isnull=True)
qs |= qs.filter(end__gte=datetime.datetime.now())
qs = qs.order_by('position__sort_order')
return qs
|
from django.views.generic import ListView
from aspc.senate.models import Document, Appointment
import datetime
class DocumentList(ListView):
model = Document
context_object_name = 'documents'
paginate_by = 20
class AppointmentList(ListView):
model = Appointment
context_object_name = 'appointments'
def get_queryset(self, *args, **kwargs):
all_qs = super(AppointmentList, self).get_queryset(*args, **kwargs)
qs = all_qs.filter(end__isnull=True)
qs |= all_qs.filter(end__gte=datetime.datetime.now())
qs = qs.order_by('position__sort_order')
return qs
|
Change queryset filtering for positions view
|
Change queryset filtering for positions view
|
Python
|
mit
|
theworldbright/mainsite,theworldbright/mainsite,theworldbright/mainsite,aspc/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,aspc/mainsite
|
python
|
## Code Before:
from django.views.generic import ListView
from aspc.senate.models import Document, Appointment
import datetime
class DocumentList(ListView):
model = Document
context_object_name = 'documents'
paginate_by = 20
class AppointmentList(ListView):
model = Appointment
context_object_name = 'appointments'
def get_queryset(self, *args, **kwargs):
qs = super(AppointmentList, self).get_queryset(*args, **kwargs)
qs = qs.filter(end__isnull=True)
qs |= qs.filter(end__gte=datetime.datetime.now())
qs = qs.order_by('position__sort_order')
return qs
## Instruction:
Change queryset filtering for positions view
## Code After:
from django.views.generic import ListView
from aspc.senate.models import Document, Appointment
import datetime
class DocumentList(ListView):
model = Document
context_object_name = 'documents'
paginate_by = 20
class AppointmentList(ListView):
model = Appointment
context_object_name = 'appointments'
def get_queryset(self, *args, **kwargs):
all_qs = super(AppointmentList, self).get_queryset(*args, **kwargs)
qs = all_qs.filter(end__isnull=True)
qs |= all_qs.filter(end__gte=datetime.datetime.now())
qs = qs.order_by('position__sort_order')
return qs
|
// ... existing code ...
context_object_name = 'appointments'
def get_queryset(self, *args, **kwargs):
all_qs = super(AppointmentList, self).get_queryset(*args, **kwargs)
qs = all_qs.filter(end__isnull=True)
qs |= all_qs.filter(end__gte=datetime.datetime.now())
qs = qs.order_by('position__sort_order')
return qs
// ... rest of the code ...
|
f8cbdcc43038a1acb26f6643aa06c082b14c15ef
|
src/Game/Player.h
|
src/Game/Player.h
|
//
// WulfGame/Game/Player.h
// Copyright (C) 2012 Lexi Robinson
// This code is freely available under the MIT licence.
//
#pragma once
#include <glm/glm.hpp>
#include "WulfConstants.h"
#include "Game/InputManager.h"
#include "Game/Constants.h"
#include "Game/Entity.h"
#include "Map/Map.h"
namespace Wulf {
class Player : public Entity {
public:
Player();
~Player() {};
void ProcessUserInput(const Input::Data& input, const double dtime);
void ProcessMapInput(const Map::Map& map);
#ifdef FREE_VIEW
glm::vec3 GetUp() const { return mUp; }
#endif
Difficulty GetDifficulty() const { return mDifficulty; }
void SetDifficulty(Difficulty nDiff) { mDifficulty = nDiff; }
private:
Difficulty mDifficulty;
#ifdef FREE_VIEW
float fhViewAngle;
float fvViewAngle;
glm::vec3 mUp;
#else
float fViewAngle;
#endif
Player(Player& other);
Player& operator=(Player& other);
};
}
|
//
// WulfGame/Game/Player.h
// Copyright (C) 2012 Lexi Robinson
// This code is freely available under the MIT licence.
//
#pragma once
#include <glm/glm.hpp>
#include "WulfConstants.h"
#include "Game/InputManager.h"
#include "Game/Constants.h"
#include "Game/Entity.h"
#include "Map/Map.h"
namespace Wulf {
class Player : public Entity {
public:
Player();
~Player() {};
void ProcessUserInput(const Input::Data& input, const double dtime);
void ProcessMapInput(const Map::Map& map);
#ifdef FREE_VIEW
glm::vec3 GetUp() const { return mUp; }
#endif
byte Ammo;
word Score;
Difficulty GetDifficulty() const { return mDifficulty; }
void SetDifficulty(Difficulty nDiff) { mDifficulty = nDiff; }
private:
Difficulty mDifficulty;
#ifdef FREE_VIEW
float fhViewAngle;
float fvViewAngle;
glm::vec3 mUp;
#else
float fViewAngle;
#endif
Player(Player& other);
Player& operator=(Player& other);
};
}
|
Add ammo and score fields to the player object
|
Add ammo and score fields to the player object
|
C
|
mit
|
Lexicality/Wulf2012,Lexicality/Wulf2012
|
c
|
## Code Before:
//
// WulfGame/Game/Player.h
// Copyright (C) 2012 Lexi Robinson
// This code is freely available under the MIT licence.
//
#pragma once
#include <glm/glm.hpp>
#include "WulfConstants.h"
#include "Game/InputManager.h"
#include "Game/Constants.h"
#include "Game/Entity.h"
#include "Map/Map.h"
namespace Wulf {
class Player : public Entity {
public:
Player();
~Player() {};
void ProcessUserInput(const Input::Data& input, const double dtime);
void ProcessMapInput(const Map::Map& map);
#ifdef FREE_VIEW
glm::vec3 GetUp() const { return mUp; }
#endif
Difficulty GetDifficulty() const { return mDifficulty; }
void SetDifficulty(Difficulty nDiff) { mDifficulty = nDiff; }
private:
Difficulty mDifficulty;
#ifdef FREE_VIEW
float fhViewAngle;
float fvViewAngle;
glm::vec3 mUp;
#else
float fViewAngle;
#endif
Player(Player& other);
Player& operator=(Player& other);
};
}
## Instruction:
Add ammo and score fields to the player object
## Code After:
//
// WulfGame/Game/Player.h
// Copyright (C) 2012 Lexi Robinson
// This code is freely available under the MIT licence.
//
#pragma once
#include <glm/glm.hpp>
#include "WulfConstants.h"
#include "Game/InputManager.h"
#include "Game/Constants.h"
#include "Game/Entity.h"
#include "Map/Map.h"
namespace Wulf {
class Player : public Entity {
public:
Player();
~Player() {};
void ProcessUserInput(const Input::Data& input, const double dtime);
void ProcessMapInput(const Map::Map& map);
#ifdef FREE_VIEW
glm::vec3 GetUp() const { return mUp; }
#endif
byte Ammo;
word Score;
Difficulty GetDifficulty() const { return mDifficulty; }
void SetDifficulty(Difficulty nDiff) { mDifficulty = nDiff; }
private:
Difficulty mDifficulty;
#ifdef FREE_VIEW
float fhViewAngle;
float fvViewAngle;
glm::vec3 mUp;
#else
float fViewAngle;
#endif
Player(Player& other);
Player& operator=(Player& other);
};
}
|
// ... existing code ...
glm::vec3 GetUp() const { return mUp; }
#endif
byte Ammo;
word Score;
Difficulty GetDifficulty() const { return mDifficulty; }
void SetDifficulty(Difficulty nDiff) { mDifficulty = nDiff; }
// ... rest of the code ...
|
ae22bbc03160032cdd77f6c6f12a9458ce1cc0a6
|
demo/src/main/java/me/yokeyword/sample/demo_wechat/base/BaseBackFragment.java
|
demo/src/main/java/me/yokeyword/sample/demo_wechat/base/BaseBackFragment.java
|
package me.yokeyword.sample.demo_wechat.base;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import me.yokeyword.sample.R;
/**
* Created by YoKeyword on 16/2/7.
*/
public class BaseBackFragment extends SwipeBackFragment {
private static final String TAG = "Fragmentation";
protected void initToolbarNav(Toolbar toolbar) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_mActivity.onBackPressed();
}
});
}
}
|
package me.yokeyword.sample.demo_wechat.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import me.yokeyword.sample.R;
/**
* Created by YoKeyword on 16/2/7.
*/
public class BaseBackFragment extends SwipeBackFragment {
private static final String TAG = "Fragmentation";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setParallaxOffset(0.5f);
}
protected void initToolbarNav(Toolbar toolbar) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_mActivity.onBackPressed();
}
});
}
}
|
Add a sample of setParallaxOffset().
|
Add a sample of setParallaxOffset().
|
Java
|
apache-2.0
|
YoKeyword/Fragmentation
|
java
|
## Code Before:
package me.yokeyword.sample.demo_wechat.base;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import me.yokeyword.sample.R;
/**
* Created by YoKeyword on 16/2/7.
*/
public class BaseBackFragment extends SwipeBackFragment {
private static final String TAG = "Fragmentation";
protected void initToolbarNav(Toolbar toolbar) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_mActivity.onBackPressed();
}
});
}
}
## Instruction:
Add a sample of setParallaxOffset().
## Code After:
package me.yokeyword.sample.demo_wechat.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import me.yokeyword.sample.R;
/**
* Created by YoKeyword on 16/2/7.
*/
public class BaseBackFragment extends SwipeBackFragment {
private static final String TAG = "Fragmentation";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setParallaxOffset(0.5f);
}
protected void initToolbarNav(Toolbar toolbar) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_mActivity.onBackPressed();
}
});
}
}
|
// ... existing code ...
package me.yokeyword.sample.demo_wechat.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
// ... modified code ...
public class BaseBackFragment extends SwipeBackFragment {
private static final String TAG = "Fragmentation";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setParallaxOffset(0.5f);
}
protected void initToolbarNav(Toolbar toolbar) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
// ... rest of the code ...
|
c1d8eedac71576ddb5a5ec57af8b314ab1427972
|
src/main/java/com/playlist/SlackClient.java
|
src/main/java/com/playlist/SlackClient.java
|
package com.playlist;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL.
*/
public class SlackClient {
private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");
public void postMessageToSlack(String message) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(slackWebHookUrl);
JSONObject json = new JSONObject();
json.put("text", message);
json.put("channel", "#test-integrations");//TODO: remove channel override
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if(response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity()));
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
|
package com.playlist;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL.
*/
public class SlackClient {
private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");
private String slackChannelOverride = System.getenv("SLACK_CHANNEL_OVERRIDE");
public void postMessageToSlack(String message) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(slackWebHookUrl);
JSONObject json = new JSONObject();
json.put("text", message);
//Include a channel override if one has been provided
if(!StringUtils.isEmpty(slackChannelOverride)) {
json.put("channel", slackChannelOverride);
}
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if(response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity()));
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
|
Refactor channel override to environment variable.
|
Refactor channel override to environment variable.
|
Java
|
mit
|
RaymondKroon/slack-spotify-playlist,bradfogle/slack-spotify-playlist
|
java
|
## Code Before:
package com.playlist;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL.
*/
public class SlackClient {
private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");
public void postMessageToSlack(String message) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(slackWebHookUrl);
JSONObject json = new JSONObject();
json.put("text", message);
json.put("channel", "#test-integrations");//TODO: remove channel override
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if(response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity()));
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
## Instruction:
Refactor channel override to environment variable.
## Code After:
package com.playlist;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL.
*/
public class SlackClient {
private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");
private String slackChannelOverride = System.getenv("SLACK_CHANNEL_OVERRIDE");
public void postMessageToSlack(String message) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(slackWebHookUrl);
JSONObject json = new JSONObject();
json.put("text", message);
//Include a channel override if one has been provided
if(!StringUtils.isEmpty(slackChannelOverride)) {
json.put("channel", slackChannelOverride);
}
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if(response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity()));
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
|
...
package com.playlist;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
...
public class SlackClient {
private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");
private String slackChannelOverride = System.getenv("SLACK_CHANNEL_OVERRIDE");
public void postMessageToSlack(String message) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
...
JSONObject json = new JSONObject();
json.put("text", message);
//Include a channel override if one has been provided
if(!StringUtils.isEmpty(slackChannelOverride)) {
json.put("channel", slackChannelOverride);
}
StringEntity entity = new StringEntity(json.toString());
...
|
c0c73dd73f13e8d1d677cc2d7cad5c2f63217751
|
python/tests/test_rmm.py
|
python/tests/test_rmm.py
|
import pytest
import functools
from itertools import product
import numpy as np
from numba import cuda
from libgdf_cffi import libgdf
from librmm_cffi import ffi, librmm
from .utils import new_column, unwrap_devary, get_dtype, gen_rand, fix_zeros
from .utils import buffer_as_bits
_dtypes = [np.int32]
_nelems = [128]
@pytest.fixture(scope="module")
def rmm():
print("initialize librmm")
assert librmm.initialize() == librmm.RMM_SUCCESS
yield librmm
print("finalize librmm")
assert librmm.finalize() == librmm.RMM_SUCCESS
@pytest.mark.parametrize('dtype,nelem', list(product(_dtypes, _nelems)))
def test_rmm_alloc(dtype, nelem, rmm):
expect_fn = np.add
test_fn = libgdf.gdf_add_generic
#import cffi
#ffi = cffi.FFI()
# data
h_in = gen_rand(dtype, nelem)
h_result = gen_rand(dtype, nelem)
d_in = rmm.to_device(h_in)
d_result = rmm.device_array_like(d_in)
d_result.copy_to_device(d_in)
h_result = d_result.copy_to_host()
print('expect')
print(h_in)
print('got')
print(h_result)
np.testing.assert_array_equal(h_result, h_in)
assert rmm.free_device_array_memory(d_in) == rmm.RMM_SUCCESS
assert rmm.free_device_array_memory(d_result) == rmm.RMM_SUCCESS
|
import pytest
import functools
from itertools import product
import numpy as np
from numba import cuda
from librmm_cffi import librmm as rmm
from .utils import gen_rand
_dtypes = [np.int32]
_nelems = [1, 2, 7, 8, 9, 32, 128]
@pytest.mark.parametrize('dtype,nelem', list(product(_dtypes, _nelems)))
def test_rmm_alloc(dtype, nelem):
# data
h_in = gen_rand(dtype, nelem)
h_result = gen_rand(dtype, nelem)
d_in = rmm.to_device(h_in)
d_result = rmm.device_array_like(d_in)
d_result.copy_to_device(d_in)
h_result = d_result.copy_to_host()
print('expect')
print(h_in)
print('got')
print(h_result)
np.testing.assert_array_equal(h_result, h_in)
|
Improve librmm python API and convert all pytests to use RMM to create device_arrays.
|
Improve librmm python API and convert all pytests to use RMM to create device_arrays.
|
Python
|
apache-2.0
|
gpuopenanalytics/libgdf,gpuopenanalytics/libgdf,gpuopenanalytics/libgdf,gpuopenanalytics/libgdf
|
python
|
## Code Before:
import pytest
import functools
from itertools import product
import numpy as np
from numba import cuda
from libgdf_cffi import libgdf
from librmm_cffi import ffi, librmm
from .utils import new_column, unwrap_devary, get_dtype, gen_rand, fix_zeros
from .utils import buffer_as_bits
_dtypes = [np.int32]
_nelems = [128]
@pytest.fixture(scope="module")
def rmm():
print("initialize librmm")
assert librmm.initialize() == librmm.RMM_SUCCESS
yield librmm
print("finalize librmm")
assert librmm.finalize() == librmm.RMM_SUCCESS
@pytest.mark.parametrize('dtype,nelem', list(product(_dtypes, _nelems)))
def test_rmm_alloc(dtype, nelem, rmm):
expect_fn = np.add
test_fn = libgdf.gdf_add_generic
#import cffi
#ffi = cffi.FFI()
# data
h_in = gen_rand(dtype, nelem)
h_result = gen_rand(dtype, nelem)
d_in = rmm.to_device(h_in)
d_result = rmm.device_array_like(d_in)
d_result.copy_to_device(d_in)
h_result = d_result.copy_to_host()
print('expect')
print(h_in)
print('got')
print(h_result)
np.testing.assert_array_equal(h_result, h_in)
assert rmm.free_device_array_memory(d_in) == rmm.RMM_SUCCESS
assert rmm.free_device_array_memory(d_result) == rmm.RMM_SUCCESS
## Instruction:
Improve librmm python API and convert all pytests to use RMM to create device_arrays.
## Code After:
import pytest
import functools
from itertools import product
import numpy as np
from numba import cuda
from librmm_cffi import librmm as rmm
from .utils import gen_rand
_dtypes = [np.int32]
_nelems = [1, 2, 7, 8, 9, 32, 128]
@pytest.mark.parametrize('dtype,nelem', list(product(_dtypes, _nelems)))
def test_rmm_alloc(dtype, nelem):
# data
h_in = gen_rand(dtype, nelem)
h_result = gen_rand(dtype, nelem)
d_in = rmm.to_device(h_in)
d_result = rmm.device_array_like(d_in)
d_result.copy_to_device(d_in)
h_result = d_result.copy_to_host()
print('expect')
print(h_in)
print('got')
print(h_result)
np.testing.assert_array_equal(h_result, h_in)
|
# ... existing code ...
import numpy as np
from numba import cuda
from librmm_cffi import librmm as rmm
from .utils import gen_rand
_dtypes = [np.int32]
_nelems = [1, 2, 7, 8, 9, 32, 128]
@pytest.mark.parametrize('dtype,nelem', list(product(_dtypes, _nelems)))
def test_rmm_alloc(dtype, nelem):
# data
h_in = gen_rand(dtype, nelem)
h_result = gen_rand(dtype, nelem)
# ... modified code ...
print(h_result)
np.testing.assert_array_equal(h_result, h_in)
# ... rest of the code ...
|
bfc7a13439114313897526ea461f404539cc3fe5
|
tests/test_publisher.py
|
tests/test_publisher.py
|
import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
|
import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
|
Test that local rsync publishing works (with and w/o delete option)
|
Test that local rsync publishing works (with and w/o delete option)
This excercises #946
|
Python
|
bsd-3-clause
|
lektor/lektor,lektor/lektor,lektor/lektor,lektor/lektor
|
python
|
## Code Before:
import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
## Instruction:
Test that local rsync publishing works (with and w/o delete option)
This excercises #946
## Code After:
import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
|
# ... existing code ...
import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# ... modified code ...
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
# ... rest of the code ...
|
49a50ddc3ce5cde43488296e30c2518b085b3e12
|
cineio-broadcast-android-sdk/src/main/java/io/cine/android/BroadcastConfig.java
|
cineio-broadcast-android-sdk/src/main/java/io/cine/android/BroadcastConfig.java
|
package io.cine.android;
import android.util.Log;
/**
* Created by thomas on 1/16/15.
*/
public class BroadcastConfig {
private int width;
private int height;
private String requestedCamera;
private String lockedOrientation;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getLockedOrientation() {
return lockedOrientation;
}
public void lockOrientation(String lockedOrientation) {
if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){
this.lockedOrientation = lockedOrientation;
} else {
throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\"");
}
}
public String getRequestedCamera() {
return requestedCamera;
}
public void selectCamera(String camera) {
if(camera.equals("back") || camera.equals("front") || camera == null){
this.requestedCamera = camera;
} else {
throw new RuntimeException("Camera must be \"front\" or \"back\"");
}
}
}
|
package io.cine.android;
import android.util.Log;
/**
* Created by thomas on 1/16/15.
*/
public class BroadcastConfig {
private Integer width;
private Integer height;
private String requestedCamera;
private String lockedOrientation;
public int getWidth() {
if (width == null){
return -1;
}else{
return width;
}
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
if (height == null){
return -1;
}else{
return height;
}
}
public void setHeight(int height) {
this.height = height;
}
public String getLockedOrientation() {
return lockedOrientation;
}
public void lockOrientation(String lockedOrientation) {
if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){
this.lockedOrientation = lockedOrientation;
} else {
throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\"");
}
}
public String getRequestedCamera() {
return requestedCamera;
}
public void selectCamera(String camera) {
if(camera.equals("back") || camera.equals("front") || camera == null){
this.requestedCamera = camera;
} else {
throw new RuntimeException("Camera must be \"front\" or \"back\"");
}
}
}
|
Set BroadCastConfig width and height to Integers, and check for null values; return -1 if null. This allows us to avoid the problem of ints defaulting to 0 which messes up the default settings for screen width/height
|
Set BroadCastConfig width and height to Integers, and check for null values; return -1 if null.
This allows us to avoid the problem of ints defaulting to 0 which messes up the default settings for screen width/height
|
Java
|
mit
|
cine-io/cineio-broadcast-android,DisruptiveMind/cineio-broadcast-android
|
java
|
## Code Before:
package io.cine.android;
import android.util.Log;
/**
* Created by thomas on 1/16/15.
*/
public class BroadcastConfig {
private int width;
private int height;
private String requestedCamera;
private String lockedOrientation;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getLockedOrientation() {
return lockedOrientation;
}
public void lockOrientation(String lockedOrientation) {
if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){
this.lockedOrientation = lockedOrientation;
} else {
throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\"");
}
}
public String getRequestedCamera() {
return requestedCamera;
}
public void selectCamera(String camera) {
if(camera.equals("back") || camera.equals("front") || camera == null){
this.requestedCamera = camera;
} else {
throw new RuntimeException("Camera must be \"front\" or \"back\"");
}
}
}
## Instruction:
Set BroadCastConfig width and height to Integers, and check for null values; return -1 if null.
This allows us to avoid the problem of ints defaulting to 0 which messes up the default settings for screen width/height
## Code After:
package io.cine.android;
import android.util.Log;
/**
* Created by thomas on 1/16/15.
*/
public class BroadcastConfig {
private Integer width;
private Integer height;
private String requestedCamera;
private String lockedOrientation;
public int getWidth() {
if (width == null){
return -1;
}else{
return width;
}
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
if (height == null){
return -1;
}else{
return height;
}
}
public void setHeight(int height) {
this.height = height;
}
public String getLockedOrientation() {
return lockedOrientation;
}
public void lockOrientation(String lockedOrientation) {
if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){
this.lockedOrientation = lockedOrientation;
} else {
throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\"");
}
}
public String getRequestedCamera() {
return requestedCamera;
}
public void selectCamera(String camera) {
if(camera.equals("back") || camera.equals("front") || camera == null){
this.requestedCamera = camera;
} else {
throw new RuntimeException("Camera must be \"front\" or \"back\"");
}
}
}
|
// ... existing code ...
* Created by thomas on 1/16/15.
*/
public class BroadcastConfig {
private Integer width;
private Integer height;
private String requestedCamera;
private String lockedOrientation;
public int getWidth() {
if (width == null){
return -1;
}else{
return width;
}
}
public void setWidth(int width) {
// ... modified code ...
}
public int getHeight() {
if (height == null){
return -1;
}else{
return height;
}
}
public void setHeight(int height) {
// ... rest of the code ...
|
2d8a3b8c9ca6196317758e58cefc76163b88607f
|
falcom/table.py
|
falcom/table.py
|
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
if tab_separated_text and "\r" in tab_separated_text:
raise self.InputStrContainsCarriageReturn
self.text = tab_separated_text
if self.text:
self.text = self.text.rstrip("\n")
@property
def rows (self):
return len(self)
@property
def cols (self):
return len(self.text.split("\n")[0].split("\t")) if self.text else 0
def __len__ (self):
return len(self.text.split("\n")) if self.text else 0
def __iter__ (self):
if self.text:
for row in self.text.split("\n"):
yield(tuple(row.split("\t")))
else:
return iter(())
def __getitem__ (self, key):
if self.text:
return tuple(self.text.split("\n")[key].split("\t"))
else:
raise IndexError
def __repr__ (self):
return "<{} {}>".format(self.__class__.__name__,
repr(self.text))
|
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
if tab_separated_text:
if "\r" in tab_separated_text:
raise self.InputStrContainsCarriageReturn
self.text = tab_separated_text.rstrip("\n")
else:
self.text = tab_separated_text
@property
def rows (self):
return len(self)
@property
def cols (self):
return len(self.text.split("\n")[0].split("\t")) if self.text else 0
def __len__ (self):
return len(self.text.split("\n")) if self.text else 0
def __iter__ (self):
if self.text:
for row in self.text.split("\n"):
yield(tuple(row.split("\t")))
else:
return iter(())
def __getitem__ (self, key):
if self.text:
return tuple(self.text.split("\n")[key].split("\t"))
else:
raise IndexError
def __repr__ (self):
return "<{} {}>".format(self.__class__.__name__,
repr(self.text))
|
Move assignments in Table.__init__ around
|
Move assignments in Table.__init__ around
|
Python
|
bsd-3-clause
|
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
|
python
|
## Code Before:
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
if tab_separated_text and "\r" in tab_separated_text:
raise self.InputStrContainsCarriageReturn
self.text = tab_separated_text
if self.text:
self.text = self.text.rstrip("\n")
@property
def rows (self):
return len(self)
@property
def cols (self):
return len(self.text.split("\n")[0].split("\t")) if self.text else 0
def __len__ (self):
return len(self.text.split("\n")) if self.text else 0
def __iter__ (self):
if self.text:
for row in self.text.split("\n"):
yield(tuple(row.split("\t")))
else:
return iter(())
def __getitem__ (self, key):
if self.text:
return tuple(self.text.split("\n")[key].split("\t"))
else:
raise IndexError
def __repr__ (self):
return "<{} {}>".format(self.__class__.__name__,
repr(self.text))
## Instruction:
Move assignments in Table.__init__ around
## Code After:
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
if tab_separated_text:
if "\r" in tab_separated_text:
raise self.InputStrContainsCarriageReturn
self.text = tab_separated_text.rstrip("\n")
else:
self.text = tab_separated_text
@property
def rows (self):
return len(self)
@property
def cols (self):
return len(self.text.split("\n")[0].split("\t")) if self.text else 0
def __len__ (self):
return len(self.text.split("\n")) if self.text else 0
def __iter__ (self):
if self.text:
for row in self.text.split("\n"):
yield(tuple(row.split("\t")))
else:
return iter(())
def __getitem__ (self, key):
if self.text:
return tuple(self.text.split("\n")[key].split("\t"))
else:
raise IndexError
def __repr__ (self):
return "<{} {}>".format(self.__class__.__name__,
repr(self.text))
|
// ... existing code ...
pass
def __init__ (self, tab_separated_text = None):
if tab_separated_text:
if "\r" in tab_separated_text:
raise self.InputStrContainsCarriageReturn
self.text = tab_separated_text.rstrip("\n")
else:
self.text = tab_separated_text
@property
def rows (self):
// ... rest of the code ...
|
5b8106e848d99433f62310dbf3cb80ef9812e572
|
include/msvc_compat/C99/stdbool.h
|
include/msvc_compat/C99/stdbool.h
|
/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
typedef BOOL _Bool;
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* stdbool_h */
|
/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
/* Clang-cl uses MSVC headers, so needs msvc_compat, but has _Bool as
* a built-in type. */
#ifndef __clang__
typedef BOOL _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* stdbool_h */
|
Allow to build with clang-cl
|
Allow to build with clang-cl
|
C
|
bsd-2-clause
|
geekboxzone/lollipop_external_jemalloc,TeamExodus/external_jemalloc,TeamExodus/external_jemalloc,geekboxzone/mmallow_external_jemalloc,xin3liang/platform_external_jemalloc,VRToxin/android_external_jemalloc,geekboxzone/lollipop_external_jemalloc,CMRemix/android_external_jemalloc,sudosurootdev/external_jemalloc,CMRemix/android_external_jemalloc,CyanogenMod/android_external_jemalloc,CyanogenMod/android_external_jemalloc,android-ia/platform_external_jemalloc,geekboxzone/mmallow_external_jemalloc,android-ia/platform_external_jemalloc,AndroidExternal/jemalloc,VRToxin/android_external_jemalloc,sudosurootdev/external_jemalloc,VRToxin/android_external_jemalloc,CMRemix/android_external_jemalloc,CyanogenMod/android_external_jemalloc,TeamExodus/external_jemalloc,geekboxzone/mmallow_external_jemalloc,AndroidExternal/jemalloc,AndroidExternal/jemalloc,android-ia/platform_external_jemalloc,CMRemix/android_external_jemalloc,geekboxzone/mmallow_external_jemalloc,VRToxin/android_external_jemalloc,AndroidExternal/jemalloc,xin3liang/platform_external_jemalloc,sudosurootdev/external_jemalloc,xin3liang/platform_external_jemalloc,geekboxzone/lollipop_external_jemalloc,geekboxzone/lollipop_external_jemalloc,sudosurootdev/external_jemalloc,xin3liang/platform_external_jemalloc,CyanogenMod/android_external_jemalloc,TeamExodus/external_jemalloc,android-ia/platform_external_jemalloc
|
c
|
## Code Before:
/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
typedef BOOL _Bool;
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* stdbool_h */
## Instruction:
Allow to build with clang-cl
## Code After:
/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
/* Clang-cl uses MSVC headers, so needs msvc_compat, but has _Bool as
* a built-in type. */
#ifndef __clang__
typedef BOOL _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* stdbool_h */
|
...
/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
/* Clang-cl uses MSVC headers, so needs msvc_compat, but has _Bool as
* a built-in type. */
#ifndef __clang__
typedef BOOL _Bool;
#endif
#define bool _Bool
#define true 1
...
|
fd5b1bc59bc6b6640727fc88ade075be9b8355c4
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='[email protected]',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['thotkeeper/*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
|
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='[email protected]',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
|
Fix the XRC package_data entry.
|
Fix the XRC package_data entry.
|
Python
|
bsd-2-clause
|
cmpilato/thotkeeper
|
python
|
## Code Before:
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='[email protected]',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['thotkeeper/*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
## Instruction:
Fix the XRC package_data entry.
## Code After:
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='[email protected]',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
|
# ... existing code ...
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
# ... rest of the code ...
|
989ff44354d624906d72f20aac933a9243214cf8
|
corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py
|
corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
"""
return [
row['id'] for row in CommCareCase.get_db().view(
'cases_by_server_date/by_owner_server_modified_on',
startkey=[domain, owner_id, json_format_datetime(reference_date)],
endkey=[domain, owner_id, {}],
include_docs=False,
reduce=False
)
]
|
from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
"""
return [
row['id'] for row in CommCareCase.get_db().view(
'cases_by_server_date/by_owner_server_modified_on',
startkey=[domain, owner_id, json_format_datetime(reference_date)],
endkey=[domain, owner_id, {} if not until_date else json_format_datetime(until_date)],
include_docs=False,
reduce=False
)
]
|
Make get_case_ids_modified_with_owner_since accept an end date as well
|
Make get_case_ids_modified_with_owner_since accept an end date as well
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
python
|
## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
"""
return [
row['id'] for row in CommCareCase.get_db().view(
'cases_by_server_date/by_owner_server_modified_on',
startkey=[domain, owner_id, json_format_datetime(reference_date)],
endkey=[domain, owner_id, {}],
include_docs=False,
reduce=False
)
]
## Instruction:
Make get_case_ids_modified_with_owner_since accept an end date as well
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
"""
return [
row['id'] for row in CommCareCase.get_db().view(
'cases_by_server_date/by_owner_server_modified_on',
startkey=[domain, owner_id, json_format_datetime(reference_date)],
endkey=[domain, owner_id, {} if not until_date else json_format_datetime(until_date)],
include_docs=False,
reduce=False
)
]
|
...
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specified owner ID that have been modified
since a particular reference_date (using the server's timestamp)
...
row['id'] for row in CommCareCase.get_db().view(
'cases_by_server_date/by_owner_server_modified_on',
startkey=[domain, owner_id, json_format_datetime(reference_date)],
endkey=[domain, owner_id, {} if not until_date else json_format_datetime(until_date)],
include_docs=False,
reduce=False
)
...
|
33dd6ab01cea7a2a83d3d9d0c7682f716cbcb8b2
|
molecule/default/tests/test_default.py
|
molecule/default/tests/test_default.py
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed"""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version"""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3')
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3')
|
Fix lint errors in tests
|
Fix lint errors in tests
|
Python
|
apache-2.0
|
brucellino/cvmfs-client-2.2,brucellino/cvmfs-client-2.2,AAROC/cvmfs-client-2.2,AAROC/cvmfs-client-2.2
|
python
|
## Code Before:
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed"""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version"""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3')
## Instruction:
Fix lint errors in tests
## Code After:
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3')
|
# ... existing code ...
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
# ... modified code ...
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
...
assert pkg.is_installed
assert pkg.version.startswith(version)
assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
...
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
# ... rest of the code ...
|
ee960cafaa546a31b3682368c5513d5352770091
|
src/test/java/org/dita/dost/EndToEndTest.java
|
src/test/java/org/dita/dost/EndToEndTest.java
|
package org.dita.dost;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.warnCount(10)
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
|
package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.warnCount(10)
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
|
Add import of Ignore for ignored HTMLHelp test
|
Add import of Ignore for ignored HTMLHelp test
|
Java
|
apache-2.0
|
shaneataylor/dita-ot,shaneataylor/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,dita-ot/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,infotexture/dita-ot,drmacro/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,infotexture/dita-ot,infotexture/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot
|
java
|
## Code Before:
package org.dita.dost;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.warnCount(10)
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
## Instruction:
Add import of Ignore for ignored HTMLHelp test
## Code After:
package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.warnCount(10)
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
|
# ... existing code ...
package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
# ... rest of the code ...
|
9e6a016c5a59b25199426f6825b2c83571997e68
|
build/android/buildbot/tests/bb_run_bot_test.py
|
build/android/buildbot/tests/bb_run_bot_test.py
|
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotsWithTesting(bot_step_map):
code = 0
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bot_step_map]
for bot, proc in procs:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running bb_run_bot with id="%s"' % bot, err
return code
def main():
return RunBotsWithTesting(bb_run_bot.GetBotStepMap())
if __name__ == '__main__':
sys.exit(main())
|
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotProcesses(bot_process_map):
code = 0
for bot, proc in bot_process_map:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running the bot script with id="%s"' % bot, err
return code
def main():
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bb_run_bot.GetBotStepMap()]
return RunBotProcesses(procs)
if __name__ == '__main__':
sys.exit(main())
|
Refactor buildbot tests so that they can be used downstream.
|
[Android] Refactor buildbot tests so that they can be used downstream.
I refactored in the wrong way in r211209 (https://chromiumcodereview.appspot.com/18325030/). This CL fixes that. Note that r211209 is not broken; it is just not usable downstream.
BUG=249997
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/18202005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@211454 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
ondra-novak/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,jaruba/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,ltilve/chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,Chilledheart/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,Chilledheart/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,jaruba/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,littlstar/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,littlstar/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,ltilve/chromium,dushu1203/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,jaruba/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,anirudhSK/chromium
|
python
|
## Code Before:
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotsWithTesting(bot_step_map):
code = 0
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bot_step_map]
for bot, proc in procs:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running bb_run_bot with id="%s"' % bot, err
return code
def main():
return RunBotsWithTesting(bb_run_bot.GetBotStepMap())
if __name__ == '__main__':
sys.exit(main())
## Instruction:
[Android] Refactor buildbot tests so that they can be used downstream.
I refactored in the wrong way in r211209 (https://chromiumcodereview.appspot.com/18325030/). This CL fixes that. Note that r211209 is not broken; it is just not usable downstream.
BUG=249997
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/18202005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@211454 0039d316-1c4b-4281-b951-d872f2087c98
## Code After:
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotProcesses(bot_process_map):
code = 0
for bot, proc in bot_process_map:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running the bot script with id="%s"' % bot, err
return code
def main():
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bb_run_bot.GetBotStepMap()]
return RunBotProcesses(procs)
if __name__ == '__main__':
sys.exit(main())
|
...
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
def RunBotProcesses(bot_process_map):
code = 0
for bot, proc in bot_process_map:
_, err = proc.communicate()
code |= proc.returncode
if proc.returncode != 0:
print 'Error running the bot script with id="%s"' % bot, err
return code
def main():
procs = [
(bot, subprocess.Popen(
[os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
'--testing'], stdout=subprocess.PIPE, stderr=subprocess.PIPE))
for bot in bb_run_bot.GetBotStepMap()]
return RunBotProcesses(procs)
if __name__ == '__main__':
...
|
71b7885bc1e3740adf8c07c23b41835e1e69f8a2
|
sqlobject/tests/test_class_hash.py
|
sqlobject/tests/test_class_hash.py
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
# Test hashing a column instance
########################################
class ClassHashTest(SQLObject):
name = StringCol(length=50, alternateID=True, dbName='name_col')
def test_class_hash():
setupClass(ClassHashTest)
ClassHashTest(name='bob')
conn = ClassHashTest._connection
b = ClassHashTest.byName('bob')
hashed = hash(b)
b.expire()
b = ClassHashTest.byName('bob')
assert hash(b) == hashed
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
# Test hashing a column instance
########################################
class ClassHashTest(SQLObject):
name = StringCol(length=50, alternateID=True, dbName='name_col')
def test_class_hash():
setupClass(ClassHashTest)
ClassHashTest(name='bob')
b = ClassHashTest.byName('bob')
hashed = hash(b)
b.expire()
b = ClassHashTest.byName('bob')
assert hash(b) == hashed
|
Fix flake8 warning in test case
|
Fix flake8 warning in test case
|
Python
|
lgpl-2.1
|
drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject
|
python
|
## Code Before:
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
# Test hashing a column instance
########################################
class ClassHashTest(SQLObject):
name = StringCol(length=50, alternateID=True, dbName='name_col')
def test_class_hash():
setupClass(ClassHashTest)
ClassHashTest(name='bob')
conn = ClassHashTest._connection
b = ClassHashTest.byName('bob')
hashed = hash(b)
b.expire()
b = ClassHashTest.byName('bob')
assert hash(b) == hashed
## Instruction:
Fix flake8 warning in test case
## Code After:
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
# Test hashing a column instance
########################################
class ClassHashTest(SQLObject):
name = StringCol(length=50, alternateID=True, dbName='name_col')
def test_class_hash():
setupClass(ClassHashTest)
ClassHashTest(name='bob')
b = ClassHashTest.byName('bob')
hashed = hash(b)
b.expire()
b = ClassHashTest.byName('bob')
assert hash(b) == hashed
|
# ... existing code ...
setupClass(ClassHashTest)
ClassHashTest(name='bob')
b = ClassHashTest.byName('bob')
hashed = hash(b)
b.expire()
# ... rest of the code ...
|
56a89d57824d3bd25ac235a8e360d528edd9a7cf
|
test/factories/blogpost_factory.py
|
test/factories/blogpost_factory.py
|
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(lambda blogpost: blogpost.owner.id)
|
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(
lambda blogpost: blogpost.owner.id if blogpost.owner else None)
|
Fix for nullable author in blogpost factory
|
Fix for nullable author in blogpost factory
|
Python
|
agpl-3.0
|
OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,proyectos-analizo-info/pybossa-analizo-info,geotagx/pybossa,inteligencia-coletiva-lsd/pybossa,jean/pybossa,proyectos-analizo-info/pybossa-analizo-info,harihpr/tweetclickers,stefanhahmann/pybossa,OpenNewsLabs/pybossa,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa,jean/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,PyBossa/pybossa,Scifabric/pybossa,geotagx/pybossa,PyBossa/pybossa
|
python
|
## Code Before:
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(lambda blogpost: blogpost.owner.id)
## Instruction:
Fix for nullable author in blogpost factory
## Code After:
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(
lambda blogpost: blogpost.owner.id if blogpost.owner else None)
|
...
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(
lambda blogpost: blogpost.owner.id if blogpost.owner else None)
...
|
7f3f2802fb3c00baf440ebdc10920ad0b48118f9
|
setup.py
|
setup.py
|
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='[email protected]',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
|
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='[email protected]',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
|
Use attrs<19.2.0 to avoid pytest error
|
Use attrs<19.2.0 to avoid pytest error
|
Python
|
mit
|
toslunar/chainerrl,toslunar/chainerrl
|
python
|
## Code Before:
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='[email protected]',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
## Instruction:
Use attrs<19.2.0 to avoid pytest error
## Code After:
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='[email protected]',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
|
# ... existing code ...
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2):
# ... rest of the code ...
|
6bc4f24c8bdd2be0875fba7cb98a81ff86caa5c3
|
tests/behave/environment.py
|
tests/behave/environment.py
|
from toolium.behave.environment import before_scenario, after_scenario, after_all
|
import os
from toolium.behave.environment import before_all as toolium_before_all, before_scenario, after_scenario, after_all
from toolium.config_files import ConfigFiles
def before_all(context):
config_files = ConfigFiles()
config_files.set_config_directory(os.path.join(get_root_path(), 'conf'))
config_files.set_output_directory(os.path.join(get_root_path(), 'output'))
config_files.set_config_properties_filenames('properties.cfg', 'local-properties.cfg')
context.config_files = config_files
toolium_before_all(context)
def get_root_path():
"""Returns absolute path of the project root folder
:returns: root folder path
"""
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
|
Add before_all method to set configuration files
|
Add before_all method to set configuration files
|
Python
|
apache-2.0
|
Telefonica/toolium-examples
|
python
|
## Code Before:
from toolium.behave.environment import before_scenario, after_scenario, after_all
## Instruction:
Add before_all method to set configuration files
## Code After:
import os
from toolium.behave.environment import before_all as toolium_before_all, before_scenario, after_scenario, after_all
from toolium.config_files import ConfigFiles
def before_all(context):
config_files = ConfigFiles()
config_files.set_config_directory(os.path.join(get_root_path(), 'conf'))
config_files.set_output_directory(os.path.join(get_root_path(), 'output'))
config_files.set_config_properties_filenames('properties.cfg', 'local-properties.cfg')
context.config_files = config_files
toolium_before_all(context)
def get_root_path():
"""Returns absolute path of the project root folder
:returns: root folder path
"""
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
|
# ... existing code ...
import os
from toolium.behave.environment import before_all as toolium_before_all, before_scenario, after_scenario, after_all
from toolium.config_files import ConfigFiles
def before_all(context):
config_files = ConfigFiles()
config_files.set_config_directory(os.path.join(get_root_path(), 'conf'))
config_files.set_output_directory(os.path.join(get_root_path(), 'output'))
config_files.set_config_properties_filenames('properties.cfg', 'local-properties.cfg')
context.config_files = config_files
toolium_before_all(context)
def get_root_path():
"""Returns absolute path of the project root folder
:returns: root folder path
"""
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
# ... rest of the code ...
|
c938227b9fcbf43d079bfd3a1e12244da2b3b73c
|
include/psp2/update.h
|
include/psp2/update.h
|
/**
* \usergroup{SceUpdateMgr}
* \usage{psp2/update.h,SceSblSsUpdateMgr_stub}
*/
#ifndef _PSP2_UPDATE_MGR_H_
#define _PSP2_UPDATE_MGR_H_
#include <psp2/types.h>
typedef char SceUpdateMode;
#define SCE_UPDATE_MODE_SWU_GUI 0x10
#define SCE_UPDATE_MODE_SWU_CUI 0x30
/**
* Getting system update mode on boot
*
* @param[out] mode - The pointer of SceUpdateMode variable
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsGetUpdateMode(SceUpdateMode *mode);
/**
* Setting system update mode on boot
*
* @param[in] mode - The update mode
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsSetUpdateMode(SceUpdateMode mode);
/**
* Verify PUP
*
* @param[in] path - The PUP path
*
* @return 0 on success, < 0 on error.
*
* note - If verify CEX PUP on Devkit system, got error.
*/
int sceSblUsVerifyPup(const char *path);
#endif /* _PSP2_UPDATE_MGR_H_ */
|
/**
* \usergroup{SceUpdateMgr}
* \usage{psp2/update.h,SceSblSsUpdateMgr_stub}
*/
#ifndef _PSP2_UPDATE_MGR_H_
#define _PSP2_UPDATE_MGR_H_
#include <psp2/types.h>
typedef char SceUpdateMode;
#define SCE_UPDATE_MODE_SWU_GUI 0x10
#define SCE_UPDATE_MODE_SWU_CUI 0x30
/**
* Getting system update mode on boot
*
* @param[out] mode - The pointer of SceUpdateMode variable
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsGetUpdateMode(SceUpdateMode *mode);
#define sceSblSsUpdateMgrGetBootMode sceSblUsGetUpdateMode
/**
* Setting system update mode on boot
*
* @param[in] mode - The update mode
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsSetUpdateMode(SceUpdateMode mode);
#define sceSblSsUpdateMgrSetBootMode sceSblUsSetUpdateMode
/**
* Verify PUP
*
* @param[in] path - The PUP path
*
* @return 0 on success, < 0 on error.
*
* note - If verify CEX PUP on Devkit system, got error.
*/
int sceSblUsVerifyPup(const char *path);
#endif /* _PSP2_UPDATE_MGR_H_ */
|
Fix compatibility with some modules
|
Fix compatibility with some modules
|
C
|
mit
|
Rinnegatamante/vita-headers,vitasdk/vita-headers,Rinnegatamante/vita-headers,vitasdk/vita-headers,Rinnegatamante/vita-headers,Rinnegatamante/vita-headers,vitasdk/vita-headers,vitasdk/vita-headers
|
c
|
## Code Before:
/**
* \usergroup{SceUpdateMgr}
* \usage{psp2/update.h,SceSblSsUpdateMgr_stub}
*/
#ifndef _PSP2_UPDATE_MGR_H_
#define _PSP2_UPDATE_MGR_H_
#include <psp2/types.h>
typedef char SceUpdateMode;
#define SCE_UPDATE_MODE_SWU_GUI 0x10
#define SCE_UPDATE_MODE_SWU_CUI 0x30
/**
* Getting system update mode on boot
*
* @param[out] mode - The pointer of SceUpdateMode variable
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsGetUpdateMode(SceUpdateMode *mode);
/**
* Setting system update mode on boot
*
* @param[in] mode - The update mode
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsSetUpdateMode(SceUpdateMode mode);
/**
* Verify PUP
*
* @param[in] path - The PUP path
*
* @return 0 on success, < 0 on error.
*
* note - If verify CEX PUP on Devkit system, got error.
*/
int sceSblUsVerifyPup(const char *path);
#endif /* _PSP2_UPDATE_MGR_H_ */
## Instruction:
Fix compatibility with some modules
## Code After:
/**
* \usergroup{SceUpdateMgr}
* \usage{psp2/update.h,SceSblSsUpdateMgr_stub}
*/
#ifndef _PSP2_UPDATE_MGR_H_
#define _PSP2_UPDATE_MGR_H_
#include <psp2/types.h>
typedef char SceUpdateMode;
#define SCE_UPDATE_MODE_SWU_GUI 0x10
#define SCE_UPDATE_MODE_SWU_CUI 0x30
/**
* Getting system update mode on boot
*
* @param[out] mode - The pointer of SceUpdateMode variable
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsGetUpdateMode(SceUpdateMode *mode);
#define sceSblSsUpdateMgrGetBootMode sceSblUsGetUpdateMode
/**
* Setting system update mode on boot
*
* @param[in] mode - The update mode
*
* @return 0 on success, < 0 on error.
*/
int sceSblUsSetUpdateMode(SceUpdateMode mode);
#define sceSblSsUpdateMgrSetBootMode sceSblUsSetUpdateMode
/**
* Verify PUP
*
* @param[in] path - The PUP path
*
* @return 0 on success, < 0 on error.
*
* note - If verify CEX PUP on Devkit system, got error.
*/
int sceSblUsVerifyPup(const char *path);
#endif /* _PSP2_UPDATE_MGR_H_ */
|
// ... existing code ...
*/
int sceSblUsGetUpdateMode(SceUpdateMode *mode);
#define sceSblSsUpdateMgrGetBootMode sceSblUsGetUpdateMode
/**
* Setting system update mode on boot
*
// ... modified code ...
* @return 0 on success, < 0 on error.
*/
int sceSblUsSetUpdateMode(SceUpdateMode mode);
#define sceSblSsUpdateMgrSetBootMode sceSblUsSetUpdateMode
/**
* Verify PUP
// ... rest of the code ...
|
957bb5e3795c00750ae12dfdcc0f863160e69ba2
|
storm-data-contracts/src/main/java/com/forter/contracts/validation/OneOfValidator.java
|
storm-data-contracts/src/main/java/com/forter/contracts/validation/OneOfValidator.java
|
package com.forter.contracts.validation;
import com.google.common.base.Preconditions;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
/**
* Checks against one of the specified values
*/
public class OneOfValidator implements ConstraintValidator<OneOf, Object>{
private List<String> values;
@Override
public void initialize(OneOf constraintAnnotation) {
values = Arrays.asList(constraintAnnotation.value());
Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value != null && values.contains(String.valueOf(value));
}
}
|
package com.forter.contracts.validation;
import com.google.common.base.Preconditions;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
/**
* Checks against one of the specified values.
* Returns isValid true if the value is null. Use @NotNull to explicitly reject null values.
*/
public class OneOfValidator implements ConstraintValidator<OneOf, Object>{
private List<String> values;
@Override
public void initialize(OneOf constraintAnnotation) {
values = Arrays.asList(constraintAnnotation.value());
Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value == null || values.contains(String.valueOf(value));
}
}
|
Fix @OneOf to approve null values
|
Fix @OneOf to approve null values
|
Java
|
apache-2.0
|
talbor49/storm-data-contracts,forter/storm-data-contracts,conkeyn/storm-data-contracts
|
java
|
## Code Before:
package com.forter.contracts.validation;
import com.google.common.base.Preconditions;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
/**
* Checks against one of the specified values
*/
public class OneOfValidator implements ConstraintValidator<OneOf, Object>{
private List<String> values;
@Override
public void initialize(OneOf constraintAnnotation) {
values = Arrays.asList(constraintAnnotation.value());
Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value != null && values.contains(String.valueOf(value));
}
}
## Instruction:
Fix @OneOf to approve null values
## Code After:
package com.forter.contracts.validation;
import com.google.common.base.Preconditions;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
/**
* Checks against one of the specified values.
* Returns isValid true if the value is null. Use @NotNull to explicitly reject null values.
*/
public class OneOfValidator implements ConstraintValidator<OneOf, Object>{
private List<String> values;
@Override
public void initialize(OneOf constraintAnnotation) {
values = Arrays.asList(constraintAnnotation.value());
Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value == null || values.contains(String.valueOf(value));
}
}
|
// ... existing code ...
import java.util.List;
/**
* Checks against one of the specified values.
* Returns isValid true if the value is null. Use @NotNull to explicitly reject null values.
*/
public class OneOfValidator implements ConstraintValidator<OneOf, Object>{
// ... modified code ...
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return value == null || values.contains(String.valueOf(value));
}
}
// ... rest of the code ...
|
2e131bf04bd44ce4b86b73481838e47fdcdab3eb
|
subscription/src/main/java/com/timgroup/eventsubscription/BroadcastingEventHandler.java
|
subscription/src/main/java/com/timgroup/eventsubscription/BroadcastingEventHandler.java
|
package com.timgroup.eventsubscription;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
final class BroadcastingEventHandler implements EventHandler {
private final List<EventHandler> handlers;
BroadcastingEventHandler(List<? extends EventHandler> handlers) {
this.handlers = new ArrayList<>(handlers);
}
@Override
public void apply(ResolvedEvent resolvedEvent, Event deserializedEvent, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(resolvedEvent, deserializedEvent, endOfBatch);
}
}
@Override
public void apply(Position position, DateTime timestamp, Event deserialized, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(position, timestamp, deserialized, endOfBatch);
}
}
@Override
public void apply(Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(deserialized);
}
}
}
|
package com.timgroup.eventsubscription;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
final class BroadcastingEventHandler implements EventHandler {
private final List<EventHandler> handlers;
BroadcastingEventHandler(List<? extends EventHandler> handlers) {
this.handlers = new ArrayList<>(handlers);
}
@Override
public void apply(ResolvedEvent resolvedEvent, Event deserializedEvent, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(resolvedEvent, deserializedEvent, endOfBatch);
}
}
@Override
public void apply(Position position, Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(position, deserialized);
}
}
@Override
public void apply(Position position, DateTime timestamp, Event deserialized, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(position, timestamp, deserialized, endOfBatch);
}
}
@Override
public void apply(Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(deserialized);
}
}
}
|
Add new method to broadcast for consistency
|
Add new method to broadcast for consistency
|
Java
|
bsd-2-clause
|
tim-group/tg-eventstore,tim-group/tg-eventstore
|
java
|
## Code Before:
package com.timgroup.eventsubscription;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
final class BroadcastingEventHandler implements EventHandler {
private final List<EventHandler> handlers;
BroadcastingEventHandler(List<? extends EventHandler> handlers) {
this.handlers = new ArrayList<>(handlers);
}
@Override
public void apply(ResolvedEvent resolvedEvent, Event deserializedEvent, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(resolvedEvent, deserializedEvent, endOfBatch);
}
}
@Override
public void apply(Position position, DateTime timestamp, Event deserialized, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(position, timestamp, deserialized, endOfBatch);
}
}
@Override
public void apply(Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(deserialized);
}
}
}
## Instruction:
Add new method to broadcast for consistency
## Code After:
package com.timgroup.eventsubscription;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
final class BroadcastingEventHandler implements EventHandler {
private final List<EventHandler> handlers;
BroadcastingEventHandler(List<? extends EventHandler> handlers) {
this.handlers = new ArrayList<>(handlers);
}
@Override
public void apply(ResolvedEvent resolvedEvent, Event deserializedEvent, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(resolvedEvent, deserializedEvent, endOfBatch);
}
}
@Override
public void apply(Position position, Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(position, deserialized);
}
}
@Override
public void apply(Position position, DateTime timestamp, Event deserialized, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(position, timestamp, deserialized, endOfBatch);
}
}
@Override
public void apply(Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(deserialized);
}
}
}
|
# ... existing code ...
}
@Override
public void apply(Position position, Event deserialized) {
for (EventHandler handler : handlers) {
handler.apply(position, deserialized);
}
}
@Override
public void apply(Position position, DateTime timestamp, Event deserialized, boolean endOfBatch) {
for (EventHandler handler : handlers) {
handler.apply(position, timestamp, deserialized, endOfBatch);
# ... rest of the code ...
|
270a03dc78838137051fec49050f550c44be2359
|
facebook_auth/views.py
|
facebook_auth/views.py
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
self.login(next_url)
response = http.HttpResponseRedirect(next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(next_url['close'])
return response
def login(self, next_url):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(next_url['next'],
next_url['close']))
if user:
login(self.request, user)
handler = Handler.as_view()
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
try:
self.login()
except facepy.FacepyError as e:
return self.handle_facebook_error(e)
response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(self.next_url['close'])
return response
def login(self):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(self.next_url['next'],
self.next_url['close']))
if user:
login(self.request, user)
def handle_facebook_error(self, e):
return http.HttpResponseRedirect(self.next_url['next'])
handler = Handler.as_view()
|
Add facebook error handler in view.
|
Add facebook error handler in view.
This assumes that there is no other backend which
can authenticate user with facebook credentials.
|
Python
|
mit
|
jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth
|
python
|
## Code Before:
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
self.login(next_url)
response = http.HttpResponseRedirect(next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(next_url['close'])
return response
def login(self, next_url):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(next_url['next'],
next_url['close']))
if user:
login(self.request, user)
handler = Handler.as_view()
## Instruction:
Add facebook error handler in view.
This assumes that there is no other backend which
can authenticate user with facebook credentials.
## Code After:
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
try:
self.login()
except facepy.FacepyError as e:
return self.handle_facebook_error(e)
response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(self.next_url['close'])
return response
def login(self):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(self.next_url['next'],
self.next_url['close']))
if user:
login(self.request, user)
def handle_facebook_error(self, e):
return http.HttpResponseRedirect(self.next_url['next'])
handler = Handler.as_view()
|
# ... existing code ...
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
# ... modified code ...
class Handler(generic.View):
def get(self, request):
try:
self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
try:
self.login()
except facepy.FacepyError as e:
return self.handle_facebook_error(e)
response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(self.next_url['close'])
return response
def login(self):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(self.next_url['next'],
self.next_url['close']))
if user:
login(self.request, user)
def handle_facebook_error(self, e):
return http.HttpResponseRedirect(self.next_url['next'])
handler = Handler.as_view()
# ... rest of the code ...
|
d80a21abcc56192d57c987cf4b8e2057e1d4ffcd
|
nethud/nh_client.py
|
nethud/nh_client.py
|
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
Make all the things unicode.
|
Make all the things unicode.
|
Python
|
mit
|
ryansb/netHUD
|
python
|
## Code Before:
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
## Instruction:
Make all the things unicode.
## Code After:
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
# ... existing code ...
from __future__ import unicode_literals
import json
# ... modified code ...
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
# ... rest of the code ...
|
20dbd80d0262869f3378597d7152dab7a6104de8
|
routes/__init__.py
|
routes/__init__.py
|
import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
|
import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
__all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
|
Tweak for exporting the symbols
|
[svn] Tweak for exporting the symbols
--HG--
branch : trunk
|
Python
|
mit
|
alex/routes,bbangert/routes,mikepk/routes,webknjaz/routes,mikepk/pybald-routes
|
python
|
## Code Before:
import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
## Instruction:
[svn] Tweak for exporting the symbols
--HG--
branch : trunk
## Code After:
import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
__all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
|
...
from base import Mapper
from util import url_for, redirect_to
__all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
...
|
5e4e424a1fdf967b71c138cf8a0fc5140f37629e
|
src/main/java/RArray.java
|
src/main/java/RArray.java
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class RArray extends RObject {
public final ArrayList<RObject> impl;
public RArray() {
impl = new ArrayList<RObject>();
}
public RArray(RObject... args) {
impl = new ArrayList<RObject>(Arrays.asList(args));
}
public RArray(List<RObject> impl) {
this.impl = new ArrayList<RObject>(impl);
}
public RObject $less$less(RObject what) {
add(what);
return this;
}
public RObject $lbrack$rbrack(RObject where) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < size()) {
return get(index);
}
return RNil;
}
public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
int index = (int)((RFixnum)where.to_i()).fix;
// TODO index >= size
impl.set(index, what);
return this;
}
public RObject size() {
return new RFixnum(impl.size());
}
public RObject clear() {
impl.clear();
return this;
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class RArray extends RObject {
public final ArrayList<RObject> impl;
public RArray() {
impl = new ArrayList<RObject>();
}
public RArray(RObject... args) {
impl = new ArrayList<RObject>(Arrays.asList(args));
}
public RArray(List<RObject> impl) {
this.impl = new ArrayList<RObject>(impl);
}
public RObject $less$less(RObject what) {
impl.add(what);
return this;
}
public RObject $lbrack$rbrack(RObject where) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index < impl.size()) {
return impl.get(index);
} else {
return RNil;
}
}
public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index >= impl.size()) {
impl.ensureCapacity(index + 1);
}
impl.set(index, what);
return this;
}
public RObject size() {
return new RFixnum(impl.size());
}
public RObject clear() {
impl.clear();
return this;
}
}
|
Fix existing Array methods and support negative and >= size sets.
|
Fix existing Array methods and support negative and >= size sets.
|
Java
|
apache-2.0
|
headius/rubyflux,amorphid/rubyflux,headius/rubyflux,amorphid/rubyflux
|
java
|
## Code Before:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class RArray extends RObject {
public final ArrayList<RObject> impl;
public RArray() {
impl = new ArrayList<RObject>();
}
public RArray(RObject... args) {
impl = new ArrayList<RObject>(Arrays.asList(args));
}
public RArray(List<RObject> impl) {
this.impl = new ArrayList<RObject>(impl);
}
public RObject $less$less(RObject what) {
add(what);
return this;
}
public RObject $lbrack$rbrack(RObject where) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < size()) {
return get(index);
}
return RNil;
}
public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
int index = (int)((RFixnum)where.to_i()).fix;
// TODO index >= size
impl.set(index, what);
return this;
}
public RObject size() {
return new RFixnum(impl.size());
}
public RObject clear() {
impl.clear();
return this;
}
}
## Instruction:
Fix existing Array methods and support negative and >= size sets.
## Code After:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class RArray extends RObject {
public final ArrayList<RObject> impl;
public RArray() {
impl = new ArrayList<RObject>();
}
public RArray(RObject... args) {
impl = new ArrayList<RObject>(Arrays.asList(args));
}
public RArray(List<RObject> impl) {
this.impl = new ArrayList<RObject>(impl);
}
public RObject $less$less(RObject what) {
impl.add(what);
return this;
}
public RObject $lbrack$rbrack(RObject where) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index < impl.size()) {
return impl.get(index);
} else {
return RNil;
}
}
public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index >= impl.size()) {
impl.ensureCapacity(index + 1);
}
impl.set(index, what);
return this;
}
public RObject size() {
return new RFixnum(impl.size());
}
public RObject clear() {
impl.clear();
return this;
}
}
|
// ... existing code ...
}
public RObject $less$less(RObject what) {
impl.add(what);
return this;
}
// ... modified code ...
public RObject $lbrack$rbrack(RObject where) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index < impl.size()) {
return impl.get(index);
} else {
return RNil;
}
}
public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
int index = (int)((RFixnum)where.to_i()).fix;
if (index < 0) {
index = impl.size() + index;
}
if (index >= impl.size()) {
impl.ensureCapacity(index + 1);
}
impl.set(index, what);
return this;
// ... rest of the code ...
|
c74edbeb427255f520f8bdbbeb5d278003ead728
|
src/main/java/no/uio/ifi/trackfind/backend/services/GSuiteService.java
|
src/main/java/no/uio/ifi/trackfind/backend/services/GSuiteService.java
|
package no.uio.ifi.trackfind.backend.services;
import no.uio.ifi.trackfind.backend.dao.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.function.Function;
/**
* Service for querying remote GSuite service for performing JSON to GSuite conversion.
*/
@Service
public class GSuiteService implements Function<Collection<Dataset>, String> {
private RestTemplate restTemplate;
/**
* Convert datasets to GSuite.
*
* @param datasets Datasets to convert.
* @return GSuite string.
*/
@SuppressWarnings("unchecked")
@Override
public String apply(Collection<Dataset> datasets) {
HttpEntity<Collection<Dataset>> request = new HttpEntity<>(datasets);
return restTemplate.postForObject("http://gsuite/togsuite", request, String.class);
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
|
package no.uio.ifi.trackfind.backend.services;
import no.uio.ifi.trackfind.backend.dao.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Service for querying remote GSuite service for performing JSON to GSuite conversion.
*/
@Service
public class GSuiteService implements Function<Collection<Dataset>, String> {
private RestTemplate restTemplate;
private SchemaService schemaService;
/**
* Convert datasets to GSuite.
*
* @param datasets Datasets to convert.
* @return GSuite string.
*/
@SuppressWarnings("unchecked")
@Override
public String apply(Collection<Dataset> datasets) {
Map<String, Object> body = new HashMap<>();
body.put("attributes", schemaService.getAttributes());
body.put("datasets", datasets);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(body);
return restTemplate.postForObject("http://gsuite/togsuite", request, String.class);
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Autowired
public void setSchemaService(SchemaService schemaService) {
this.schemaService = schemaService;
}
}
|
Send FAIR attributes to GSuite service.
|
Send FAIR attributes to GSuite service.
|
Java
|
mit
|
elixir-no-nels/trackfind,elixir-no-nels/trackfind,elixir-no-nels/trackfind
|
java
|
## Code Before:
package no.uio.ifi.trackfind.backend.services;
import no.uio.ifi.trackfind.backend.dao.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.function.Function;
/**
* Service for querying remote GSuite service for performing JSON to GSuite conversion.
*/
@Service
public class GSuiteService implements Function<Collection<Dataset>, String> {
private RestTemplate restTemplate;
/**
* Convert datasets to GSuite.
*
* @param datasets Datasets to convert.
* @return GSuite string.
*/
@SuppressWarnings("unchecked")
@Override
public String apply(Collection<Dataset> datasets) {
HttpEntity<Collection<Dataset>> request = new HttpEntity<>(datasets);
return restTemplate.postForObject("http://gsuite/togsuite", request, String.class);
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
## Instruction:
Send FAIR attributes to GSuite service.
## Code After:
package no.uio.ifi.trackfind.backend.services;
import no.uio.ifi.trackfind.backend.dao.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Service for querying remote GSuite service for performing JSON to GSuite conversion.
*/
@Service
public class GSuiteService implements Function<Collection<Dataset>, String> {
private RestTemplate restTemplate;
private SchemaService schemaService;
/**
* Convert datasets to GSuite.
*
* @param datasets Datasets to convert.
* @return GSuite string.
*/
@SuppressWarnings("unchecked")
@Override
public String apply(Collection<Dataset> datasets) {
Map<String, Object> body = new HashMap<>();
body.put("attributes", schemaService.getAttributes());
body.put("datasets", datasets);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(body);
return restTemplate.postForObject("http://gsuite/togsuite", request, String.class);
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Autowired
public void setSchemaService(SchemaService schemaService) {
this.schemaService = schemaService;
}
}
|
...
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
...
public class GSuiteService implements Function<Collection<Dataset>, String> {
private RestTemplate restTemplate;
private SchemaService schemaService;
/**
* Convert datasets to GSuite.
...
@SuppressWarnings("unchecked")
@Override
public String apply(Collection<Dataset> datasets) {
Map<String, Object> body = new HashMap<>();
body.put("attributes", schemaService.getAttributes());
body.put("datasets", datasets);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(body);
return restTemplate.postForObject("http://gsuite/togsuite", request, String.class);
}
...
this.restTemplate = restTemplate;
}
@Autowired
public void setSchemaService(SchemaService schemaService) {
this.schemaService = schemaService;
}
}
...
|
271b4cd3795cbe0e5e013ac53c3ea26ca08e7a1a
|
IPython/utils/importstring.py
|
IPython/utils/importstring.py
|
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
return module.__dict__[obj]
else:
return __import__(obj)
|
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
return __import__(obj)
|
Fix error in test suite startup with dotted import names.
|
Fix error in test suite startup with dotted import names.
Detected first on ubuntu 12.04, but the bug is generic, we just hadn't
seen it before. Will push straight to master as this will begin
causing problems as more people upgrade.
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
python
|
## Code Before:
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
return module.__dict__[obj]
else:
return __import__(obj)
## Instruction:
Fix error in test suite startup with dotted import names.
Detected first on ubuntu 12.04, but the bug is generic, we just hadn't
seen it before. Will push straight to master as this will begin
causing problems as more people upgrade.
## Code After:
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# the road, to make it easier on anyone looking for a problem. This code
# should be removed once we're comfortable we didn't break anything.
## execString = 'from %s import %s' % (package, obj)
## try:
## exec execString
## except SyntaxError:
## raise ImportError("Invalid class specification: %s" % name)
## exec 'temp = %s' % obj
## return temp
if package:
module = __import__(package,fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
return __import__(obj)
|
// ... existing code ...
if package:
module = __import__(package,fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
return __import__(obj)
// ... rest of the code ...
|
318d87ddc093ded8e70bb41204079c45e73b4e5e
|
os/atTime.h
|
os/atTime.h
|
// Under Windows, define the gettimeofday() function with corresponding types
#ifdef _MSC_VER
#include <windows.h>
#include <time.h>
// TYPES
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
// FUNCTIONS
int gettimeofday(struct timeval * tv, struct timezone * tz);
#else
#include <sys/time.h>
#endif
#endif
|
// Under Windows, define the gettimeofday() function with corresponding types
#ifdef _MSC_VER
#include <windows.h>
#include <time.h>
#include "atSymbols.h"
// TYPES
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
// FUNCTIONS
ATLAS_SYM int gettimeofday(struct timeval * tv, struct timezone * tz);
#else
#include <sys/time.h>
#endif
#endif
|
Add the atSymbols to this so the getTimeOfDay function was usable outside of the windows dll.
|
Add the atSymbols to this so the getTimeOfDay function was usable outside of the windows dll.
|
C
|
apache-2.0
|
ucfistirl/atlas,ucfistirl/atlas
|
c
|
## Code Before:
// Under Windows, define the gettimeofday() function with corresponding types
#ifdef _MSC_VER
#include <windows.h>
#include <time.h>
// TYPES
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
// FUNCTIONS
int gettimeofday(struct timeval * tv, struct timezone * tz);
#else
#include <sys/time.h>
#endif
#endif
## Instruction:
Add the atSymbols to this so the getTimeOfDay function was usable outside of the windows dll.
## Code After:
// Under Windows, define the gettimeofday() function with corresponding types
#ifdef _MSC_VER
#include <windows.h>
#include <time.h>
#include "atSymbols.h"
// TYPES
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
// FUNCTIONS
ATLAS_SYM int gettimeofday(struct timeval * tv, struct timezone * tz);
#else
#include <sys/time.h>
#endif
#endif
|
// ... existing code ...
#ifdef _MSC_VER
#include <windows.h>
#include <time.h>
#include "atSymbols.h"
// TYPES
// ... modified code ...
// FUNCTIONS
ATLAS_SYM int gettimeofday(struct timeval * tv, struct timezone * tz);
#else
#include <sys/time.h>
#endif
// ... rest of the code ...
|
a57f7c43bc7749de5acd42b6db95d77074308cef
|
scaper/__init__.py
|
scaper/__init__.py
|
"""Top-level module for scaper"""
from .core import *
__version__ = '0.1.0'
|
"""Top-level module for scaper"""
from .core import *
import jams
from pkg_resources import resource_filename
__version__ = '0.1.0'
# Add sound_event namesapce
namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
jams.schema.add_namespace(namespace_file)
|
Add sound_event namespace to jams during init
|
Add sound_event namespace to jams during init
|
Python
|
bsd-3-clause
|
justinsalamon/scaper
|
python
|
## Code Before:
"""Top-level module for scaper"""
from .core import *
__version__ = '0.1.0'
## Instruction:
Add sound_event namespace to jams during init
## Code After:
"""Top-level module for scaper"""
from .core import *
import jams
from pkg_resources import resource_filename
__version__ = '0.1.0'
# Add sound_event namesapce
namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
jams.schema.add_namespace(namespace_file)
|
# ... existing code ...
"""Top-level module for scaper"""
from .core import *
import jams
from pkg_resources import resource_filename
__version__ = '0.1.0'
# Add sound_event namesapce
namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
jams.schema.add_namespace(namespace_file)
# ... rest of the code ...
|
a721476360ad88fa3e28202b4a399af3e7da2259
|
src/Engine/windowManager.h
|
src/Engine/windowManager.h
|
#ifndef windowManager_H
#define windowManager_H
#include <iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
class windowManager
{
public:
void init();
void windowManager::getScreenSize();
//Functions to return dimensions of window
int getWindowHeight();
int getWindowWidth();
GLFWwindow* getWindow();
private:
//The window height
int width;
int height;
GLFWwindow* currentWindow;
};
#endif
|
#ifndef windowManager_H
#define windowManager_H
#include <iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
class windowManager
{
public:
void init();
void getScreenSize();
//Functions to return dimensions of window
int getWindowHeight();
int getWindowWidth();
GLFWwindow* getWindow();
private:
//The window height
int width;
int height;
GLFWwindow* currentWindow;
};
#endif
|
Fix building error on Linux
|
Fix building error on Linux
|
C
|
apache-2.0
|
Afrostie/Mopviewer
|
c
|
## Code Before:
#ifndef windowManager_H
#define windowManager_H
#include <iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
class windowManager
{
public:
void init();
void windowManager::getScreenSize();
//Functions to return dimensions of window
int getWindowHeight();
int getWindowWidth();
GLFWwindow* getWindow();
private:
//The window height
int width;
int height;
GLFWwindow* currentWindow;
};
#endif
## Instruction:
Fix building error on Linux
## Code After:
#ifndef windowManager_H
#define windowManager_H
#include <iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
class windowManager
{
public:
void init();
void getScreenSize();
//Functions to return dimensions of window
int getWindowHeight();
int getWindowWidth();
GLFWwindow* getWindow();
private:
//The window height
int width;
int height;
GLFWwindow* currentWindow;
};
#endif
|
# ... existing code ...
public:
void init();
void getScreenSize();
//Functions to return dimensions of window
int getWindowHeight();
int getWindowWidth();
# ... rest of the code ...
|
b6eaabd47e98d51e4392c5419a59a75a0db45bf1
|
geotrek/core/tests/test_forms.py
|
geotrek/core/tests/test_forms.py
|
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
|
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
|
Add tests for path overlapping check
|
Add tests for path overlapping check
|
Python
|
bsd-2-clause
|
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin
|
python
|
## Code Before:
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
## Instruction:
Add tests for path overlapping check
## Code After:
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
|
...
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
...
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
...
|
114eae527cce97423ec5cc5896a4728dc0764d2c
|
chunsabot/modules/images.py
|
chunsabot/modules/images.py
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
Fix some confusion of creating folders
|
Fix some confusion of creating folders
|
Python
|
mit
|
susemeee/Chunsabot-framework
|
python
|
## Code Before:
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
## Instruction:
Fix some confusion of creating folders
## Code After:
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
...
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
...
|
20d766de4d20355303b5b423dd30bf0cd4c8ee8e
|
createGlyphsPDF.py
|
createGlyphsPDF.py
|
from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
my_selection = CurrentFont() # May also be CurrentFont.selection or else
class RegisterGlyph(object):
def __init__(self, glyph):
self.glyph = glyph
print 'Registered glyph:', self.glyph.name
self.proportion_ratio = self.getProportionRatio()
def getProportionRatio(self):
xMin, yMin, xMax, yMax = self.glyph.box
self.w = xMax - xMin
self.h = yMax - yMin
ratio = self.w/self.h
return ratio
def drawGlyphOnNewPage(self):
newPage(page_format)
self._drawGlyph()
def _drawGlyph(self):
pen = CocoaPen(self.glyph.getParent())
self.glyph.draw(pen)
drawPath(pen.path)
for g in my_selection:
if len(g) > 0: # Ignore whitespace glyphs
glyph = RegisterGlyph(g)
glyph.drawGlyphOnNewPage()
|
from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
margins = (50,50,50,50) # left, top, right, bottom
my_selection = CurrentFont() # May also be CurrentFont.selection or else
# Init
size(page_format)
class RegisterGlyph(object):
def __init__(self, glyph):
self.glyph = glyph
#print 'Registered glyph:', self.glyph.name
self.proportion_ratio = self.getProportionRatio()
def getProportionRatio(self):
xMin, yMin, xMax, yMax = self.glyph.box
self.w = xMax - xMin
self.h = yMax - yMin
ratio = self.w/self.h
return ratio
def drawGlyphOnNewPage(self):
newPage()
print
self._drawGlyph()
def _drawGlyph(self):
pen = CocoaPen(self.glyph.getParent())
self.glyph.draw(pen)
drawPath(pen.path)
for g in my_selection:
if len(g) > 0: # Ignore whitespace glyphs
glyph = RegisterGlyph(g)
glyph.drawGlyphOnNewPage()
|
Set size nonce at the beginning of the script
|
Set size nonce at the beginning of the script
|
Python
|
mit
|
AlphabetType/DrawBot-Scripts
|
python
|
## Code Before:
from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
my_selection = CurrentFont() # May also be CurrentFont.selection or else
class RegisterGlyph(object):
def __init__(self, glyph):
self.glyph = glyph
print 'Registered glyph:', self.glyph.name
self.proportion_ratio = self.getProportionRatio()
def getProportionRatio(self):
xMin, yMin, xMax, yMax = self.glyph.box
self.w = xMax - xMin
self.h = yMax - yMin
ratio = self.w/self.h
return ratio
def drawGlyphOnNewPage(self):
newPage(page_format)
self._drawGlyph()
def _drawGlyph(self):
pen = CocoaPen(self.glyph.getParent())
self.glyph.draw(pen)
drawPath(pen.path)
for g in my_selection:
if len(g) > 0: # Ignore whitespace glyphs
glyph = RegisterGlyph(g)
glyph.drawGlyphOnNewPage()
## Instruction:
Set size nonce at the beginning of the script
## Code After:
from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
margins = (50,50,50,50) # left, top, right, bottom
my_selection = CurrentFont() # May also be CurrentFont.selection or else
# Init
size(page_format)
class RegisterGlyph(object):
def __init__(self, glyph):
self.glyph = glyph
#print 'Registered glyph:', self.glyph.name
self.proportion_ratio = self.getProportionRatio()
def getProportionRatio(self):
xMin, yMin, xMax, yMax = self.glyph.box
self.w = xMax - xMin
self.h = yMax - yMin
ratio = self.w/self.h
return ratio
def drawGlyphOnNewPage(self):
newPage()
print
self._drawGlyph()
def _drawGlyph(self):
pen = CocoaPen(self.glyph.getParent())
self.glyph.draw(pen)
drawPath(pen.path)
for g in my_selection:
if len(g) > 0: # Ignore whitespace glyphs
glyph = RegisterGlyph(g)
glyph.drawGlyphOnNewPage()
|
# ... existing code ...
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
margins = (50,50,50,50) # left, top, right, bottom
my_selection = CurrentFont() # May also be CurrentFont.selection or else
# Init
size(page_format)
class RegisterGlyph(object):
# ... modified code ...
def __init__(self, glyph):
self.glyph = glyph
#print 'Registered glyph:', self.glyph.name
self.proportion_ratio = self.getProportionRatio()
...
return ratio
def drawGlyphOnNewPage(self):
newPage()
print
self._drawGlyph()
def _drawGlyph(self):
# ... rest of the code ...
|
1ba5550b33dd504ae1816e06126e805f3d651f72
|
src/main/java/nl/myndocs/database/migrator/definition/Constraint.java
|
src/main/java/nl/myndocs/database/migrator/definition/Constraint.java
|
package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
|
package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE, FOREIGN_KEY
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
|
Prepare FOREIGN_KEY as ALTER TABLE
|
Prepare FOREIGN_KEY as ALTER TABLE
|
Java
|
mit
|
adhesivee/database-migrator
|
java
|
## Code Before:
package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
## Instruction:
Prepare FOREIGN_KEY as ALTER TABLE
## Code After:
package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE, FOREIGN_KEY
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
|
...
public class Constraint {
public enum TYPE {
INDEX, UNIQUE, FOREIGN_KEY
}
private String constraintName;
...
|
f548b304c556ad93e229344247c1ca5773257a6d
|
orienteer-core/src/main/java/org/orienteer/core/behavior/OneTimeAjaxClientInfoBehavior.java
|
orienteer-core/src/main/java/org/orienteer/core/behavior/OneTimeAjaxClientInfoBehavior.java
|
package org.orienteer.core.behavior;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxClientInfoBehavior;
import org.orienteer.core.OrienteerWebSession;
/**
* Behavior to gather ClientInfo only once
*/
public class OneTimeAjaxClientInfoBehavior extends AjaxClientInfoBehavior {
@Override
public boolean isEnabled(Component component) {
return !OrienteerWebSession.get().isClientInfoAvailable();
}
@Override
public boolean isTemporary(Component component) {
return !isEnabled(component);
}
}
|
package org.orienteer.core.behavior;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxClientInfoBehavior;
import org.orienteer.core.OrienteerWebSession;
/**
* Behavior to gather ClientInfo only once
*/
public class OneTimeAjaxClientInfoBehavior extends AjaxClientInfoBehavior {
@Override
public boolean isEnabled(Component component) {
return !OrienteerWebSession.get().isClientInfoAvailable();
}
}
|
Fix InvalidBehaviorIdException due to dynamic swith to temporal behavior
|
Fix InvalidBehaviorIdException due to dynamic swith to temporal behavior
|
Java
|
apache-2.0
|
OrienteerBAP/Orienteer,WeaxMe/Orienteer,WeaxMe/Orienteer,OrienteerBAP/Orienteer,OrienteerDW/Orienteer,OrienteerDW/Orienteer,OrienteerBAP/Orienteer,WeaxMe/Orienteer,OrienteerBAP/Orienteer,OrienteerDW/Orienteer
|
java
|
## Code Before:
package org.orienteer.core.behavior;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxClientInfoBehavior;
import org.orienteer.core.OrienteerWebSession;
/**
* Behavior to gather ClientInfo only once
*/
public class OneTimeAjaxClientInfoBehavior extends AjaxClientInfoBehavior {
@Override
public boolean isEnabled(Component component) {
return !OrienteerWebSession.get().isClientInfoAvailable();
}
@Override
public boolean isTemporary(Component component) {
return !isEnabled(component);
}
}
## Instruction:
Fix InvalidBehaviorIdException due to dynamic swith to temporal behavior
## Code After:
package org.orienteer.core.behavior;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxClientInfoBehavior;
import org.orienteer.core.OrienteerWebSession;
/**
* Behavior to gather ClientInfo only once
*/
public class OneTimeAjaxClientInfoBehavior extends AjaxClientInfoBehavior {
@Override
public boolean isEnabled(Component component) {
return !OrienteerWebSession.get().isClientInfoAvailable();
}
}
|
...
public boolean isEnabled(Component component) {
return !OrienteerWebSession.get().isClientInfoAvailable();
}
}
...
|
b5fa8ff1d86485c7f00ddecaef040ca66a817dfc
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
|
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib',
'chardet'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
|
Add Chardet as installation dependency
|
Add Chardet as installation dependency
|
Python
|
mit
|
xigt/freki,xigt/freki
|
python
|
## Code Before:
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
## Instruction:
Add Chardet as installation dependency
## Code After:
from distutils.core import setup
setup(
name='freki',
version='0.3.0-develop',
description='PDF-Extraction helper for RiPLEs pipeline.',
author='Michael Goodman, Ryan Georgi',
author_email='[email protected], [email protected]',
url='https://github.com/xigt/freki',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
'Topic :: Utilities'
],
keywords='nlp pdf ie text',
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib',
'chardet'
],
entry_points={
'console_scripts': [
'freki=freki.main:main'
]
},
)
|
...
packages=['freki', 'freki.readers', 'freki.analyzers'],
install_requires=[
'numpy',
'matplotlib',
'chardet'
],
entry_points={
'console_scripts': [
...
|
151e94d2d0208ac1984da105c6c7966b2a76c697
|
pymodels/TS_V04_01/__init__.py
|
pymodels/TS_V04_01/__init__.py
|
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapping
from .families import get_section_name_mapping
# -- default accelerator values for TS_V04_01--
lattice_version = accelerator_data['lattice_version']
|
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapping
from .families import get_section_name_mapping
from .control_system import get_control_system_data
# -- default accelerator values for TS_V04_01--
lattice_version = accelerator_data['lattice_version']
|
Add control system data to init.
|
TS.ENH: Add control system data to init.
|
Python
|
mit
|
lnls-fac/sirius
|
python
|
## Code Before:
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapping
from .families import get_section_name_mapping
# -- default accelerator values for TS_V04_01--
lattice_version = accelerator_data['lattice_version']
## Instruction:
TS.ENH: Add control system data to init.
## Code After:
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapping
from .families import get_section_name_mapping
from .control_system import get_control_system_data
# -- default accelerator values for TS_V04_01--
lattice_version = accelerator_data['lattice_version']
|
// ... existing code ...
from .families import family_mapping
from .families import get_section_name_mapping
from .control_system import get_control_system_data
# -- default accelerator values for TS_V04_01--
lattice_version = accelerator_data['lattice_version']
// ... rest of the code ...
|
2fff4600d701d6f5ac9675d96916ca74cf3cfdbd
|
riker/worker/apps.py
|
riker/worker/apps.py
|
from __future__ import unicode_literals
from django.apps import AppConfig
from worker.utils import LircListener
class WorkerConfig(AppConfig):
name = 'worker'
def ready(self):
lirc_name = getattr(settings, 'RIKER_LIRC_LISTENER_NAME', 'riker')
LircListener(lirc_name=lirc_name).start()
|
from __future__ import unicode_literals
from django.apps import AppConfig
from worker.utils import LircListener
class WorkerConfig(AppConfig):
name = 'worker'
|
Remove prematurely inserted 'ready' method
|
Remove prematurely inserted 'ready' method
|
Python
|
mit
|
haikuginger/riker
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.apps import AppConfig
from worker.utils import LircListener
class WorkerConfig(AppConfig):
name = 'worker'
def ready(self):
lirc_name = getattr(settings, 'RIKER_LIRC_LISTENER_NAME', 'riker')
LircListener(lirc_name=lirc_name).start()
## Instruction:
Remove prematurely inserted 'ready' method
## Code After:
from __future__ import unicode_literals
from django.apps import AppConfig
from worker.utils import LircListener
class WorkerConfig(AppConfig):
name = 'worker'
|
# ... existing code ...
class WorkerConfig(AppConfig):
name = 'worker'
# ... rest of the code ...
|
ea3660bcc1a9f7be619def8e26dd7b0ab4a873cf
|
estmator_project/est_client/forms.py
|
estmator_project/est_client/forms.py
|
from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
'email'
]
widgets = {
'company': Select(attrs={'required': True}),
}
class CompanyCreateForm(ModelForm):
class Meta:
model = Company
fields = [
'company_name',
'phone',
'address',
'address2',
'city',
'state',
'postal',
'st_rate',
'ot_rate'
]
widgets = {
'company_name': TextInput(attrs={'required': True}),
}
class CompanyListForm(ModelForm):
class Meta:
model = Client
fields = ['company']
|
from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
'email'
]
widgets = {
'company': Select(attrs={'required': True}),
'first_name': TextInput(attrs={'required': True}),
'last_name': TextInput(attrs={'required': True}),
'title': TextInput(attrs={'required': True}),
'cell': TextInput(attrs={'required': True}),
'email': TextInput(attrs={'required': True}),
}
class CompanyCreateForm(ModelForm):
class Meta:
model = Company
fields = [
'company_name',
'phone',
'address',
'address2',
'city',
'state',
'postal',
'st_rate',
'ot_rate'
]
widgets = {
'company_name': TextInput(attrs={'required': True}),
'phone': TextInput(attrs={'required': True}),
'address': TextInput(attrs={'required': True}),
'city': TextInput(attrs={'required': True}),
'postal': TextInput(attrs={'required': True}),
}
class CompanyListForm(ModelForm):
class Meta:
model = Client
fields = ['company']
|
Make fields required on new client and company
|
Make fields required on new client and company
|
Python
|
mit
|
Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp
|
python
|
## Code Before:
from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
'email'
]
widgets = {
'company': Select(attrs={'required': True}),
}
class CompanyCreateForm(ModelForm):
class Meta:
model = Company
fields = [
'company_name',
'phone',
'address',
'address2',
'city',
'state',
'postal',
'st_rate',
'ot_rate'
]
widgets = {
'company_name': TextInput(attrs={'required': True}),
}
class CompanyListForm(ModelForm):
class Meta:
model = Client
fields = ['company']
## Instruction:
Make fields required on new client and company
## Code After:
from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
'email'
]
widgets = {
'company': Select(attrs={'required': True}),
'first_name': TextInput(attrs={'required': True}),
'last_name': TextInput(attrs={'required': True}),
'title': TextInput(attrs={'required': True}),
'cell': TextInput(attrs={'required': True}),
'email': TextInput(attrs={'required': True}),
}
class CompanyCreateForm(ModelForm):
class Meta:
model = Company
fields = [
'company_name',
'phone',
'address',
'address2',
'city',
'state',
'postal',
'st_rate',
'ot_rate'
]
widgets = {
'company_name': TextInput(attrs={'required': True}),
'phone': TextInput(attrs={'required': True}),
'address': TextInput(attrs={'required': True}),
'city': TextInput(attrs={'required': True}),
'postal': TextInput(attrs={'required': True}),
}
class CompanyListForm(ModelForm):
class Meta:
model = Client
fields = ['company']
|
// ... existing code ...
]
widgets = {
'company': Select(attrs={'required': True}),
'first_name': TextInput(attrs={'required': True}),
'last_name': TextInput(attrs={'required': True}),
'title': TextInput(attrs={'required': True}),
'cell': TextInput(attrs={'required': True}),
'email': TextInput(attrs={'required': True}),
}
// ... modified code ...
]
widgets = {
'company_name': TextInput(attrs={'required': True}),
'phone': TextInput(attrs={'required': True}),
'address': TextInput(attrs={'required': True}),
'city': TextInput(attrs={'required': True}),
'postal': TextInput(attrs={'required': True}),
}
// ... rest of the code ...
|
b470cb1825f5d54ff4a48875a216dbb0cdf44eb7
|
apps/innovate/tests/test_views.py
|
apps/innovate/tests/test_views.py
|
from django.core.urlresolvers import reverse
from django.test import Client
from projects.models import Project
from innovate import urls
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
|
from django.core.urlresolvers import reverse
from django.test import Client
from django.test.client import RequestFactory
from projects.models import Project
from innovate import urls
from innovate.views import handle404, handle500
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
def test_404_handler():
"""Test that the 404 error handler renders and gives the correct code."""
response = handle404(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 404
def test_500_handler():
"""Test that the 500 error handler renders and gives the correct code."""
response = handle500(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 500
|
Add tests for the 404 and 500 error handlers.
|
Add tests for the 404 and 500 error handlers.
|
Python
|
bsd-3-clause
|
mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm
|
python
|
## Code Before:
from django.core.urlresolvers import reverse
from django.test import Client
from projects.models import Project
from innovate import urls
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
## Instruction:
Add tests for the 404 and 500 error handlers.
## Code After:
from django.core.urlresolvers import reverse
from django.test import Client
from django.test.client import RequestFactory
from projects.models import Project
from innovate import urls
from innovate.views import handle404, handle500
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
def test_404_handler():
"""Test that the 404 error handler renders and gives the correct code."""
response = handle404(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 404
def test_500_handler():
"""Test that the 500 error handler renders and gives the correct code."""
response = handle500(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 500
|
// ... existing code ...
from django.core.urlresolvers import reverse
from django.test import Client
from django.test.client import RequestFactory
from projects.models import Project
from innovate import urls
from innovate.views import handle404, handle500
def test_routes():
// ... modified code ...
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
def test_404_handler():
"""Test that the 404 error handler renders and gives the correct code."""
response = handle404(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 404
def test_500_handler():
"""Test that the 500 error handler renders and gives the correct code."""
response = handle500(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 500
// ... rest of the code ...
|
360efe51bc45f189c235bed6b2b7bfdd4fd1bfbd
|
flask-restful/api.py
|
flask-restful/api.py
|
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(self):
args = parser.parse_args()
txt = args['txt']
rp = reach.process_text(txt, offline=False)
st = rp.statements
json_statements = {}
json_statements['statements'] = []
for s in st:
s_json = s.to_json()
json_statements['statements'].append(s_json)
json_statements = json.dumps(json_statements)
return json_statements, 201
api.add_resource(InputText, '/parse')
class InputStmtJSON(Resource):
def post(self):
args = parser.parse_args()
print(args)
json_data = args['json']
json_dict = json.loads(json_data)
st = []
for j in json_dict['statements']:
s = Statement.from_json(j)
print(s)
st.append(s)
return 201
api.add_resource(InputStmtJSON, '/load')
if __name__ == '__main__':
app.run(debug=True)
|
import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
|
Reimplement using bottle and add 3 endpoints
|
Reimplement using bottle and add 3 endpoints
|
Python
|
bsd-2-clause
|
sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra
|
python
|
## Code Before:
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(self):
args = parser.parse_args()
txt = args['txt']
rp = reach.process_text(txt, offline=False)
st = rp.statements
json_statements = {}
json_statements['statements'] = []
for s in st:
s_json = s.to_json()
json_statements['statements'].append(s_json)
json_statements = json.dumps(json_statements)
return json_statements, 201
api.add_resource(InputText, '/parse')
class InputStmtJSON(Resource):
def post(self):
args = parser.parse_args()
print(args)
json_data = args['json']
json_dict = json.loads(json_data)
st = []
for j in json_dict['statements']:
s = Statement.from_json(j)
print(s)
st.append(s)
return 201
api.add_resource(InputStmtJSON, '/load')
if __name__ == '__main__':
app.run(debug=True)
## Instruction:
Reimplement using bottle and add 3 endpoints
## Code After:
import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
|
# ... existing code ...
import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
# ... rest of the code ...
|
440305707dfbf9a7a321b48250245edafc42aa73
|
candidates/csv_helpers.py
|
candidates/csv_helpers.py
|
from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1])
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
|
from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
)
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
|
Sort on first name after last name
|
Sort on first name after last name
|
Python
|
agpl-3.0
|
mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative
|
python
|
## Code Before:
from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1])
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
## Instruction:
Sort on first name after last name
## Code After:
from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
)
def _candidate_sort_by_post_key(row):
return (
not row['election_current'],
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
)
def list_to_csv(candidates_list, group_by_post=False):
from .election_specific import EXTRA_CSV_ROW_FIELDS
csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
writer.writeheader()
if group_by_post:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key)
else:
sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key)
for row in sorted_rows:
writer.writerow(row)
return writer.output
|
# ... existing code ...
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['election'],
# ... modified code ...
row['election_date'],
row['election'],
row['post_label'],
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
)
def list_to_csv(candidates_list, group_by_post=False):
# ... rest of the code ...
|
c32eb5f0a09f0a43172ed257ce21ab9545b6e03e
|
lazy_helpers.py
|
lazy_helpers.py
|
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
from selenium import webdriver
# Configure headless mode
chrome_options = webdriver.ChromeOptions() #Oops
chrome_options.add_argument('--verbose')
chrome_options.add_argument('--ignore-certificate-errors')
log_path = "/tmp/chromelogpanda{0}".format(os.getpid())
if not os.path.exists(log_path):
os.mkdir(log_path)
chrome_options.add_argument("--log-path {0}/log.txt".format(log_path))
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-setuid-sandbox")
cls._driver = webdriver.Chrome(chrome_options=chrome_options)
return cls._driver
class LazyPool(object):
_pool = None
@classmethod
def get(cls):
if cls._pool is None:
import urllib3
cls._pool = urllib3.PoolManager()
return cls._pool
|
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
cls._display = display
display = Display(visible=0, size=(1024, 768))
display.start()
from selenium import webdriver
# Configure headless mode
chrome_options = webdriver.ChromeOptions() #Oops
chrome_options.add_argument('--verbose')
chrome_options.add_argument('--ignore-certificate-errors')
log_path = "/tmp/chromelogpanda{0}".format(os.getpid())
if not os.path.exists(log_path):
os.mkdir(log_path)
chrome_options.add_argument("--log-path {0}/log.txt".format(log_path))
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-setuid-sandbox")
cls._driver = webdriver.Chrome(chrome_options=chrome_options)
return cls._driver
@classmethod
def reset(cls):
cls._display.stop()
cls._driver.Dispose()
class LazyPool(object):
_pool = None
@classmethod
def get(cls):
if cls._pool is None:
import urllib3
cls._pool = urllib3.PoolManager()
return cls._pool
|
Update lazy helper to support the idea of a reset on bad state.
|
Update lazy helper to support the idea of a reset on bad state.
|
Python
|
apache-2.0
|
holdenk/diversity-analytics,holdenk/diversity-analytics
|
python
|
## Code Before:
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
from selenium import webdriver
# Configure headless mode
chrome_options = webdriver.ChromeOptions() #Oops
chrome_options.add_argument('--verbose')
chrome_options.add_argument('--ignore-certificate-errors')
log_path = "/tmp/chromelogpanda{0}".format(os.getpid())
if not os.path.exists(log_path):
os.mkdir(log_path)
chrome_options.add_argument("--log-path {0}/log.txt".format(log_path))
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-setuid-sandbox")
cls._driver = webdriver.Chrome(chrome_options=chrome_options)
return cls._driver
class LazyPool(object):
_pool = None
@classmethod
def get(cls):
if cls._pool is None:
import urllib3
cls._pool = urllib3.PoolManager()
return cls._pool
## Instruction:
Update lazy helper to support the idea of a reset on bad state.
## Code After:
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
cls._display = display
display = Display(visible=0, size=(1024, 768))
display.start()
from selenium import webdriver
# Configure headless mode
chrome_options = webdriver.ChromeOptions() #Oops
chrome_options.add_argument('--verbose')
chrome_options.add_argument('--ignore-certificate-errors')
log_path = "/tmp/chromelogpanda{0}".format(os.getpid())
if not os.path.exists(log_path):
os.mkdir(log_path)
chrome_options.add_argument("--log-path {0}/log.txt".format(log_path))
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-setuid-sandbox")
cls._driver = webdriver.Chrome(chrome_options=chrome_options)
return cls._driver
@classmethod
def reset(cls):
cls._display.stop()
cls._driver.Dispose()
class LazyPool(object):
_pool = None
@classmethod
def get(cls):
if cls._pool is None:
import urllib3
cls._pool = urllib3.PoolManager()
return cls._pool
|
...
import os
if cls._driver is None:
from pyvirtualdisplay import Display
cls._display = display
display = Display(visible=0, size=(1024, 768))
display.start()
from selenium import webdriver
# Configure headless mode
...
cls._driver = webdriver.Chrome(chrome_options=chrome_options)
return cls._driver
@classmethod
def reset(cls):
cls._display.stop()
cls._driver.Dispose()
class LazyPool(object):
_pool = None
...
|
4e4390db6ed35de4fb7ad42579be5180a95bb96f
|
src/settings.py
|
src/settings.py
|
import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music")
# Tells flask to serve the mp3 files
# Typically you'd want nginx to do this instead, as this is an
# easy way to cause concurrent response issues with flask
SERVE_FILES = True
# acceptable standard html5 compatible formats
FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$")
# number of directories upwards to limit recursive check for cover image
COVER_IMG_RECURSION_LIMIT = 1
|
import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/")
# Tells flask to serve the mp3 files
# Typically you'd want nginx to do this instead, as this is an
# easy way to cause concurrent response issues with flask
SERVE_FILES = True
# acceptable standard html5 compatible formats
FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$")
# number of directories upwards to limit recursive check for cover image
COVER_IMG_RECURSION_LIMIT = 1
|
Allow for case-insensitive checking of file formats. Support m4a
|
Allow for case-insensitive checking of file formats. Support m4a
|
Python
|
apache-2.0
|
nhydock/ftmp3,lunared/ftmp3,nhydock/ftmp3,lunared/ftmp3,lunared/ftmp3
|
python
|
## Code Before:
import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music")
# Tells flask to serve the mp3 files
# Typically you'd want nginx to do this instead, as this is an
# easy way to cause concurrent response issues with flask
SERVE_FILES = True
# acceptable standard html5 compatible formats
FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$")
# number of directories upwards to limit recursive check for cover image
COVER_IMG_RECURSION_LIMIT = 1
## Instruction:
Allow for case-insensitive checking of file formats. Support m4a
## Code After:
import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/")
# Tells flask to serve the mp3 files
# Typically you'd want nginx to do this instead, as this is an
# easy way to cause concurrent response issues with flask
SERVE_FILES = True
# acceptable standard html5 compatible formats
FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$")
# number of directories upwards to limit recursive check for cover image
COVER_IMG_RECURSION_LIMIT = 1
|
# ... existing code ...
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/")
# Tells flask to serve the mp3 files
# Typically you'd want nginx to do this instead, as this is an
# easy way to cause concurrent response issues with flask
SERVE_FILES = True
# acceptable standard html5 compatible formats
FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$")
# number of directories upwards to limit recursive check for cover image
COVER_IMG_RECURSION_LIMIT = 1
# ... rest of the code ...
|
01c6e7f3c04646b9b038088214eeb2c3b470e1ef
|
src/com/ingotpowered/api/world/World.java
|
src/com/ingotpowered/api/world/World.java
|
package com.ingotpowered.api.world;
public interface World {
public Chunk getChunkAt(ChunkPosition position);
public Chunk getChunkAt(int x, int z);
}
|
package com.ingotpowered.api.world;
import com.ingotpowered.api.definitions.Difficulty;
import com.ingotpowered.api.definitions.Dimension;
import com.ingotpowered.api.definitions.LevelType;
public interface World {
public LevelType getType();
public Dimension getDimension();
public Difficulty getDifficulty();
public void setDifficulty(Difficulty difficulty);
public Chunk getChunkAt(ChunkPosition position);
public Chunk getChunkAt(int x, int z);
}
|
Add type, dimension, and difficulty definitions to world
|
Add type, dimension, and difficulty definitions to world
|
Java
|
mit
|
IngotPowered/IngotAPI
|
java
|
## Code Before:
package com.ingotpowered.api.world;
public interface World {
public Chunk getChunkAt(ChunkPosition position);
public Chunk getChunkAt(int x, int z);
}
## Instruction:
Add type, dimension, and difficulty definitions to world
## Code After:
package com.ingotpowered.api.world;
import com.ingotpowered.api.definitions.Difficulty;
import com.ingotpowered.api.definitions.Dimension;
import com.ingotpowered.api.definitions.LevelType;
public interface World {
public LevelType getType();
public Dimension getDimension();
public Difficulty getDifficulty();
public void setDifficulty(Difficulty difficulty);
public Chunk getChunkAt(ChunkPosition position);
public Chunk getChunkAt(int x, int z);
}
|
// ... existing code ...
package com.ingotpowered.api.world;
import com.ingotpowered.api.definitions.Difficulty;
import com.ingotpowered.api.definitions.Dimension;
import com.ingotpowered.api.definitions.LevelType;
public interface World {
public LevelType getType();
public Dimension getDimension();
public Difficulty getDifficulty();
public void setDifficulty(Difficulty difficulty);
public Chunk getChunkAt(ChunkPosition position);
// ... rest of the code ...
|
8b3c438b3f5fb9b2538a30182dd4f5d306aa098b
|
ankieta/contact/forms.py
|
ankieta/contact/forms.py
|
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
|
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
Fix contact form - send to recipient, not managers
|
Fix contact form - send to recipient, not managers
|
Python
|
bsd-3-clause
|
watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl
|
python
|
## Code Before:
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
## Instruction:
Fix contact form - send to recipient, not managers
## Code After:
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
...
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
...
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
...
|
e1b62a5d39fd3a4adb7d783c131fd122ba09c3d5
|
support/biicode-build.py
|
support/biicode-build.py
|
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None, install_dir='.')
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
|
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None)
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
|
Install CMake in system dirs
|
Install CMake in system dirs
|
Python
|
bsd-2-clause
|
blaquee/cppformat,mojoBrendan/fmt,cppformat/cppformat,mojoBrendan/fmt,seungrye/cppformat,lightslife/cppformat,nelson4722/cppformat,alabuzhev/fmt,alabuzhev/fmt,lightslife/cppformat,lightslife/cppformat,cppformat/cppformat,alabuzhev/fmt,cppformat/cppformat,Jopie64/cppformat,blaquee/cppformat,mojoBrendan/fmt,dean0x7d/cppformat,seungrye/cppformat,nelson4722/cppformat,wangshijin/cppformat,dean0x7d/cppformat,nelson4722/cppformat,Jopie64/cppformat,blaquee/cppformat,wangshijin/cppformat,dean0x7d/cppformat,Jopie64/cppformat,seungrye/cppformat,wangshijin/cppformat
|
python
|
## Code Before:
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None, install_dir='.')
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
## Instruction:
Install CMake in system dirs
## Code After:
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None)
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
with Downloader().download('http://www.biicode.com/downloads/latest/macos') as f:
check_call(['sudo', 'installer', '-pkg', f, '-target', '/'])
project_dir = 'biicode_project'
check_call(['bii', 'init', project_dir])
cppformat_dir = os.path.join(project_dir, 'blocks/vitaut/cppformat')
shutil.copytree('.', cppformat_dir,
ignore=shutil.ignore_patterns('biicode_project'))
for f in glob.glob('support/biicode/*'):
shutil.copy(f, cppformat_dir)
check_call(['bii', 'cpp:build'], cwd=project_dir)
|
...
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz', check_installed=False, download_dir=None)
with Downloader().download('http://www.biicode.com/downloads/latest/ubuntu64') as f:
check_call(['sudo', 'dpkg', '-i', f])
elif os_name == 'osx':
...
|
a692c65ed369e9ad92b164c9beb900abda442933
|
src/main/java/org/cyclops/integrateddynamics/core/evaluate/variable/ValueTypeListProxyEntityArmorInventory.java
|
src/main/java/org/cyclops/integrateddynamics/core/evaluate/variable/ValueTypeListProxyEntityArmorInventory.java
|
package org.cyclops.integrateddynamics.core.evaluate.variable;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.cyclops.cyclopscore.persist.nbt.INBTProvider;
/**
* A list proxy for the inventory of an entity.
*/
public class ValueTypeListProxyEntityArmorInventory extends ValueTypeListProxyEntityBase<ValueObjectTypeItemStack, ValueObjectTypeItemStack.ValueItemStack> implements INBTProvider {
public ValueTypeListProxyEntityArmorInventory() {
this(null, null);
}
public ValueTypeListProxyEntityArmorInventory(World world, Entity entity) {
super(ValueTypeListProxyFactories.ENTITY_ARMORINVENTORY.getName(), ValueTypes.OBJECT_ITEMSTACK, world, entity);
}
protected ItemStack[] getInventory() {
Entity e = getEntity();
if(e != null) {
return e.getInventory();
}
return new ItemStack[0];
}
@Override
public int getLength() {
return getInventory().length;
}
@Override
public ValueObjectTypeItemStack.ValueItemStack get(int index) {
return ValueObjectTypeItemStack.ValueItemStack.of(getInventory()[index]);
}
@Override
public void writeGeneratedFieldsToNBT(NBTTagCompound tag) {
}
@Override
public void readGeneratedFieldsFromNBT(NBTTagCompound tag) {
}
}
|
package org.cyclops.integrateddynamics.core.evaluate.variable;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.cyclops.cyclopscore.persist.nbt.INBTProvider;
/**
* A list proxy for the inventory of an entity.
*/
public class ValueTypeListProxyEntityArmorInventory extends ValueTypeListProxyEntityBase<ValueObjectTypeItemStack, ValueObjectTypeItemStack.ValueItemStack> implements INBTProvider {
public ValueTypeListProxyEntityArmorInventory() {
this(null, null);
}
public ValueTypeListProxyEntityArmorInventory(World world, Entity entity) {
super(ValueTypeListProxyFactories.ENTITY_ARMORINVENTORY.getName(), ValueTypes.OBJECT_ITEMSTACK, world, entity);
}
protected ItemStack[] getInventory() {
Entity e = getEntity();
if(e != null) {
ItemStack[] inventory = e.getInventory();
if(inventory != null) {
return inventory;
}
}
return new ItemStack[0];
}
@Override
public int getLength() {
return getInventory().length;
}
@Override
public ValueObjectTypeItemStack.ValueItemStack get(int index) {
return ValueObjectTypeItemStack.ValueItemStack.of(getInventory()[index]);
}
@Override
public void writeGeneratedFieldsToNBT(NBTTagCompound tag) {
}
@Override
public void readGeneratedFieldsFromNBT(NBTTagCompound tag) {
}
}
|
Fix NPE when reading mob armor inventories in peaceful mode
|
Fix NPE when reading mob armor inventories in peaceful mode
|
Java
|
mit
|
CyclopsMC/IntegratedDynamics
|
java
|
## Code Before:
package org.cyclops.integrateddynamics.core.evaluate.variable;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.cyclops.cyclopscore.persist.nbt.INBTProvider;
/**
* A list proxy for the inventory of an entity.
*/
public class ValueTypeListProxyEntityArmorInventory extends ValueTypeListProxyEntityBase<ValueObjectTypeItemStack, ValueObjectTypeItemStack.ValueItemStack> implements INBTProvider {
public ValueTypeListProxyEntityArmorInventory() {
this(null, null);
}
public ValueTypeListProxyEntityArmorInventory(World world, Entity entity) {
super(ValueTypeListProxyFactories.ENTITY_ARMORINVENTORY.getName(), ValueTypes.OBJECT_ITEMSTACK, world, entity);
}
protected ItemStack[] getInventory() {
Entity e = getEntity();
if(e != null) {
return e.getInventory();
}
return new ItemStack[0];
}
@Override
public int getLength() {
return getInventory().length;
}
@Override
public ValueObjectTypeItemStack.ValueItemStack get(int index) {
return ValueObjectTypeItemStack.ValueItemStack.of(getInventory()[index]);
}
@Override
public void writeGeneratedFieldsToNBT(NBTTagCompound tag) {
}
@Override
public void readGeneratedFieldsFromNBT(NBTTagCompound tag) {
}
}
## Instruction:
Fix NPE when reading mob armor inventories in peaceful mode
## Code After:
package org.cyclops.integrateddynamics.core.evaluate.variable;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.cyclops.cyclopscore.persist.nbt.INBTProvider;
/**
* A list proxy for the inventory of an entity.
*/
public class ValueTypeListProxyEntityArmorInventory extends ValueTypeListProxyEntityBase<ValueObjectTypeItemStack, ValueObjectTypeItemStack.ValueItemStack> implements INBTProvider {
public ValueTypeListProxyEntityArmorInventory() {
this(null, null);
}
public ValueTypeListProxyEntityArmorInventory(World world, Entity entity) {
super(ValueTypeListProxyFactories.ENTITY_ARMORINVENTORY.getName(), ValueTypes.OBJECT_ITEMSTACK, world, entity);
}
protected ItemStack[] getInventory() {
Entity e = getEntity();
if(e != null) {
ItemStack[] inventory = e.getInventory();
if(inventory != null) {
return inventory;
}
}
return new ItemStack[0];
}
@Override
public int getLength() {
return getInventory().length;
}
@Override
public ValueObjectTypeItemStack.ValueItemStack get(int index) {
return ValueObjectTypeItemStack.ValueItemStack.of(getInventory()[index]);
}
@Override
public void writeGeneratedFieldsToNBT(NBTTagCompound tag) {
}
@Override
public void readGeneratedFieldsFromNBT(NBTTagCompound tag) {
}
}
|
...
protected ItemStack[] getInventory() {
Entity e = getEntity();
if(e != null) {
ItemStack[] inventory = e.getInventory();
if(inventory != null) {
return inventory;
}
}
return new ItemStack[0];
}
...
|
85db14b8584995da667c92cda6a44e2b3395250e
|
greenlight/views/__init__.py
|
greenlight/views/__init__.py
|
from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.services())
class RequestsView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.requests())
def post(self, request):
open311_response = QC_three.post(**request.POST)[0]
if open311_response.get('code') == 'BadRequest':
return self.ErrorAPIResponse(open311_response)
request_id = open311_response['service_request_id']
location = reverse('request', args = (request_id,))
response = self.OkAPIResponse({
'id': request_id,
'location': location
})
response['Location'] = location
return response
class RequestView(APIView):
def get(self, request, id):
requests = QC_three.request(id)
if requests:
return self.OkAPIResponse(requests[0])
else:
raise Http404
|
from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.services())
class RequestsView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.requests())
def post(self, request):
open311_response = QC_three.post(**request.POST)[0]
if open311_response.get('code') == 'BadRequest':
return self.ErrorAPIResponse((open311_response['code'], open311_response['description']))
request_id = open311_response['service_request_id']
location = reverse('request', args = (request_id,))
response = self.OkAPIResponse({
'id': request_id,
'location': location
})
response['Location'] = location
return response
class RequestView(APIView):
def get(self, request, id):
requests = QC_three.request(id)
if requests:
return self.OkAPIResponse(requests[0])
else:
raise Http404
|
Fix a bug when the open311 API returns an error.
|
Fix a bug when the open311 API returns an error.
|
Python
|
mit
|
ironweb/lesfeuxverts-backend
|
python
|
## Code Before:
from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.services())
class RequestsView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.requests())
def post(self, request):
open311_response = QC_three.post(**request.POST)[0]
if open311_response.get('code') == 'BadRequest':
return self.ErrorAPIResponse(open311_response)
request_id = open311_response['service_request_id']
location = reverse('request', args = (request_id,))
response = self.OkAPIResponse({
'id': request_id,
'location': location
})
response['Location'] = location
return response
class RequestView(APIView):
def get(self, request, id):
requests = QC_three.request(id)
if requests:
return self.OkAPIResponse(requests[0])
else:
raise Http404
## Instruction:
Fix a bug when the open311 API returns an error.
## Code After:
from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.services())
class RequestsView(APIView):
def get(self, request):
return self.OkAPIResponse(QC_three.requests())
def post(self, request):
open311_response = QC_three.post(**request.POST)[0]
if open311_response.get('code') == 'BadRequest':
return self.ErrorAPIResponse((open311_response['code'], open311_response['description']))
request_id = open311_response['service_request_id']
location = reverse('request', args = (request_id,))
response = self.OkAPIResponse({
'id': request_id,
'location': location
})
response['Location'] = location
return response
class RequestView(APIView):
def get(self, request, id):
requests = QC_three.request(id)
if requests:
return self.OkAPIResponse(requests[0])
else:
raise Http404
|
...
open311_response = QC_three.post(**request.POST)[0]
if open311_response.get('code') == 'BadRequest':
return self.ErrorAPIResponse((open311_response['code'], open311_response['description']))
request_id = open311_response['service_request_id']
...
|
de5076e6991aeb1a4463d9398a5718fbe3209507
|
library/src/main/java/it/sephiroth/android/library/tooltip/TooltipBackgroundDrawable.java
|
library/src/main/java/it/sephiroth/android/library/tooltip/TooltipBackgroundDrawable.java
|
package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
|
package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
canvas.save();
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
canvas.restore();
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
|
Fix canvas not restored properly
|
Fix canvas not restored properly
|
Java
|
apache-2.0
|
freeletics/android-target-tooltip
|
java
|
## Code Before:
package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
## Instruction:
Fix canvas not restored properly
## Code After:
package it.sephiroth.android.library.tooltip;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.List;
public class TooltipBackgroundDrawable extends Drawable {
private int mBackgroundColor;
private List<View> mHighlightViews;
private Drawable mHighlightDrawable;
public TooltipBackgroundDrawable(Context context, TooltipManager.Builder builder) {
mBackgroundColor = context.getResources().getColor(builder.backgroundColorResId);
mHighlightViews = builder.highlightViews;
if (builder.highlightDrawableResId > 0) {
mHighlightDrawable = context.getResources().getDrawable(builder.highlightDrawableResId);
}
}
@Override
public void draw(Canvas canvas) {
canvas.save();
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
for(View v: mHighlightViews) {
v.getGlobalVisibleRect(vRect);
highlightRect.union(vRect);
}
if (mHighlightDrawable != null) {
mHighlightDrawable.setBounds(highlightRect);
mHighlightDrawable.draw(canvas);
}
canvas.clipRect(highlightRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mBackgroundColor);
canvas.restore();
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
}
|
// ... existing code ...
@Override
public void draw(Canvas canvas) {
canvas.save();
if (mHighlightViews != null) {
Rect highlightRect = new Rect();
Rect vRect = new Rect();
// ... modified code ...
}
canvas.drawColor(mBackgroundColor);
canvas.restore();
}
@Override
// ... rest of the code ...
|
6db8a9e779031ae97977a49e4edd11d42fb6389d
|
samples/04_markdown_parse/epub2markdown.py
|
samples/04_markdown_parse/epub2markdown.py
|
import sys
import subprocess
import os
import os.path
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0]+'.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '%s/%s' % (base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print '>> ', file_name
# write content to file
f = open('%s/%s' % (base_name, file_name), 'w')
f.write(content)
f.close()
|
import os.path
import subprocess
import sys
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0] + '.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print('>> {0}'.format(file_name))
# write content to file
with open('{0}/{1}'.format(base_name, file_name), 'w') as f:
f.write(content)
|
Make `samples/04_markdown_parse` Python 2+3 compatible
|
Make `samples/04_markdown_parse` Python 2+3 compatible
|
Python
|
agpl-3.0
|
booktype/ebooklib,aerkalov/ebooklib
|
python
|
## Code Before:
import sys
import subprocess
import os
import os.path
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0]+'.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '%s/%s' % (base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print '>> ', file_name
# write content to file
f = open('%s/%s' % (base_name, file_name), 'w')
f.write(content)
f.close()
## Instruction:
Make `samples/04_markdown_parse` Python 2+3 compatible
## Code After:
import os.path
import subprocess
import sys
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0] + '.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print('>> {0}'.format(file_name))
# write content to file
with open('{0}/{1}'.format(base_name, file_name), 'w') as f:
f.write(content)
|
// ... existing code ...
import os.path
import subprocess
import sys
from ebooklib import epub
// ... modified code ...
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0] + '.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print('>> {0}'.format(file_name))
# write content to file
with open('{0}/{1}'.format(base_name, file_name), 'w') as f:
f.write(content)
// ... rest of the code ...
|
9c35a41c6594d0ac482a558abf4772150c2a67e9
|
squash/dashboard/urls.py
|
squash/dashboard/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
|
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
=======
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet)
api_router.register(r'metrics', views.MetricViewSet)
api_router.register(r'packages', views.PackageViewSet)
>>>>>>> b962845... Make all API resource collection endpoints plural
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
|
Make all API resource collection endpoints plural
|
Make all API resource collection endpoints plural
/api/job/ -> /api/jobs/
/api/metric/ -> /api/metrics/
It's a standard convention in RESTful APIs to make endpoints for
collections plural.
|
Python
|
mit
|
lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard
|
python
|
## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
## Instruction:
Make all API resource collection endpoints plural
/api/job/ -> /api/jobs/
/api/metric/ -> /api/metrics/
It's a standard convention in RESTful APIs to make endpoints for
collections plural.
## Code After:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
=======
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet)
api_router.register(r'metrics', views.MetricViewSet)
api_router.register(r'packages', views.PackageViewSet)
>>>>>>> b962845... Make all API resource collection endpoints plural
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
|
# ... existing code ...
from rest_framework.routers import DefaultRouter
from . import views
<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
=======
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet)
api_router.register(r'metrics', views.MetricViewSet)
api_router.register(r'packages', views.PackageViewSet)
>>>>>>> b962845... Make all API resource collection endpoints plural
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# ... rest of the code ...
|
98c207ea262e500ea4f5c338a9bb5642047b24b7
|
alexandria/session.py
|
alexandria/session.py
|
from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000
)
config.set_session_factory(_session_factory)
|
from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000,
timeout=864000,
reissue_time=1200,
)
config.set_session_factory(_session_factory)
|
Change the timeout, and reissue_time
|
Change the timeout, and reissue_time
We want to make sure that the session never expires, since this also
causes our CSRF token to expire, which causes issues...
|
Python
|
isc
|
cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria
|
python
|
## Code Before:
from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000
)
config.set_session_factory(_session_factory)
## Instruction:
Change the timeout, and reissue_time
We want to make sure that the session never expires, since this also
causes our CSRF token to expire, which causes issues...
## Code After:
from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000,
timeout=864000,
reissue_time=1200,
)
config.set_session_factory(_session_factory)
|
...
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000,
timeout=864000,
reissue_time=1200,
)
config.set_session_factory(_session_factory)
...
|
64dacd10a2cf0bf7673878aba79ac079d646b004
|
plugins/ClojureEditor/src/org/micromanager/clojureeditor/ClojureEditorPlugin.java
|
plugins/ClojureEditor/src/org/micromanager/clojureeditor/ClojureEditorPlugin.java
|
/*
* Arthur Edelstein, UCSF, 2011
*/
package org.micromanager.clojureeditor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class ClojureEditorPlugin implements MMPlugin {
public static String menuName = "Clojure editor";
public void dispose() {
// do nothing
}
public void setApp(ScriptInterface app) {
// do nothing.
}
public void show() {
clooj.core.show();
}
public void configurationChanged() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getDescription() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getInfo() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getCopyright() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
/*
* Arthur Edelstein, UCSF, 2011
*/
package org.micromanager.clojureeditor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class ClojureEditorPlugin implements MMPlugin {
public static String menuName = "Clojure editor";
public void dispose() {
// do nothing
}
public void setApp(ScriptInterface app) {
// do nothing.
}
public void show() {
// this line does not compile:
//clooj.core.show();
}
public void configurationChanged() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getDescription() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getInfo() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getCopyright() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
Remove line that does not compile
|
Remove line that does not compile
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@7511 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
|
Java
|
mit
|
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
|
java
|
## Code Before:
/*
* Arthur Edelstein, UCSF, 2011
*/
package org.micromanager.clojureeditor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class ClojureEditorPlugin implements MMPlugin {
public static String menuName = "Clojure editor";
public void dispose() {
// do nothing
}
public void setApp(ScriptInterface app) {
// do nothing.
}
public void show() {
clooj.core.show();
}
public void configurationChanged() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getDescription() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getInfo() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getCopyright() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
## Instruction:
Remove line that does not compile
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@7511 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
## Code After:
/*
* Arthur Edelstein, UCSF, 2011
*/
package org.micromanager.clojureeditor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class ClojureEditorPlugin implements MMPlugin {
public static String menuName = "Clojure editor";
public void dispose() {
// do nothing
}
public void setApp(ScriptInterface app) {
// do nothing.
}
public void show() {
// this line does not compile:
//clooj.core.show();
}
public void configurationChanged() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getDescription() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getInfo() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getVersion() {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getCopyright() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
# ... existing code ...
}
public void show() {
// this line does not compile:
//clooj.core.show();
}
public void configurationChanged() {
# ... rest of the code ...
|
3ebb80476553e8228c6709a3e6ff75ea42fff586
|
properties/property.py
|
properties/property.py
|
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self):
pass
|
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self, name, price, baseRent, rentWithHouses, mortgageValue, owner=None, houseCost, hotelCost):
self.name = name
self.owner = owner
self.price = price
self.baseRent = baseRent
self.rentWithHouses = rentWithHouses
self.mortgageValue = mortgageValue
self.houseCost = houseCost
self.hotelCost = hotelCost
self.houses = 0
self.hotels = 0
@property
def rent(self):
return
def purchase(self, player, cost):
player.balance -= cost
def purchaseProperty(self, player):
self.owner = player
purchase(player, self.cost)
def buyHotel(self, player):
self.hotels += 1
player.balance -= self.hotelCost
def buyHouse(self, player):
self.houses += 1
player.balance -= self.houseCost
|
Add some basic transactional methdos to properties
|
Add some basic transactional methdos to properties
|
Python
|
mit
|
markthethomas/monopoly
|
python
|
## Code Before:
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self):
pass
## Instruction:
Add some basic transactional methdos to properties
## Code After:
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self, name, price, baseRent, rentWithHouses, mortgageValue, owner=None, houseCost, hotelCost):
self.name = name
self.owner = owner
self.price = price
self.baseRent = baseRent
self.rentWithHouses = rentWithHouses
self.mortgageValue = mortgageValue
self.houseCost = houseCost
self.hotelCost = hotelCost
self.houses = 0
self.hotels = 0
@property
def rent(self):
return
def purchase(self, player, cost):
player.balance -= cost
def purchaseProperty(self, player):
self.owner = player
purchase(player, self.cost)
def buyHotel(self, player):
self.hotels += 1
player.balance -= self.hotelCost
def buyHouse(self, player):
self.houses += 1
player.balance -= self.houseCost
|
// ... existing code ...
class Property(object):
"""
// ... modified code ...
a monopoly property that items on the
board can inherit from
"""
def __init__(self, name, price, baseRent, rentWithHouses, mortgageValue, owner=None, houseCost, hotelCost):
self.name = name
self.owner = owner
self.price = price
self.baseRent = baseRent
self.rentWithHouses = rentWithHouses
self.mortgageValue = mortgageValue
self.houseCost = houseCost
self.hotelCost = hotelCost
self.houses = 0
self.hotels = 0
@property
def rent(self):
return
def purchase(self, player, cost):
player.balance -= cost
def purchaseProperty(self, player):
self.owner = player
purchase(player, self.cost)
def buyHotel(self, player):
self.hotels += 1
player.balance -= self.hotelCost
def buyHouse(self, player):
self.houses += 1
player.balance -= self.houseCost
// ... rest of the code ...
|
e5b11c7a133058e3a26124fc057fda07c5658471
|
swagger-springmvc/src/main/java/com/mangofactory/swagger/paths/RelativeSwaggerPathProvider.java
|
swagger-springmvc/src/main/java/com/mangofactory/swagger/paths/RelativeSwaggerPathProvider.java
|
package com.mangofactory.swagger.paths;
import javax.servlet.ServletContext;
public class RelativeSwaggerPathProvider extends SwaggerPathProvider {
public static final String ROOT = "/";
private final ServletContext servletContext;
public RelativeSwaggerPathProvider(ServletContext servletContext) {
super();
this.servletContext = servletContext;
}
@Override
protected String applicationPath() {
return servletContext.getContextPath();
}
@Override
protected String getDocumentationPath() {
return ROOT;
}
}
|
package com.mangofactory.swagger.paths;
import javax.servlet.ServletContext;
import static com.google.common.base.Strings.isNullOrEmpty;
public class RelativeSwaggerPathProvider extends SwaggerPathProvider {
public static final String ROOT = "/";
private final ServletContext servletContext;
public RelativeSwaggerPathProvider(ServletContext servletContext) {
super();
this.servletContext = servletContext;
}
@Override
protected String applicationPath() {
return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
}
@Override
protected String getDocumentationPath() {
return ROOT;
}
}
|
Fix for when the context path is at the root the 'try this' doesnt work
|
Fix for when the context path is at the root the 'try this' doesnt work
|
Java
|
apache-2.0
|
wjc133/springfox,vmarusic/springfox,yelhouti/springfox,acourtneybrown/springfox,thomsonreuters/springfox,maksimu/springfox,RobWin/springfox,zhiqinghuang/springfox,jlstrater/springfox,maksimu/springfox,arshadalisoomro/springfox,ammmze/swagger-springmvc,springfox/springfox,RobWin/springfox,jlstrater/springfox,choiapril6/springfox,qq291462491/springfox,ammmze/swagger-springmvc,erikthered/springfox,namkee/springfox,erikthered/springfox,springfox/springfox,izeye/springfox,thomsonreuters/springfox,yelhouti/springfox,wjc133/springfox,thomasdarimont/springfox,namkee/springfox,cbornet/springfox,qq291462491/springfox,wjc133/springfox,vmarusic/springfox,kevinconaway/springfox,zorosteven/springfox,thomsonreuters/springfox,vmarusic/springfox,yelhouti/springfox,maksimu/springfox,acourtneybrown/springfox,cbornet/springfox,springfox/springfox,arshadalisoomro/springfox,acourtneybrown/springfox,springfox/springfox,zhiqinghuang/springfox,namkee/springfox,jlstrater/springfox,izeye/springfox,cbornet/springfox,choiapril6/springfox,arshadalisoomro/springfox,zorosteven/springfox,zorosteven/springfox,kevinconaway/springfox,izeye/springfox,qq291462491/springfox,RobWin/springfox,kevinconaway/springfox,choiapril6/springfox,erikthered/springfox,thomasdarimont/springfox,zhiqinghuang/springfox,thomasdarimont/springfox,ammmze/swagger-springmvc
|
java
|
## Code Before:
package com.mangofactory.swagger.paths;
import javax.servlet.ServletContext;
public class RelativeSwaggerPathProvider extends SwaggerPathProvider {
public static final String ROOT = "/";
private final ServletContext servletContext;
public RelativeSwaggerPathProvider(ServletContext servletContext) {
super();
this.servletContext = servletContext;
}
@Override
protected String applicationPath() {
return servletContext.getContextPath();
}
@Override
protected String getDocumentationPath() {
return ROOT;
}
}
## Instruction:
Fix for when the context path is at the root the 'try this' doesnt work
## Code After:
package com.mangofactory.swagger.paths;
import javax.servlet.ServletContext;
import static com.google.common.base.Strings.isNullOrEmpty;
public class RelativeSwaggerPathProvider extends SwaggerPathProvider {
public static final String ROOT = "/";
private final ServletContext servletContext;
public RelativeSwaggerPathProvider(ServletContext servletContext) {
super();
this.servletContext = servletContext;
}
@Override
protected String applicationPath() {
return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
}
@Override
protected String getDocumentationPath() {
return ROOT;
}
}
|
...
package com.mangofactory.swagger.paths;
import javax.servlet.ServletContext;
import static com.google.common.base.Strings.isNullOrEmpty;
public class RelativeSwaggerPathProvider extends SwaggerPathProvider {
public static final String ROOT = "/";
...
@Override
protected String applicationPath() {
return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
}
@Override
...
|
bfecbe84cdd975c90e9d088d6b76d199af7694f7
|
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java
|
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java
|
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.commit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;
/**
* Open commit action
*/
public class OpenCommitAction extends ActionDelegate implements
IWorkbenchWindowActionDelegate {
private Shell shell;
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK == dialog.open())
for (Object result : dialog.getResult())
CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
shell = window.getShell();
}
}
|
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.commit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;
/**
* Open commit action
*/
public class OpenCommitAction extends ActionDelegate implements
IWorkbenchWindowActionDelegate {
private Shell shell;
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK != dialog.open())
return;
Object[] results = dialog.getResult();
if (results == null || results.length == 0)
return;
for (Object result : results)
CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
shell = window.getShell();
}
}
|
Add check for null/empty results in commit selection dialog.
|
Add check for null/empty results in commit selection dialog.
Bug: 353151
Change-Id: Ia3ca7764b4d7dde41da6f9219ff43d322c9f4ab5
Signed-off-by: Kevin Sawicki <[email protected]>
|
Java
|
epl-1.0
|
collaborative-modeling/egit,chalstrick/egit,paulvi/egit,collaborative-modeling/egit,blizzy78/egit,paulvi/egit,mdoninger/egit,SmithAndr/egit,wdliu/egit,SmithAndr/egit,wdliu/egit
|
java
|
## Code Before:
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.commit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;
/**
* Open commit action
*/
public class OpenCommitAction extends ActionDelegate implements
IWorkbenchWindowActionDelegate {
private Shell shell;
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK == dialog.open())
for (Object result : dialog.getResult())
CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
shell = window.getShell();
}
}
## Instruction:
Add check for null/empty results in commit selection dialog.
Bug: 353151
Change-Id: Ia3ca7764b4d7dde41da6f9219ff43d322c9f4ab5
Signed-off-by: Kevin Sawicki <[email protected]>
## Code After:
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.commit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;
/**
* Open commit action
*/
public class OpenCommitAction extends ActionDelegate implements
IWorkbenchWindowActionDelegate {
private Shell shell;
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK != dialog.open())
return;
Object[] results = dialog.getResult();
if (results == null || results.length == 0)
return;
for (Object result : results)
CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
shell = window.getShell();
}
}
|
// ... existing code ...
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK != dialog.open())
return;
Object[] results = dialog.getResult();
if (results == null || results.length == 0)
return;
for (Object result : results)
CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
// ... rest of the code ...
|
24788b106b9cdd70e7240dc3eccac82fba290c85
|
tests/util/test_yaml.py
|
tests/util/test_yaml.py
|
"""Test Home Assistant yaml loader."""
import io
import unittest
from homeassistant.util import yaml
class TestYaml(unittest.TestCase):
"""Test util.yaml loader."""
def test_simple_list(self):
"""Test simple list."""
conf = "config:\n - simple\n - list"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['config'] == ["simple", "list"]
def test_simple_dict(self):
"""Test simple dict."""
conf = "key: value"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['key'] == 'value'
def test_duplicate_key(self):
"""Test simple dict."""
conf = "key: thing1\nkey: thing2"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
|
"""Test Home Assistant yaml loader."""
import io
import unittest
import os
from homeassistant.util import yaml
class TestYaml(unittest.TestCase):
"""Test util.yaml loader."""
def test_simple_list(self):
"""Test simple list."""
conf = "config:\n - simple\n - list"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['config'] == ["simple", "list"]
def test_simple_dict(self):
"""Test simple dict."""
conf = "key: value"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['key'] == 'value'
def test_duplicate_key(self):
"""Test simple dict."""
conf = "key: thing1\nkey: thing2"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
def test_enviroment_variable(self):
"""Test config file with enviroment variable."""
os.environ["PASSWORD"] = "secret_password"
conf = "password: !env_var PASSWORD"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['password'] == "secret_password"
del os.environ["PASSWORD"]
def test_invalid_enviroment_variable(self):
"""Test config file with no enviroment variable sat."""
conf = "password: !env_var PASSWORD"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
|
Add test for yaml enviroment
|
Add test for yaml enviroment
|
Python
|
mit
|
lukas-hetzenecker/home-assistant,LinuxChristian/home-assistant,molobrakos/home-assistant,sffjunkie/home-assistant,titilambert/home-assistant,ewandor/home-assistant,emilhetty/home-assistant,mikaelboman/home-assistant,nkgilley/home-assistant,robbiet480/home-assistant,jawilson/home-assistant,molobrakos/home-assistant,devdelay/home-assistant,florianholzapfel/home-assistant,deisi/home-assistant,betrisey/home-assistant,jaharkes/home-assistant,qedi-r/home-assistant,postlund/home-assistant,mezz64/home-assistant,eagleamon/home-assistant,w1ll1am23/home-assistant,varunr047/homefile,balloob/home-assistant,leoc/home-assistant,jabesq/home-assistant,MungoRae/home-assistant,Cinntax/home-assistant,nugget/home-assistant,soldag/home-assistant,dmeulen/home-assistant,happyleavesaoc/home-assistant,devdelay/home-assistant,sffjunkie/home-assistant,kennedyshead/home-assistant,sffjunkie/home-assistant,sander76/home-assistant,hexxter/home-assistant,balloob/home-assistant,Teagan42/home-assistant,DavidLP/home-assistant,Danielhiversen/home-assistant,robjohnson189/home-assistant,morphis/home-assistant,Zac-HD/home-assistant,ct-23/home-assistant,w1ll1am23/home-assistant,Danielhiversen/home-assistant,aronsky/home-assistant,kyvinh/home-assistant,emilhetty/home-assistant,hexxter/home-assistant,hmronline/home-assistant,varunr047/homefile,shaftoe/home-assistant,MartinHjelmare/home-assistant,shaftoe/home-assistant,deisi/home-assistant,joopert/home-assistant,open-homeautomation/home-assistant,open-homeautomation/home-assistant,dmeulen/home-assistant,oandrew/home-assistant,HydrelioxGitHub/home-assistant,deisi/home-assistant,leoc/home-assistant,emilhetty/home-assistant,postlund/home-assistant,ct-23/home-assistant,ct-23/home-assistant,auduny/home-assistant,betrisey/home-assistant,HydrelioxGitHub/home-assistant,PetePriority/home-assistant,leppa/home-assistant,home-assistant/home-assistant,PetePriority/home-assistant,sffjunkie/home-assistant,persandstrom/home-assistant,jabesq/home-assistant,robjohnson189/home-assistant,jamespcole/home-assistant,alexmogavero/home-assistant,oandrew/home-assistant,Smart-Torvy/torvy-home-assistant,philipbl/home-assistant,tchellomello/home-assistant,GenericStudent/home-assistant,rohitranjan1991/home-assistant,stefan-jonasson/home-assistant,xifle/home-assistant,philipbl/home-assistant,auduny/home-assistant,MungoRae/home-assistant,jaharkes/home-assistant,Zac-HD/home-assistant,soldag/home-assistant,tinloaf/home-assistant,bdfoster/blumate,morphis/home-assistant,keerts/home-assistant,morphis/home-assistant,jnewland/home-assistant,Smart-Torvy/torvy-home-assistant,partofthething/home-assistant,alexmogavero/home-assistant,eagleamon/home-assistant,PetePriority/home-assistant,mKeRix/home-assistant,florianholzapfel/home-assistant,tinloaf/home-assistant,kyvinh/home-assistant,nkgilley/home-assistant,persandstrom/home-assistant,kyvinh/home-assistant,Zac-HD/home-assistant,turbokongen/home-assistant,turbokongen/home-assistant,fbradyirl/home-assistant,JshWright/home-assistant,bdfoster/blumate,sffjunkie/home-assistant,partofthething/home-assistant,emilhetty/home-assistant,kennedyshead/home-assistant,aequitas/home-assistant,emilhetty/home-assistant,pschmitt/home-assistant,jabesq/home-assistant,varunr047/homefile,srcLurker/home-assistant,Smart-Torvy/torvy-home-assistant,Julian/home-assistant,toddeye/home-assistant,GenericStudent/home-assistant,mKeRix/home-assistant,srcLurker/home-assistant,rohitranjan1991/home-assistant,robjohnson189/home-assistant,robbiet480/home-assistant,stefan-jonasson/home-assistant,HydrelioxGitHub/home-assistant,jnewland/home-assistant,happyleavesaoc/home-assistant,adrienbrault/home-assistant,alexmogavero/home-assistant,DavidLP/home-assistant,philipbl/home-assistant,tboyce1/home-assistant,LinuxChristian/home-assistant,hmronline/home-assistant,MungoRae/home-assistant,mikaelboman/home-assistant,Duoxilian/home-assistant,hexxter/home-assistant,JshWright/home-assistant,bdfoster/blumate,fbradyirl/home-assistant,miniconfig/home-assistant,robjohnson189/home-assistant,nugget/home-assistant,Cinntax/home-assistant,betrisey/home-assistant,sdague/home-assistant,adrienbrault/home-assistant,tboyce1/home-assistant,home-assistant/home-assistant,lukas-hetzenecker/home-assistant,sdague/home-assistant,tchellomello/home-assistant,rohitranjan1991/home-assistant,toddeye/home-assistant,mKeRix/home-assistant,mKeRix/home-assistant,eagleamon/home-assistant,mikaelboman/home-assistant,aronsky/home-assistant,oandrew/home-assistant,eagleamon/home-assistant,morphis/home-assistant,ewandor/home-assistant,betrisey/home-assistant,ma314smith/home-assistant,sander76/home-assistant,balloob/home-assistant,jaharkes/home-assistant,dmeulen/home-assistant,miniconfig/home-assistant,keerts/home-assistant,aequitas/home-assistant,FreekingDean/home-assistant,Julian/home-assistant,Zac-HD/home-assistant,oandrew/home-assistant,ma314smith/home-assistant,MungoRae/home-assistant,nugget/home-assistant,open-homeautomation/home-assistant,ewandor/home-assistant,deisi/home-assistant,florianholzapfel/home-assistant,mikaelboman/home-assistant,titilambert/home-assistant,Teagan42/home-assistant,jaharkes/home-assistant,Duoxilian/home-assistant,shaftoe/home-assistant,leppa/home-assistant,keerts/home-assistant,mezz64/home-assistant,jawilson/home-assistant,deisi/home-assistant,jamespcole/home-assistant,Smart-Torvy/torvy-home-assistant,tboyce021/home-assistant,stefan-jonasson/home-assistant,stefan-jonasson/home-assistant,ct-23/home-assistant,DavidLP/home-assistant,auduny/home-assistant,pschmitt/home-assistant,ma314smith/home-assistant,persandstrom/home-assistant,varunr047/homefile,philipbl/home-assistant,joopert/home-assistant,devdelay/home-assistant,FreekingDean/home-assistant,happyleavesaoc/home-assistant,hmronline/home-assistant,xifle/home-assistant,tboyce021/home-assistant,xifle/home-assistant,miniconfig/home-assistant,aequitas/home-assistant,Duoxilian/home-assistant,bdfoster/blumate,JshWright/home-assistant,open-homeautomation/home-assistant,keerts/home-assistant,leoc/home-assistant,ma314smith/home-assistant,srcLurker/home-assistant,jamespcole/home-assistant,LinuxChristian/home-assistant,jnewland/home-assistant,varunr047/homefile,shaftoe/home-assistant,miniconfig/home-assistant,tboyce1/home-assistant,devdelay/home-assistant,happyleavesaoc/home-assistant,MungoRae/home-assistant,MartinHjelmare/home-assistant,hmronline/home-assistant,LinuxChristian/home-assistant,bdfoster/blumate,tinloaf/home-assistant,xifle/home-assistant,srcLurker/home-assistant,Julian/home-assistant,florianholzapfel/home-assistant,molobrakos/home-assistant,LinuxChristian/home-assistant,Julian/home-assistant,tboyce1/home-assistant,mikaelboman/home-assistant,leoc/home-assistant,kyvinh/home-assistant,hexxter/home-assistant,Duoxilian/home-assistant,hmronline/home-assistant,JshWright/home-assistant,MartinHjelmare/home-assistant,alexmogavero/home-assistant,qedi-r/home-assistant,dmeulen/home-assistant,fbradyirl/home-assistant,ct-23/home-assistant
|
python
|
## Code Before:
"""Test Home Assistant yaml loader."""
import io
import unittest
from homeassistant.util import yaml
class TestYaml(unittest.TestCase):
"""Test util.yaml loader."""
def test_simple_list(self):
"""Test simple list."""
conf = "config:\n - simple\n - list"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['config'] == ["simple", "list"]
def test_simple_dict(self):
"""Test simple dict."""
conf = "key: value"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['key'] == 'value'
def test_duplicate_key(self):
"""Test simple dict."""
conf = "key: thing1\nkey: thing2"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
## Instruction:
Add test for yaml enviroment
## Code After:
"""Test Home Assistant yaml loader."""
import io
import unittest
import os
from homeassistant.util import yaml
class TestYaml(unittest.TestCase):
"""Test util.yaml loader."""
def test_simple_list(self):
"""Test simple list."""
conf = "config:\n - simple\n - list"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['config'] == ["simple", "list"]
def test_simple_dict(self):
"""Test simple dict."""
conf = "key: value"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['key'] == 'value'
def test_duplicate_key(self):
"""Test simple dict."""
conf = "key: thing1\nkey: thing2"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
def test_enviroment_variable(self):
"""Test config file with enviroment variable."""
os.environ["PASSWORD"] = "secret_password"
conf = "password: !env_var PASSWORD"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['password'] == "secret_password"
del os.environ["PASSWORD"]
def test_invalid_enviroment_variable(self):
"""Test config file with no enviroment variable sat."""
conf = "password: !env_var PASSWORD"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
|
...
"""Test Home Assistant yaml loader."""
import io
import unittest
import os
from homeassistant.util import yaml
...
pass
else:
assert 0
def test_enviroment_variable(self):
"""Test config file with enviroment variable."""
os.environ["PASSWORD"] = "secret_password"
conf = "password: !env_var PASSWORD"
with io.StringIO(conf) as f:
doc = yaml.yaml.safe_load(f)
assert doc['password'] == "secret_password"
del os.environ["PASSWORD"]
def test_invalid_enviroment_variable(self):
"""Test config file with no enviroment variable sat."""
conf = "password: !env_var PASSWORD"
try:
with io.StringIO(conf) as f:
yaml.yaml.safe_load(f)
except Exception:
pass
else:
assert 0
...
|
a42ffdcd34876bcd1df81ce00dbfd6426580bd82
|
gaphor/UML/classes/copypaste.py
|
gaphor/UML/classes/copypaste.py
|
import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
|
import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_enumeration(element: Enumeration):
yield element.id, copy_named_element(element)
for literal in element.ownedLiteral:
yield from copy(literal)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
|
Copy enumeration literals when pasting an Enumeration
|
Copy enumeration literals when pasting an Enumeration
Signed-off-by: Dan Yeaw <[email protected]>
|
Python
|
lgpl-2.1
|
amolenaar/gaphor,amolenaar/gaphor
|
python
|
## Code Before:
import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
## Instruction:
Copy enumeration literals when pasting an Enumeration
Signed-off-by: Dan Yeaw <[email protected]>
## Code After:
import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_enumeration(element: Enumeration):
yield element.id, copy_named_element(element)
for literal in element.ownedLiteral:
yield from copy(literal)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
|
// ... existing code ...
import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation
@copy.register(Class)
// ... modified code ...
@copy.register
def copy_enumeration(element: Enumeration):
yield element.id, copy_named_element(element)
for literal in element.ownedLiteral:
yield from copy(literal)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
// ... rest of the code ...
|
8e67056ccd09a3b31edfb13bc38091606752c84d
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "[email protected]",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
|
from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg',
'pcbmode_config.json'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "[email protected]",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
|
Include pcbmode_config.json file in package
|
Include pcbmode_config.json file in package
|
Python
|
mit
|
ddm/pcbmode,boldport/pcbmode
|
python
|
## Code Before:
from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "[email protected]",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
## Instruction:
Include pcbmode_config.json file in package
## Code After:
from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg',
'pcbmode_config.json'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "[email protected]",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
|
// ... existing code ...
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg',
'pcbmode_config.json'],
},
# metadata for upload to PyPI
// ... rest of the code ...
|
fa279ca1f8e4c8e6b4094840d3ab40c0ac637eff
|
ocradmin/ocrpresets/models.py
|
ocradmin/ocrpresets/models.py
|
from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return self.name
|
from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
|
Improve unicode method. Whitespace cleanup
|
Improve unicode method. Whitespace cleanup
|
Python
|
apache-2.0
|
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
|
python
|
## Code Before:
from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return self.name
## Instruction:
Improve unicode method. Whitespace cleanup
## Code After:
from django.db import models
from django.contrib.auth.models import User
from picklefield import fields
from tagging.fields import TagField
import tagging
class OcrPreset(models.Model):
user = models.ForeignKey(User)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True, auto_now=True)
type = models.CharField(max_length=20,
choices=[("segment", "Segment"), ("binarize", "Binarize")])
data = fields.PickledObjectField()
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
|
// ... existing code ...
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
// ... rest of the code ...
|
1b36dd94759c41c4af433ce53e131e318d09c14a
|
tests/storage/dav/test_carddav.py
|
tests/storage/dav/test_carddav.py
|
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
class TestCarddavStorage(DavStorageTests):
storage_class = CarddavStorage
item_template = (u'BEGIN:VCARD\n'
u'VERSION:3.0\n'
u'FN:Cyrus Daboo\n'
u'N:Daboo;Cyrus\n'
u'ADR;TYPE=POSTAL:;2822 Email HQ;' # address continuing
u'Suite 2821;RFCVille;PA;15213;USA\n' # on next line
u'EMAIL;TYPE=INTERNET;TYPE=PREF:[email protected]\n'
u'NICKNAME:me\n'
u'NOTE:Example VCard.\n'
u'ORG:Self Employed\n'
u'TEL;TYPE=WORK;TYPE=VOICE:412 605 0499\n'
u'TEL;TYPE=FAX:412 605 0705\n'
u'URL:http://www.example.com\n'
u'UID:{uid}\n'
u'X-SOMETHING:{r}\n'
u'END:VCARD')
|
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
VCARD_TEMPLATE = u'''BEGIN:VCARD
VERSION:3.0
FN:Cyrus Daboo
N:Daboo;Cyrus
ADR;TYPE=POSTAL:;2822 Email HQ;Suite 2821;RFCVille;PA;15213;USA
EMAIL;TYPE=INTERNET;TYPE=PREF:[email protected]
NICKNAME:me
NOTE:Example VCard.
ORG:Self Employed
TEL;TYPE=WORK;TYPE=VOICE:412 605 0499
TEL;TYPE=FAX:412 605 0705
URL:http://www.example.com
UID:{uid}
X-SOMETHING:{r}
END:VCARD'''
class TestCarddavStorage(DavStorageTests):
storage_class = CarddavStorage
item_template = VCARD_TEMPLATE
|
Move vcard template to real multi-line string
|
Move vcard template to real multi-line string
|
Python
|
mit
|
tribut/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,mathstuf/vdirsyncer,hobarrera/vdirsyncer,hobarrera/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,tribut/vdirsyncer,mathstuf/vdirsyncer
|
python
|
## Code Before:
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
class TestCarddavStorage(DavStorageTests):
storage_class = CarddavStorage
item_template = (u'BEGIN:VCARD\n'
u'VERSION:3.0\n'
u'FN:Cyrus Daboo\n'
u'N:Daboo;Cyrus\n'
u'ADR;TYPE=POSTAL:;2822 Email HQ;' # address continuing
u'Suite 2821;RFCVille;PA;15213;USA\n' # on next line
u'EMAIL;TYPE=INTERNET;TYPE=PREF:[email protected]\n'
u'NICKNAME:me\n'
u'NOTE:Example VCard.\n'
u'ORG:Self Employed\n'
u'TEL;TYPE=WORK;TYPE=VOICE:412 605 0499\n'
u'TEL;TYPE=FAX:412 605 0705\n'
u'URL:http://www.example.com\n'
u'UID:{uid}\n'
u'X-SOMETHING:{r}\n'
u'END:VCARD')
## Instruction:
Move vcard template to real multi-line string
## Code After:
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
VCARD_TEMPLATE = u'''BEGIN:VCARD
VERSION:3.0
FN:Cyrus Daboo
N:Daboo;Cyrus
ADR;TYPE=POSTAL:;2822 Email HQ;Suite 2821;RFCVille;PA;15213;USA
EMAIL;TYPE=INTERNET;TYPE=PREF:[email protected]
NICKNAME:me
NOTE:Example VCard.
ORG:Self Employed
TEL;TYPE=WORK;TYPE=VOICE:412 605 0499
TEL;TYPE=FAX:412 605 0705
URL:http://www.example.com
UID:{uid}
X-SOMETHING:{r}
END:VCARD'''
class TestCarddavStorage(DavStorageTests):
storage_class = CarddavStorage
item_template = VCARD_TEMPLATE
|
...
from . import DavStorageTests
VCARD_TEMPLATE = u'''BEGIN:VCARD
VERSION:3.0
FN:Cyrus Daboo
N:Daboo;Cyrus
ADR;TYPE=POSTAL:;2822 Email HQ;Suite 2821;RFCVille;PA;15213;USA
EMAIL;TYPE=INTERNET;TYPE=PREF:[email protected]
NICKNAME:me
NOTE:Example VCard.
ORG:Self Employed
TEL;TYPE=WORK;TYPE=VOICE:412 605 0499
TEL;TYPE=FAX:412 605 0705
URL:http://www.example.com
UID:{uid}
X-SOMETHING:{r}
END:VCARD'''
class TestCarddavStorage(DavStorageTests):
storage_class = CarddavStorage
item_template = VCARD_TEMPLATE
...
|
cee291799e9aa19e23593b3618a45f7cee16d0ed
|
modules/cah/CAHGame.py
|
modules/cah/CAHGame.py
|
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck ={
'questions' : [
"_? There's an app for that.",
"I got 99 problems but _ ain't one.",
],
'answers' : [
"Flying sex snakes.",
"Michelle Obama's arms.",
"German dungeon porn.",
"White people.",
"Getting so angry that you pop a boner.",
"Freedom of Speech",
]
}
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
def draw(self, color):
'''Draws a random card of <color> from the databse and returns a Card object.'''
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False
#Utiliy class for a Card
class Card:
def __init__(self, color, body):
self.color = color
self.body = body
|
from cards import Deck, NoMoreCards
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck = Deck()
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False
|
Use the new Deck class
|
Use the new Deck class
|
Python
|
mit
|
tcoppi/scrappy,tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy
|
python
|
## Code Before:
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck ={
'questions' : [
"_? There's an app for that.",
"I got 99 problems but _ ain't one.",
],
'answers' : [
"Flying sex snakes.",
"Michelle Obama's arms.",
"German dungeon porn.",
"White people.",
"Getting so angry that you pop a boner.",
"Freedom of Speech",
]
}
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
def draw(self, color):
'''Draws a random card of <color> from the databse and returns a Card object.'''
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False
#Utiliy class for a Card
class Card:
def __init__(self, color, body):
self.color = color
self.body = body
## Instruction:
Use the new Deck class
## Code After:
from cards import Deck, NoMoreCards
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck = Deck()
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False
|
# ... existing code ...
from cards import Deck, NoMoreCards
class CAHGame:
def __init__(self):
# ... modified code ...
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck = Deck()
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
...
#start the game
def start(self):
pass
...
self.score = 0
self.hand = {}
self.isCzar = False
# ... rest of the code ...
|
dd58dbbbdb9b3a9479fa5db38a4e4038a6514fef
|
configReader.py
|
configReader.py
|
class ConfigReader():
def __init__(self):
self.keys={}
#Read Keys from file
def readKeys(self):
keysFile=open("config.txt","r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
item=item[:-1]
#If a commented line
if (item[0]=='#'):
pass
#If a new line is the first char
elif (item[0]=='\n'):
pass
else:
#Get Position of equal sign
pos=item.index('=')
#Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end)
self.keys[item[0:pos]]=item[pos+1:]
#Return the keys
def getKeys(self):
return self.keys
|
class ConfigReader():
def __init__(self):
self.keys={}
#Read Keys from file
def readKeys(self):
keysFile=open("config.txt","r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
item=item[:-1]
#If a commented line
if (item[0]=='#'):
continue
#If a new line is the first char
elif (item[0]=='\n'):
continue
else:
#Get Position of equal sign
pos=item.index('=')
#Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end)
self.keys[item[0:pos]]=item[pos+1:]
#Return the keys
def getKeys(self):
return self.keys
|
Change 'pass' statements to 'continue' statements.
|
Change 'pass' statements to 'continue' statements.
|
Python
|
mit
|
ollien/PyConfigReader
|
python
|
## Code Before:
class ConfigReader():
def __init__(self):
self.keys={}
#Read Keys from file
def readKeys(self):
keysFile=open("config.txt","r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
item=item[:-1]
#If a commented line
if (item[0]=='#'):
pass
#If a new line is the first char
elif (item[0]=='\n'):
pass
else:
#Get Position of equal sign
pos=item.index('=')
#Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end)
self.keys[item[0:pos]]=item[pos+1:]
#Return the keys
def getKeys(self):
return self.keys
## Instruction:
Change 'pass' statements to 'continue' statements.
## Code After:
class ConfigReader():
def __init__(self):
self.keys={}
#Read Keys from file
def readKeys(self):
keysFile=open("config.txt","r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
item=item[:-1]
#If a commented line
if (item[0]=='#'):
continue
#If a new line is the first char
elif (item[0]=='\n'):
continue
else:
#Get Position of equal sign
pos=item.index('=')
#Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end)
self.keys[item[0:pos]]=item[pos+1:]
#Return the keys
def getKeys(self):
return self.keys
|
# ... existing code ...
item=item[:-1]
#If a commented line
if (item[0]=='#'):
continue
#If a new line is the first char
elif (item[0]=='\n'):
continue
else:
#Get Position of equal sign
pos=item.index('=')
# ... rest of the code ...
|
bcd5ea69815405508d7f862754f910fe381172b9
|
responsive/context_processors.py
|
responsive/context_processors.py
|
from django.core.exceptions import ImproperlyConfigured
from .conf import settings
from .utils import Device
def device(request):
responsive_middleware = 'responsive.middleware.ResponsiveMiddleware'
if responsive_middleware not in settings.MIDDLEWARE_CLASSES:
raise ImproperlyConfigured(
"responsive context_processors requires the responsive middleware to "
"be installed. Edit your MIDDLEWARE_CLASSES setting to insert"
"the 'responsive.middleware.ResponsiveMiddleware'")
device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None)
if not device_obj:
device_obj = Device()
return {
settings.RESPONSIVE_VARIABLE_NAME: device_obj
}
|
from django.core.exceptions import ImproperlyConfigured
from .conf import settings
from .utils import Device
def device(request):
responsive_middleware = 'responsive.middleware.ResponsiveMiddleware'
if responsive_middleware not in settings.MIDDLEWARE_CLASSES:
raise ImproperlyConfigured(
"You must enable the 'ResponsiveMiddleware'. Edit your "
"MIDDLEWARE_CLASSES setting to insert"
"the 'responsive.middleware.ResponsiveMiddleware'")
device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None)
if not device_obj:
device_obj = Device()
return {
settings.RESPONSIVE_VARIABLE_NAME: device_obj
}
|
Update message for missing ResponsiveMiddleware
|
Update message for missing ResponsiveMiddleware
|
Python
|
bsd-3-clause
|
mishbahr/django-responsive2,mishbahr/django-responsive2
|
python
|
## Code Before:
from django.core.exceptions import ImproperlyConfigured
from .conf import settings
from .utils import Device
def device(request):
responsive_middleware = 'responsive.middleware.ResponsiveMiddleware'
if responsive_middleware not in settings.MIDDLEWARE_CLASSES:
raise ImproperlyConfigured(
"responsive context_processors requires the responsive middleware to "
"be installed. Edit your MIDDLEWARE_CLASSES setting to insert"
"the 'responsive.middleware.ResponsiveMiddleware'")
device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None)
if not device_obj:
device_obj = Device()
return {
settings.RESPONSIVE_VARIABLE_NAME: device_obj
}
## Instruction:
Update message for missing ResponsiveMiddleware
## Code After:
from django.core.exceptions import ImproperlyConfigured
from .conf import settings
from .utils import Device
def device(request):
responsive_middleware = 'responsive.middleware.ResponsiveMiddleware'
if responsive_middleware not in settings.MIDDLEWARE_CLASSES:
raise ImproperlyConfigured(
"You must enable the 'ResponsiveMiddleware'. Edit your "
"MIDDLEWARE_CLASSES setting to insert"
"the 'responsive.middleware.ResponsiveMiddleware'")
device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None)
if not device_obj:
device_obj = Device()
return {
settings.RESPONSIVE_VARIABLE_NAME: device_obj
}
|
...
responsive_middleware = 'responsive.middleware.ResponsiveMiddleware'
if responsive_middleware not in settings.MIDDLEWARE_CLASSES:
raise ImproperlyConfigured(
"You must enable the 'ResponsiveMiddleware'. Edit your "
"MIDDLEWARE_CLASSES setting to insert"
"the 'responsive.middleware.ResponsiveMiddleware'")
device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None)
...
|
94c763a2d1436db2d8a824eb9caf279ff9ec57b1
|
onyx-database-tests/src/servers/SampleDatabaseServer.java
|
onyx-database-tests/src/servers/SampleDatabaseServer.java
|
package servers;
import com.onyx.application.WebDatabaseServer;
import entities.SimpleEntity;
/**
* Created by timothy.osborn on 4/1/15.
*/
public class SampleDatabaseServer extends WebDatabaseServer
{
public SampleDatabaseServer()
{
}
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
SampleDatabaseServer server1 = new SampleDatabaseServer();
server1.setPort(8080);
server1.setWebServicePort(8082);
server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd");
server1.start();
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName("Test Name");
simpleEntity.setSimpleId("ASDF");
server1.join();
System.out.println("Started");
}
}
|
package servers;
import com.onyx.application.WebDatabaseServer;
import entities.SimpleEntity;
/**
* Created by timothy.osborn on 4/1/15.
*/
public class SampleDatabaseServer extends WebDatabaseServer
{
public SampleDatabaseServer()
{
}
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
SampleDatabaseServer server1 = new SampleDatabaseServer();
server1.setPort(8080);
server1.setWebServicePort(8082);
server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd");
server1.start();
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName("Test Name");
simpleEntity.setSimpleId("ASDF");
server1.getPersistenceManager().saveEntity(simpleEntity);
server1.join();
System.out.println("Started");
}
}
|
Add line to save an entity in test
|
Add line to save an entity in test
|
Java
|
agpl-3.0
|
OnyxDevTools/onyx-database-parent,OnyxDevTools/onyx-database-parent
|
java
|
## Code Before:
package servers;
import com.onyx.application.WebDatabaseServer;
import entities.SimpleEntity;
/**
* Created by timothy.osborn on 4/1/15.
*/
public class SampleDatabaseServer extends WebDatabaseServer
{
public SampleDatabaseServer()
{
}
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
SampleDatabaseServer server1 = new SampleDatabaseServer();
server1.setPort(8080);
server1.setWebServicePort(8082);
server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd");
server1.start();
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName("Test Name");
simpleEntity.setSimpleId("ASDF");
server1.join();
System.out.println("Started");
}
}
## Instruction:
Add line to save an entity in test
## Code After:
package servers;
import com.onyx.application.WebDatabaseServer;
import entities.SimpleEntity;
/**
* Created by timothy.osborn on 4/1/15.
*/
public class SampleDatabaseServer extends WebDatabaseServer
{
public SampleDatabaseServer()
{
}
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
SampleDatabaseServer server1 = new SampleDatabaseServer();
server1.setPort(8080);
server1.setWebServicePort(8082);
server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd");
server1.start();
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName("Test Name");
simpleEntity.setSimpleId("ASDF");
server1.getPersistenceManager().saveEntity(simpleEntity);
server1.join();
System.out.println("Started");
}
}
|
...
SimpleEntity simpleEntity = new SimpleEntity();
simpleEntity.setName("Test Name");
simpleEntity.setSimpleId("ASDF");
server1.getPersistenceManager().saveEntity(simpleEntity);
server1.join();
System.out.println("Started");
...
|
8c27d261c2c1339792745c3b94fefb99e56c961d
|
src/main/java/pete/metrics/adaptability/AdaptableElement.java
|
src/main/java/pete/metrics/adaptability/AdaptableElement.java
|
package pete.metrics.adaptability;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class AdaptableElement {
private final String name;
private final List<String> adaptions;
private String locatorExpression = "//*[local-name() = 'definitions']";
public AdaptableElement(String name) {
this.name = name;
adaptions = new ArrayList<>();
}
public void addAdaption(String adaption) {
adaptions.add(adaption);
}
public List<String> getAdaptions() {
return Collections.unmodifiableList(adaptions);
}
public int getNumberOfAdaptions() {
return adaptions.size();
}
public String getName() {
return name;
}
public int getAdaptabilityScore() {
return adaptions.size();
}
public String getLocatorExpression() {
return locatorExpression;
}
public void setLocatorExpression(String locatorExpression) {
this.locatorExpression += locatorExpression;
}
}
|
package pete.metrics.adaptability;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class AdaptableElement {
private final String name;
private final List<String> adaptions;
private String documentation;
private String locatorExpression = "//*[local-name() = 'definitions']";
public AdaptableElement(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
this.name = name;
adaptions = new ArrayList<>();
documentation = "";
}
public void addAdaption(String adaption) {
if (adaption != null) {
adaptions.add(adaption);
}
}
public List<String> getAdaptions() {
return Collections.unmodifiableList(adaptions);
}
public int getNumberOfAdaptions() {
return adaptions.size();
}
public String getName() {
return name;
}
public int getAdaptabilityScore() {
return adaptions.size();
}
public String getLocatorExpression() {
return locatorExpression;
}
public void setLocatorExpression(String locatorExpression) {
if (!(locatorExpression == null)) {
this.locatorExpression += locatorExpression;
}
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
if (documentation == null) {
this.documentation = "";
} else {
this.documentation = documentation;
}
}
}
|
Add documentation field and parameter validation
|
Add documentation field and parameter validation
|
Java
|
mit
|
lenhard/pete,uniba-dsg/prope,uniba-dsg/prope,lenhard/pete,lenhard/pete,uniba-dsg/prope
|
java
|
## Code Before:
package pete.metrics.adaptability;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class AdaptableElement {
private final String name;
private final List<String> adaptions;
private String locatorExpression = "//*[local-name() = 'definitions']";
public AdaptableElement(String name) {
this.name = name;
adaptions = new ArrayList<>();
}
public void addAdaption(String adaption) {
adaptions.add(adaption);
}
public List<String> getAdaptions() {
return Collections.unmodifiableList(adaptions);
}
public int getNumberOfAdaptions() {
return adaptions.size();
}
public String getName() {
return name;
}
public int getAdaptabilityScore() {
return adaptions.size();
}
public String getLocatorExpression() {
return locatorExpression;
}
public void setLocatorExpression(String locatorExpression) {
this.locatorExpression += locatorExpression;
}
}
## Instruction:
Add documentation field and parameter validation
## Code After:
package pete.metrics.adaptability;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class AdaptableElement {
private final String name;
private final List<String> adaptions;
private String documentation;
private String locatorExpression = "//*[local-name() = 'definitions']";
public AdaptableElement(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
this.name = name;
adaptions = new ArrayList<>();
documentation = "";
}
public void addAdaption(String adaption) {
if (adaption != null) {
adaptions.add(adaption);
}
}
public List<String> getAdaptions() {
return Collections.unmodifiableList(adaptions);
}
public int getNumberOfAdaptions() {
return adaptions.size();
}
public String getName() {
return name;
}
public int getAdaptabilityScore() {
return adaptions.size();
}
public String getLocatorExpression() {
return locatorExpression;
}
public void setLocatorExpression(String locatorExpression) {
if (!(locatorExpression == null)) {
this.locatorExpression += locatorExpression;
}
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
if (documentation == null) {
this.documentation = "";
} else {
this.documentation = documentation;
}
}
}
|
...
private final List<String> adaptions;
private String documentation;
private String locatorExpression = "//*[local-name() = 'definitions']";
public AdaptableElement(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
this.name = name;
adaptions = new ArrayList<>();
documentation = "";
}
public void addAdaption(String adaption) {
if (adaption != null) {
adaptions.add(adaption);
}
}
public List<String> getAdaptions() {
...
}
public void setLocatorExpression(String locatorExpression) {
if (!(locatorExpression == null)) {
this.locatorExpression += locatorExpression;
}
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
if (documentation == null) {
this.documentation = "";
} else {
this.documentation = documentation;
}
}
}
...
|
9b968e8cf4c5fd8e4bd120255b8eb3c7bc4e6943
|
mygpoauth/authorization/admin.py
|
mygpoauth/authorization/admin.py
|
from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
pass
|
from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
def scope_list(self, app):
return ', '.join(app.scopes)
list_display = ['user', 'application', 'scope_list']
list_select_related = ['user', 'application']
readonly_fields = ['user']
fields = ['user', 'application', 'scopes', 'code']
|
Improve Admin for Authorization objects
|
Improve Admin for Authorization objects
|
Python
|
agpl-3.0
|
gpodder/mygpo-auth,gpodder/mygpo-auth
|
python
|
## Code Before:
from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
pass
## Instruction:
Improve Admin for Authorization objects
## Code After:
from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
def scope_list(self, app):
return ', '.join(app.scopes)
list_display = ['user', 'application', 'scope_list']
list_select_related = ['user', 'application']
readonly_fields = ['user']
fields = ['user', 'application', 'scopes', 'code']
|
// ... existing code ...
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
def scope_list(self, app):
return ', '.join(app.scopes)
list_display = ['user', 'application', 'scope_list']
list_select_related = ['user', 'application']
readonly_fields = ['user']
fields = ['user', 'application', 'scopes', 'code']
// ... rest of the code ...
|
6032fb8eb10a2f6be28142c7473e03b4bc349c7c
|
partitions/registry.py
|
partitions/registry.py
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
Use update instead of setting key directly
|
Use update instead of setting key directly
|
Python
|
bsd-3-clause
|
eldarion/django-partitions
|
python
|
## Code Before:
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
## Instruction:
Use update instead of setting key directly
## Code After:
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
# ... existing code ...
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
# ... rest of the code ...
|
6df499d317b53597351919ad9a8035582ccc63b5
|
demo/org/getahead/dwrdemo/cli/JettyLauncher.java
|
demo/org/getahead/dwrdemo/cli/JettyLauncher.java
|
package org.getahead.dwrdemo.cli;
import org.directwebremoting.servlet.DwrServlet;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
/**
* JettyLauncher.
*/
public class JettyLauncher
{
/**
* Sets up and runs server.
* @param args
*/
public static void main(String[] args)
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
Context htmlContext = new Context(server, "/", Context.SESSIONS);
ResourceHandler htmlHandler = new ResourceHandler();
htmlHandler.setResourceBase("web");
htmlContext.setHandler(htmlHandler);
Context servletContext = new Context(server, "/", Context.SESSIONS);
ServletHolder holder = new ServletHolder(new DwrServlet());
holder.setInitParameter("activeReverseAjaxEnabled", "true");
holder.setInitParameter("debug", "true");
servletContext.addServlet(holder, "/dwr/*");
servletContext.setResourceBase("web");
try
{
JettyShutdown.addShutdownHook(server);
server.start();
server.join();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
|
package org.getahead.dwrdemo.cli;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* JettyLauncher.
*/
public class JettyLauncher
{
/**
* Sets up and runs server.
* @param args
*/
public static void main(String[] args)
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
server.setStopAtShutdown(true);
server.addHandler(new WebAppContext("web","/dwr"));
server.addHandler(new WebAppContext("test","/dwr-test"));
}
}
|
Use more compact Jetty Launcher
|
Use more compact Jetty Launcher
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1318 3a8262b2-faa5-11dc-8610-ff947880b6b2
|
Java
|
apache-2.0
|
burris/dwr,burris/dwr
|
java
|
## Code Before:
package org.getahead.dwrdemo.cli;
import org.directwebremoting.servlet.DwrServlet;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
/**
* JettyLauncher.
*/
public class JettyLauncher
{
/**
* Sets up and runs server.
* @param args
*/
public static void main(String[] args)
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
Context htmlContext = new Context(server, "/", Context.SESSIONS);
ResourceHandler htmlHandler = new ResourceHandler();
htmlHandler.setResourceBase("web");
htmlContext.setHandler(htmlHandler);
Context servletContext = new Context(server, "/", Context.SESSIONS);
ServletHolder holder = new ServletHolder(new DwrServlet());
holder.setInitParameter("activeReverseAjaxEnabled", "true");
holder.setInitParameter("debug", "true");
servletContext.addServlet(holder, "/dwr/*");
servletContext.setResourceBase("web");
try
{
JettyShutdown.addShutdownHook(server);
server.start();
server.join();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
## Instruction:
Use more compact Jetty Launcher
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1318 3a8262b2-faa5-11dc-8610-ff947880b6b2
## Code After:
package org.getahead.dwrdemo.cli;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* JettyLauncher.
*/
public class JettyLauncher
{
/**
* Sets up and runs server.
* @param args
*/
public static void main(String[] args)
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
server.setStopAtShutdown(true);
server.addHandler(new WebAppContext("web","/dwr"));
server.addHandler(new WebAppContext("test","/dwr-test"));
}
}
|
// ... existing code ...
package org.getahead.dwrdemo.cli;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* JettyLauncher.
// ... modified code ...
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
server.setStopAtShutdown(true);
server.addHandler(new WebAppContext("web","/dwr"));
server.addHandler(new WebAppContext("test","/dwr-test"));
}
}
// ... rest of the code ...
|
17b81fa393e00cdc7c288783d4d1a3775aa6ae05
|
src/main/java/info/u_team/u_team_core/util/registry/TileEntityTypeDeferredRegister.java
|
src/main/java/info/u_team/u_team_core/util/registry/TileEntityTypeDeferredRegister.java
|
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import com.mojang.datafixers.DataFixUtils;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
|
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(null));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
|
Fix the tile entity type (just push out null. We don't need this here)
|
Fix the tile entity type (just push out null. We don't need this here)
|
Java
|
apache-2.0
|
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
|
java
|
## Code Before:
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import com.mojang.datafixers.DataFixUtils;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
## Instruction:
Fix the tile entity type (just push out null. We don't need this here)
## Code After:
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(null));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
|
...
import java.util.function.Supplier;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
...
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(null));
}
public void register(IEventBus bus) {
...
|
40400617eba718214ec442d495ec9869c471f839
|
SWXSLTransform.h
|
SWXSLTransform.h
|
//
// SWXSLTransform.h
// This file is part of the "SWXMLMapping" project, and is distributed under the MIT License.
//
// Created by Samuel Williams on 23/02/12.
// Copyright (c) 2012 Samuel Williams. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SWXSLTransform : NSObject {
NSURL * _baseURL;
void * _stylesheet;
}
/// The base URL that was used to load the stylesheet:
@property(nonatomic,strong) NSURL * baseURL;
/// Initialize the XSL stylesheet from the given URL:
- (instancetype) initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
/// Use the XSL stylesheet to process a string containing XML with a set of arguments.
/// Arguments are typically evaluated by the XSLT processor, so, for example, strings must be passed with an additional set of quotes.
- (NSData *) processDocument:(NSString *)xmlBuffer arguments:(NSDictionary *)arguments;
@end
|
//
// SWXSLTransform.h
// This file is part of the "SWXMLMapping" project, and is distributed under the MIT License.
//
// Created by Samuel Williams on 23/02/12.
// Copyright (c) 2012 Samuel Williams. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SWXSLTransform : NSObject {
NSURL * _baseURL;
void * _stylesheet;
}
/// The base URL that was used to load the stylesheet:
@property(nonatomic,strong) NSURL * baseURL;
- (instancetype) init NS_UNAVAILABLE;
/// Initialize the XSL stylesheet from the given URL:
- (instancetype) initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
/// Use the XSL stylesheet to process a string containing XML with a set of arguments.
/// Arguments are typically evaluated by the XSLT processor, so, for example, strings must be passed with an additional set of quotes.
- (NSData *) processDocument:(NSString *)xmlBuffer arguments:(NSDictionary *)arguments;
@end
|
Mark init as being unavailable.
|
Mark init as being unavailable.
|
C
|
mit
|
oriontransfer/SWXMLMapping
|
c
|
## Code Before:
//
// SWXSLTransform.h
// This file is part of the "SWXMLMapping" project, and is distributed under the MIT License.
//
// Created by Samuel Williams on 23/02/12.
// Copyright (c) 2012 Samuel Williams. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SWXSLTransform : NSObject {
NSURL * _baseURL;
void * _stylesheet;
}
/// The base URL that was used to load the stylesheet:
@property(nonatomic,strong) NSURL * baseURL;
/// Initialize the XSL stylesheet from the given URL:
- (instancetype) initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
/// Use the XSL stylesheet to process a string containing XML with a set of arguments.
/// Arguments are typically evaluated by the XSLT processor, so, for example, strings must be passed with an additional set of quotes.
- (NSData *) processDocument:(NSString *)xmlBuffer arguments:(NSDictionary *)arguments;
@end
## Instruction:
Mark init as being unavailable.
## Code After:
//
// SWXSLTransform.h
// This file is part of the "SWXMLMapping" project, and is distributed under the MIT License.
//
// Created by Samuel Williams on 23/02/12.
// Copyright (c) 2012 Samuel Williams. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SWXSLTransform : NSObject {
NSURL * _baseURL;
void * _stylesheet;
}
/// The base URL that was used to load the stylesheet:
@property(nonatomic,strong) NSURL * baseURL;
- (instancetype) init NS_UNAVAILABLE;
/// Initialize the XSL stylesheet from the given URL:
- (instancetype) initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
/// Use the XSL stylesheet to process a string containing XML with a set of arguments.
/// Arguments are typically evaluated by the XSLT processor, so, for example, strings must be passed with an additional set of quotes.
- (NSData *) processDocument:(NSString *)xmlBuffer arguments:(NSDictionary *)arguments;
@end
|
...
/// The base URL that was used to load the stylesheet:
@property(nonatomic,strong) NSURL * baseURL;
- (instancetype) init NS_UNAVAILABLE;
/// Initialize the XSL stylesheet from the given URL:
- (instancetype) initWithURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
...
|
f46226ed4b5a1c0bf2592692aba8481cc777414f
|
exp/views/dashboard.py
|
exp/views/dashboard.py
|
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic
from exp.views.mixins import ExperimenterLoginRequiredMixin
class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView):
'''
ExperimenterDashboard will show a customized view to each user based on the
role and tasks that they perform.
'''
template_name = 'exp/dashboard.html'
def dispatch(self, request, *args, **kwargs):
if not request.user.is_researcher:
return redirect(reverse_lazy('web:home'))
if self.request.path.endswith('/'):
if self.request.user.groups.exists():
# Redirect to manage studies if user has been approved
return redirect(reverse_lazy('exp:study-list'))
return super().dispatch(request, *args, **kwargs)
# If no trailing slash, append slash and redirect.
return redirect(self.request.path + '/')
|
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic
from exp.views.mixins import ExperimenterLoginRequiredMixin
class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView):
'''
ExperimenterDashboard will show a customized view to each user based on the
role and tasks that they perform.
'''
template_name = 'exp/dashboard.html'
def dispatch(self, request, *args, **kwargs):
if hasattr(request.user, 'is_researcher') and not request.user.is_researcher:
return redirect(reverse_lazy('web:home'))
if self.request.path.endswith('/'):
if self.request.user.groups.exists():
# Redirect to manage studies if user has been approved
return redirect(reverse_lazy('exp:study-list'))
return super().dispatch(request, *args, **kwargs)
# If no trailing slash, append slash and redirect.
return redirect(self.request.path + '/')
|
Check if user has is_researcher attribute before accessing it to accommodate AnonymousUser.
|
Check if user has is_researcher attribute before accessing it to accommodate AnonymousUser.
|
Python
|
apache-2.0
|
CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api
|
python
|
## Code Before:
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic
from exp.views.mixins import ExperimenterLoginRequiredMixin
class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView):
'''
ExperimenterDashboard will show a customized view to each user based on the
role and tasks that they perform.
'''
template_name = 'exp/dashboard.html'
def dispatch(self, request, *args, **kwargs):
if not request.user.is_researcher:
return redirect(reverse_lazy('web:home'))
if self.request.path.endswith('/'):
if self.request.user.groups.exists():
# Redirect to manage studies if user has been approved
return redirect(reverse_lazy('exp:study-list'))
return super().dispatch(request, *args, **kwargs)
# If no trailing slash, append slash and redirect.
return redirect(self.request.path + '/')
## Instruction:
Check if user has is_researcher attribute before accessing it to accommodate AnonymousUser.
## Code After:
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic
from exp.views.mixins import ExperimenterLoginRequiredMixin
class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView):
'''
ExperimenterDashboard will show a customized view to each user based on the
role and tasks that they perform.
'''
template_name = 'exp/dashboard.html'
def dispatch(self, request, *args, **kwargs):
if hasattr(request.user, 'is_researcher') and not request.user.is_researcher:
return redirect(reverse_lazy('web:home'))
if self.request.path.endswith('/'):
if self.request.user.groups.exists():
# Redirect to manage studies if user has been approved
return redirect(reverse_lazy('exp:study-list'))
return super().dispatch(request, *args, **kwargs)
# If no trailing slash, append slash and redirect.
return redirect(self.request.path + '/')
|
# ... existing code ...
template_name = 'exp/dashboard.html'
def dispatch(self, request, *args, **kwargs):
if hasattr(request.user, 'is_researcher') and not request.user.is_researcher:
return redirect(reverse_lazy('web:home'))
if self.request.path.endswith('/'):
if self.request.user.groups.exists():
# ... rest of the code ...
|
b3a3beb56fb56e812cd0308eb184c79a0fa97e5a
|
include/HubFramework.h
|
include/HubFramework.h
|
/// Umbrella header for the Hub Framework
#import "HUBManager.h"
#import "HUBComponent.h"
#import "HUBComponentModel.h"
#import "HUBComponentRegistry.h"
#import "HUBComponentFallbackHandler.h"
|
/// Umbrella header for the Hub Framework
#import "HUBManager.h"
#import "HUBComponent.h"
#import "HUBComponentModel.h"
#import "HUBComponentModelBuilder.h"
#import "HUBComponentImageData.h"
#import "HUBComponentImageDataBuilder.h"
#import "HUBComponentRegistry.h"
#import "HUBComponentFallbackHandler.h"
|
Add new API files to umbrella header
|
Add new API files to umbrella header
|
C
|
apache-2.0
|
spotify/HubFramework,spotify/HubFramework,spotify/HubFramework,spotify/HubFramework
|
c
|
## Code Before:
/// Umbrella header for the Hub Framework
#import "HUBManager.h"
#import "HUBComponent.h"
#import "HUBComponentModel.h"
#import "HUBComponentRegistry.h"
#import "HUBComponentFallbackHandler.h"
## Instruction:
Add new API files to umbrella header
## Code After:
/// Umbrella header for the Hub Framework
#import "HUBManager.h"
#import "HUBComponent.h"
#import "HUBComponentModel.h"
#import "HUBComponentModelBuilder.h"
#import "HUBComponentImageData.h"
#import "HUBComponentImageDataBuilder.h"
#import "HUBComponentRegistry.h"
#import "HUBComponentFallbackHandler.h"
|
// ... existing code ...
#import "HUBManager.h"
#import "HUBComponent.h"
#import "HUBComponentModel.h"
#import "HUBComponentModelBuilder.h"
#import "HUBComponentImageData.h"
#import "HUBComponentImageDataBuilder.h"
#import "HUBComponentRegistry.h"
#import "HUBComponentFallbackHandler.h"
// ... rest of the code ...
|
62ebb94f09ea2dee3276041bd471502d57078650
|
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
|
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
|
import re
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestMcrouterToMcrouterTko(McrouterTestCase):
config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']
def setUp(self):
self.underlying_mcr = self.add_mcrouter(self.config,
extra_args=self.extra_args, bg_mcrouter=True)
def get_mcrouter(self):
return self.add_mcrouter(self.config, extra_args=self.extra_args)
def test_underlying_tko(self):
mcr = self.get_mcrouter()
self.assertFalse(mcr.delete("key"))
stats = self.underlying_mcr.stats("suspect_servers")
print(stats)
self.assertEqual(1, len(stats))
self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))
stats = mcr.stats("suspect_servers")
self.assertEqual(0, len(stats))
|
import re
import time
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestMcrouterToMcrouterTko(McrouterTestCase):
config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']
def setUp(self):
self.underlying_mcr = self.add_mcrouter(self.config,
extra_args=self.extra_args, bg_mcrouter=True)
def get_mcrouter(self):
return self.add_mcrouter(self.config, extra_args=self.extra_args)
def test_underlying_tko(self):
mcr = self.get_mcrouter()
self.assertFalse(mcr.delete("key"))
retries = 10
while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0:
retries = retries - 1
time.sleep(1)
stats = self.underlying_mcr.stats("suspect_servers")
print(stats)
self.assertEqual(1, len(stats))
self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))
stats = mcr.stats("suspect_servers")
self.assertEqual(0, len(stats))
|
Fix flaky mcrouter tko tests
|
Fix flaky mcrouter tko tests
Summary: As above
Reviewed By: edenzik
Differential Revision: D25722019
fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed
|
Python
|
mit
|
facebook/mcrouter,facebook/mcrouter,facebook/mcrouter,facebook/mcrouter
|
python
|
## Code Before:
import re
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestMcrouterToMcrouterTko(McrouterTestCase):
config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']
def setUp(self):
self.underlying_mcr = self.add_mcrouter(self.config,
extra_args=self.extra_args, bg_mcrouter=True)
def get_mcrouter(self):
return self.add_mcrouter(self.config, extra_args=self.extra_args)
def test_underlying_tko(self):
mcr = self.get_mcrouter()
self.assertFalse(mcr.delete("key"))
stats = self.underlying_mcr.stats("suspect_servers")
print(stats)
self.assertEqual(1, len(stats))
self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))
stats = mcr.stats("suspect_servers")
self.assertEqual(0, len(stats))
## Instruction:
Fix flaky mcrouter tko tests
Summary: As above
Reviewed By: edenzik
Differential Revision: D25722019
fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed
## Code After:
import re
import time
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestMcrouterToMcrouterTko(McrouterTestCase):
config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']
def setUp(self):
self.underlying_mcr = self.add_mcrouter(self.config,
extra_args=self.extra_args, bg_mcrouter=True)
def get_mcrouter(self):
return self.add_mcrouter(self.config, extra_args=self.extra_args)
def test_underlying_tko(self):
mcr = self.get_mcrouter()
self.assertFalse(mcr.delete("key"))
retries = 10
while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0:
retries = retries - 1
time.sleep(1)
stats = self.underlying_mcr.stats("suspect_servers")
print(stats)
self.assertEqual(1, len(stats))
self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))
stats = mcr.stats("suspect_servers")
self.assertEqual(0, len(stats))
|
// ... existing code ...
import re
import time
from mcrouter.test.McrouterTestCase import McrouterTestCase
// ... modified code ...
self.assertFalse(mcr.delete("key"))
retries = 10
while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0:
retries = retries - 1
time.sleep(1)
stats = self.underlying_mcr.stats("suspect_servers")
print(stats)
self.assertEqual(1, len(stats))
// ... rest of the code ...
|
b3b216a95c4254302776fdbb67bab948ba12d3d3
|
ddsc_worker/tasks.py
|
ddsc_worker/tasks.py
|
from __future__ import absolute_import
from ddsc_worker.celery import celery
@celery.task
def add(x, y):
return x + y
@celery.task
def mul(x, y):
return x + y
|
from __future__ import absolute_import
from ddsc_worker.celery import celery
import time
@celery.task
def add(x, y):
time.sleep(10)
return x + y
@celery.task
def mul(x, y):
time.sleep(2)
return x * y
|
Add sleep to simulate work
|
Add sleep to simulate work
|
Python
|
mit
|
ddsc/ddsc-worker
|
python
|
## Code Before:
from __future__ import absolute_import
from ddsc_worker.celery import celery
@celery.task
def add(x, y):
return x + y
@celery.task
def mul(x, y):
return x + y
## Instruction:
Add sleep to simulate work
## Code After:
from __future__ import absolute_import
from ddsc_worker.celery import celery
import time
@celery.task
def add(x, y):
time.sleep(10)
return x + y
@celery.task
def mul(x, y):
time.sleep(2)
return x * y
|
...
from __future__ import absolute_import
from ddsc_worker.celery import celery
import time
@celery.task
def add(x, y):
time.sleep(10)
return x + y
@celery.task
def mul(x, y):
time.sleep(2)
return x * y
...
|
911437d633cca4bbd83b87a22e190f25686afe4e
|
software/cananolab-webapp/src/gov/nih/nci/cananolab/restful/view/edit/SimpleInstrumentBean.java
|
software/cananolab-webapp/src/gov/nih/nci/cananolab/restful/view/edit/SimpleInstrumentBean.java
|
package gov.nih.nci.cananolab.restful.view.edit;
public class SimpleInstrumentBean {
String manufacturer;
String modelName;
String type;
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package gov.nih.nci.cananolab.restful.view.edit;
public class SimpleInstrumentBean {
String manufacturer = "";
String modelName = "";
String type = "";
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
if (manufacturer != null)
this.manufacturer = manufacturer;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
if (modelName != null)
this.modelName = modelName;
}
public String getType() {
return type;
}
public void setType(String type) {
if (type != null)
this.type = type;
}
}
|
Make sure type doesn't have null value. Otherwise, got hibernate error
|
Make sure type doesn't have null value. Otherwise, got hibernate error
|
Java
|
bsd-3-clause
|
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
java
|
## Code Before:
package gov.nih.nci.cananolab.restful.view.edit;
public class SimpleInstrumentBean {
String manufacturer;
String modelName;
String type;
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
## Instruction:
Make sure type doesn't have null value. Otherwise, got hibernate error
## Code After:
package gov.nih.nci.cananolab.restful.view.edit;
public class SimpleInstrumentBean {
String manufacturer = "";
String modelName = "";
String type = "";
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
if (manufacturer != null)
this.manufacturer = manufacturer;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
if (modelName != null)
this.modelName = modelName;
}
public String getType() {
return type;
}
public void setType(String type) {
if (type != null)
this.type = type;
}
}
|
// ... existing code ...
public class SimpleInstrumentBean {
String manufacturer = "";
String modelName = "";
String type = "";
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
if (manufacturer != null)
this.manufacturer = manufacturer;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
if (modelName != null)
this.modelName = modelName;
}
public String getType() {
return type;
}
public void setType(String type) {
if (type != null)
this.type = type;
}
// ... rest of the code ...
|
532059d32b79e5c560142e4d1de67330361cc5f2
|
examples/ffi-struct/struct.c
|
examples/ffi-struct/struct.c
|
struct Inner
{
int x;
};
struct Outer
{
struct Inner inner_embed;
struct Inner* inner_var;
};
void modify_via_outer(struct Outer* s)
{
s->inner_embed.x = 10;
s->inner_var->x = 15;
}
void modify_inner(struct Inner* s)
{
s->x = 5;
}
|
typedef struct Inner
{
int x;
} Inner;
typedef struct Outer
{
struct Inner inner_embed;
struct Inner* inner_var;
} Outer;
void modify_via_outer(Outer* s)
{
s->inner_embed.x = 10;
s->inner_var->x = 15;
}
void modify_inner(Inner* s)
{
s->x = 5;
}
|
Fix C file coding style
|
Fix C file coding style
|
C
|
bsd-2-clause
|
jupvfranco/ponyc,cquinn/ponyc,Theodus/ponyc,jupvfranco/ponyc,mkfifo/ponyc,Praetonus/ponyc,Theodus/ponyc,Praetonus/ponyc,mkfifo/ponyc,ryanai3/ponyc,Perelandric/ponyc,lukecheeseman/ponyta,kulibali/ponyc,ryanai3/ponyc,jupvfranco/ponyc,malthe/ponyc,Theodus/ponyc,ponylang/ponyc,jupvfranco/ponyc,dipinhora/ponyc,mkfifo/ponyc,Praetonus/ponyc,sgebbie/ponyc,dipinhora/ponyc,sgebbie/ponyc,Perelandric/ponyc,CausalityLtd/ponyc,boemmels/ponyc,malthe/ponyc,cquinn/ponyc,Perelandric/ponyc,jemc/ponyc,boemmels/ponyc,boemmels/ponyc,boemmels/ponyc,boemmels/ponyc,lukecheeseman/ponyta,Perelandric/ponyc,jemc/ponyc,CausalityLtd/ponyc,mkfifo/ponyc,ponylang/ponyc,mkfifo/ponyc,cquinn/ponyc,dipinhora/ponyc,jemc/ponyc,kulibali/ponyc,ponylang/ponyc,Theodus/ponyc,sgebbie/ponyc,Theodus/ponyc,kulibali/ponyc,doublec/ponyc,doublec/ponyc,CausalityLtd/ponyc,doublec/ponyc,sgebbie/ponyc,Praetonus/ponyc,Perelandric/ponyc,cquinn/ponyc,malthe/ponyc,malthe/ponyc,lukecheeseman/ponyta,kulibali/ponyc,ryanai3/ponyc,sgebbie/ponyc,jupvfranco/ponyc
|
c
|
## Code Before:
struct Inner
{
int x;
};
struct Outer
{
struct Inner inner_embed;
struct Inner* inner_var;
};
void modify_via_outer(struct Outer* s)
{
s->inner_embed.x = 10;
s->inner_var->x = 15;
}
void modify_inner(struct Inner* s)
{
s->x = 5;
}
## Instruction:
Fix C file coding style
## Code After:
typedef struct Inner
{
int x;
} Inner;
typedef struct Outer
{
struct Inner inner_embed;
struct Inner* inner_var;
} Outer;
void modify_via_outer(Outer* s)
{
s->inner_embed.x = 10;
s->inner_var->x = 15;
}
void modify_inner(Inner* s)
{
s->x = 5;
}
|
# ... existing code ...
typedef struct Inner
{
int x;
} Inner;
typedef struct Outer
{
struct Inner inner_embed;
struct Inner* inner_var;
} Outer;
void modify_via_outer(Outer* s)
{
s->inner_embed.x = 10;
s->inner_var->x = 15;
}
void modify_inner(Inner* s)
{
s->x = 5;
}
# ... rest of the code ...
|
64038fad35e7a1b9756921a79b6b13d59925e682
|
tests/test_endpoints.py
|
tests/test_endpoints.py
|
import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
self.assertEqual(self.client.root.endpoint, "/v1/")
|
import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
self.assertEqual(self.client.root.endpoint, "/v1/")
def test_base_endpoints(self):
self.assertEqual(self.client.validation.phases.endpoint, "/v1/phases")
self.assertEqual(self.client.validation.groupRounds.endpoint, '/v1/grouprounds')
self.assertEqual(self.client.validation.knockoutRounds.endpoint, '/v1/knockoutrounds')
self.assertEqual(self.client.validation.confederations.endpoint, '/v1/confederations')
self.assertEqual(self.client.validation.countries.endpoint, '/v1/countries')
self.assertEqual(self.client.validation.seasons.endpoint, '/v1/seasons')
self.assertEqual(self.client.validation.teams.endpoint, '/v1/teams')
self.assertEqual(self.client.validation.venues.endpoint, '/v1/venues')
self.assertEqual(self.client.validation.timezones.endpoint, '/v1/timezones')
self.assertEqual(self.client.validation.persons.endpoint, '/v1/persons')
self.assertEqual(self.client.validation.positions.endpoint, '/v1/positions')
self.assertEqual(self.client.validation.fouls.endpoint, '/v1/fouls')
self.assertEqual(self.client.validation.cards.endpoint, '/v1/cards')
self.assertEqual(self.client.validation.bodyparts.endpoint, '/v1/bodyparts')
self.assertEqual(self.client.validation.shotevents.endpoint, '/v1/shotevents')
self.assertEqual(self.client.validation.penaltyOutcomes.endpoint, '/v1/penalty_outcomes')
self.assertEqual(self.client.validation.weather.endpoint, '/v1/weather')
self.assertEqual(self.client.validation.surfaces.endpoint, '/v1/surfaces')
def test_personnel_endpoints(self):
self.assertEqual(self.client.players.endpoint, '/v1/personnel/players')
self.assertEqual(self.client.managers.endpoint, '/v1/personnel/managers')
self.assertEqual(self.client.referees.endpoint, '/v1/personnel/referees')
|
Expand test on URL endpoints in API client
|
Expand test on URL endpoints in API client
|
Python
|
mit
|
soccermetrics/soccermetrics-client-py
|
python
|
## Code Before:
import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
self.assertEqual(self.client.root.endpoint, "/v1/")
## Instruction:
Expand test on URL endpoints in API client
## Code After:
import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
self.assertEqual(self.client.root.endpoint, "/v1/")
def test_base_endpoints(self):
self.assertEqual(self.client.validation.phases.endpoint, "/v1/phases")
self.assertEqual(self.client.validation.groupRounds.endpoint, '/v1/grouprounds')
self.assertEqual(self.client.validation.knockoutRounds.endpoint, '/v1/knockoutrounds')
self.assertEqual(self.client.validation.confederations.endpoint, '/v1/confederations')
self.assertEqual(self.client.validation.countries.endpoint, '/v1/countries')
self.assertEqual(self.client.validation.seasons.endpoint, '/v1/seasons')
self.assertEqual(self.client.validation.teams.endpoint, '/v1/teams')
self.assertEqual(self.client.validation.venues.endpoint, '/v1/venues')
self.assertEqual(self.client.validation.timezones.endpoint, '/v1/timezones')
self.assertEqual(self.client.validation.persons.endpoint, '/v1/persons')
self.assertEqual(self.client.validation.positions.endpoint, '/v1/positions')
self.assertEqual(self.client.validation.fouls.endpoint, '/v1/fouls')
self.assertEqual(self.client.validation.cards.endpoint, '/v1/cards')
self.assertEqual(self.client.validation.bodyparts.endpoint, '/v1/bodyparts')
self.assertEqual(self.client.validation.shotevents.endpoint, '/v1/shotevents')
self.assertEqual(self.client.validation.penaltyOutcomes.endpoint, '/v1/penalty_outcomes')
self.assertEqual(self.client.validation.weather.endpoint, '/v1/weather')
self.assertEqual(self.client.validation.surfaces.endpoint, '/v1/surfaces')
def test_personnel_endpoints(self):
self.assertEqual(self.client.players.endpoint, '/v1/personnel/players')
self.assertEqual(self.client.managers.endpoint, '/v1/personnel/managers')
self.assertEqual(self.client.referees.endpoint, '/v1/personnel/referees')
|
...
def test_service_root(self):
self.assertEqual(self.client.root.endpoint, "/v1/")
def test_base_endpoints(self):
self.assertEqual(self.client.validation.phases.endpoint, "/v1/phases")
self.assertEqual(self.client.validation.groupRounds.endpoint, '/v1/grouprounds')
self.assertEqual(self.client.validation.knockoutRounds.endpoint, '/v1/knockoutrounds')
self.assertEqual(self.client.validation.confederations.endpoint, '/v1/confederations')
self.assertEqual(self.client.validation.countries.endpoint, '/v1/countries')
self.assertEqual(self.client.validation.seasons.endpoint, '/v1/seasons')
self.assertEqual(self.client.validation.teams.endpoint, '/v1/teams')
self.assertEqual(self.client.validation.venues.endpoint, '/v1/venues')
self.assertEqual(self.client.validation.timezones.endpoint, '/v1/timezones')
self.assertEqual(self.client.validation.persons.endpoint, '/v1/persons')
self.assertEqual(self.client.validation.positions.endpoint, '/v1/positions')
self.assertEqual(self.client.validation.fouls.endpoint, '/v1/fouls')
self.assertEqual(self.client.validation.cards.endpoint, '/v1/cards')
self.assertEqual(self.client.validation.bodyparts.endpoint, '/v1/bodyparts')
self.assertEqual(self.client.validation.shotevents.endpoint, '/v1/shotevents')
self.assertEqual(self.client.validation.penaltyOutcomes.endpoint, '/v1/penalty_outcomes')
self.assertEqual(self.client.validation.weather.endpoint, '/v1/weather')
self.assertEqual(self.client.validation.surfaces.endpoint, '/v1/surfaces')
def test_personnel_endpoints(self):
self.assertEqual(self.client.players.endpoint, '/v1/personnel/players')
self.assertEqual(self.client.managers.endpoint, '/v1/personnel/managers')
self.assertEqual(self.client.referees.endpoint, '/v1/personnel/referees')
...
|
567aa141546c905b842949799474742bf171a445
|
codegolf/__init__.py
|
codegolf/__init__.py
|
from flask import Flask
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
from codegolf import views
|
from flask import Flask
import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
Session = sa.sessionmaker(bind=engine)
# instantiate Session to do things.
# I might write some nice Flask extension here, but I don't want to use flask_sqlalchemy
from codegolf import views
|
Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
|
Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
|
Python
|
mit
|
UQComputingSociety/codegolf,UQComputingSociety/codegolf,UQComputingSociety/codegolf
|
python
|
## Code Before:
from flask import Flask
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
from codegolf import views
## Instruction:
Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
## Code After:
from flask import Flask
import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
Session = sa.sessionmaker(bind=engine)
# instantiate Session to do things.
# I might write some nice Flask extension here, but I don't want to use flask_sqlalchemy
from codegolf import views
|
# ... existing code ...
from flask import Flask
import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
Session = sa.sessionmaker(bind=engine)
# instantiate Session to do things.
# I might write some nice Flask extension here, but I don't want to use flask_sqlalchemy
from codegolf import views
# ... rest of the code ...
|
a727161f67edff10bb94785e70add7c42ba99dcc
|
morepath/tests/test_app.py
|
morepath/tests/test_app.py
|
from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
|
from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
def test_app_name():
app = morepath.App(name='foo')
assert repr(app) == "<morepath.App 'foo'>"
|
Add coverage of __repr__ of app.
|
Add coverage of __repr__ of app.
|
Python
|
bsd-3-clause
|
morepath/morepath,faassen/morepath,taschini/morepath
|
python
|
## Code Before:
from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
## Instruction:
Add coverage of __repr__ of app.
## Code After:
from morepath.app import App, global_app
import morepath
def setup_module(module):
morepath.disable_implicit()
def test_global_app():
assert global_app.extends == []
assert global_app.name == 'global_app'
def test_app_without_extends():
myapp = App()
assert myapp.extends == [global_app]
assert myapp.name == ''
def test_app_with_extends():
parentapp = App()
myapp = App('myapp', extends=parentapp)
assert myapp.extends == [parentapp]
assert myapp.name == 'myapp'
def test_app_caching_lookup():
class MockClassLookup(object):
called = 0
def all(self, key, classes):
self.called += 1
return ["answer"]
class MockApp(MockClassLookup, App):
pass
myapp = MockApp()
lookup = myapp.lookup
answer = lookup.component('foo', [])
assert answer == 'answer'
assert myapp.called == 1
# after this the answer will be cached for those parameters
answer = lookup.component('foo', [])
assert myapp.called == 1
answer = myapp.lookup.component('foo', [])
assert myapp.called == 1
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
def test_app_name():
app = morepath.App(name='foo')
assert repr(app) == "<morepath.App 'foo'>"
|
// ... existing code ...
# but different parameters does trigger another call
lookup.component('bar', [])
assert myapp.called == 2
def test_app_name():
app = morepath.App(name='foo')
assert repr(app) == "<morepath.App 'foo'>"
// ... rest of the code ...
|
5f8d59646875d4e4aa75ec22a2ddc666c1802a23
|
readthedocs/core/utils/tasks/__init__.py
|
readthedocs/core/utils/tasks/__init__.py
|
from .permission_checks import user_id_matches
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
from .retrieve import get_task_data
|
from .permission_checks import user_id_matches
from .public import PublicTask
from .public import TaskNoPermission
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
from .retrieve import get_task_data
|
Revert previous commit by adding missing imports
|
Revert previous commit by adding missing imports
|
Python
|
mit
|
rtfd/readthedocs.org,tddv/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,pombredanne/readthedocs.org,pombredanne/readthedocs.org,pombredanne/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,davidfischer/readthedocs.org,tddv/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,rtfd/readthedocs.org,safwanrahman/readthedocs.org
|
python
|
## Code Before:
from .permission_checks import user_id_matches
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
from .retrieve import get_task_data
## Instruction:
Revert previous commit by adding missing imports
## Code After:
from .permission_checks import user_id_matches
from .public import PublicTask
from .public import TaskNoPermission
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
from .retrieve import get_task_data
|
// ... existing code ...
from .permission_checks import user_id_matches
from .public import PublicTask
from .public import TaskNoPermission
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
// ... rest of the code ...
|
61c0334c7115422c1806d8224b326284c236aae1
|
assignment3/src/assignment3/LinkedList.java
|
assignment3/src/assignment3/LinkedList.java
|
package assignment3;
public class LinkedList {
private Nodes root = null;
public boolean findNode(Nodes node){
if(node==null) return false;
Nodes currentNode = root;
while(currentNode.getName()!= node.getName())
{
currentNode = currentNode.getNext();
if(currentNode == null)
return false;
}
return true;
}
public void iterate(){
System.out.println("Iterate forward...");
Nodes temp = root;
while(temp!=null){
System.out.println(temp.toString());
temp = temp.getNext();
}
}
}
|
package assignment3;
public class LinkedList {
private Nodes root = null;
public boolean findNode(Nodes node){
if(node==null) return false;
Nodes currentNode = root;
while(currentNode.getName()!= node.getName())
{
currentNode = currentNode.getNext();
if(currentNode == null)
return false;
}
return true;
}
public void iterate(){
System.out.println("Iterate forward...");
Nodes temp = root;
while(temp!=null){
System.out.println(temp.toString());
temp = temp.getNext();
}
}
public boolean remove(Nodes node){
return false;
}
}
|
Add delete a node option
|
Add delete a node option
|
Java
|
epl-1.0
|
tonyrojsirilawan/assignment3
|
java
|
## Code Before:
package assignment3;
public class LinkedList {
private Nodes root = null;
public boolean findNode(Nodes node){
if(node==null) return false;
Nodes currentNode = root;
while(currentNode.getName()!= node.getName())
{
currentNode = currentNode.getNext();
if(currentNode == null)
return false;
}
return true;
}
public void iterate(){
System.out.println("Iterate forward...");
Nodes temp = root;
while(temp!=null){
System.out.println(temp.toString());
temp = temp.getNext();
}
}
}
## Instruction:
Add delete a node option
## Code After:
package assignment3;
public class LinkedList {
private Nodes root = null;
public boolean findNode(Nodes node){
if(node==null) return false;
Nodes currentNode = root;
while(currentNode.getName()!= node.getName())
{
currentNode = currentNode.getNext();
if(currentNode == null)
return false;
}
return true;
}
public void iterate(){
System.out.println("Iterate forward...");
Nodes temp = root;
while(temp!=null){
System.out.println(temp.toString());
temp = temp.getNext();
}
}
public boolean remove(Nodes node){
return false;
}
}
|
// ... existing code ...
}
}
public boolean remove(Nodes node){
return false;
}
}
// ... rest of the code ...
|
c9215a00bfe8d1edaf2840f6cd4b3ae8061c26f5
|
allauth_uwum/provider.py
|
allauth_uwum/provider.py
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
Set "notify_email" in default scope only if settings allow it
|
Set "notify_email" in default scope only if settings allow it
|
Python
|
mit
|
ExCiteS/django-allauth-uwum
|
python
|
## Code Before:
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
## Instruction:
Set "notify_email" in default scope only if settings allow it
## Code After:
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
// ... existing code ...
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
// ... rest of the code ...
|
a4e7d742d66ed4fa4f5d0af9c57a2e5c5026d976
|
content/public/browser/notification_observer.h
|
content/public/browser/notification_observer.h
|
// Copyright (c) 2012 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_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#define CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#pragma once
#include "content/common/content_export.h"
namespace content {
class NotificationDetails;
class NotificationSource;
// This is the base class for notification observers. When a matching
// notification is posted to the notification service, Observe is called.
class CONTENT_EXPORT NotificationObserver {
public:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) = 0;
protected:
NotificationObserver() {}
virtual ~NotificationObserver() {}
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
|
// Copyright (c) 2012 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_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#define CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#pragma once
#include "content/common/content_export.h"
namespace content {
class NotificationDetails;
class NotificationSource;
// This is the base class for notification observers. When a matching
// notification is posted to the notification service, Observe is called.
class CONTENT_EXPORT NotificationObserver {
public:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) = 0;
protected:
virtual ~NotificationObserver() {}
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
|
Remove unnecessary constructor from NotificationObserver.
|
content: Remove unnecessary constructor from NotificationObserver.
BUG=98716
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10449076
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@139931 0039d316-1c4b-4281-b951-d872f2087c98
|
C
|
bsd-3-clause
|
nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,dednal/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,ltilve/chromium,ltilve/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,zcbenz/cefode-chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,keishi/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,littlstar/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,dednal/chromium.src,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,M4sse/chromium.src,ltilve/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,dednal/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,keishi/chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,anirudhSK/chromium,anirudhSK/chromium,patrickm/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,patrickm/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,zcbenz/cefode-chromium,keishi/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,keishi/chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish
|
c
|
## Code Before:
// Copyright (c) 2012 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_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#define CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#pragma once
#include "content/common/content_export.h"
namespace content {
class NotificationDetails;
class NotificationSource;
// This is the base class for notification observers. When a matching
// notification is posted to the notification service, Observe is called.
class CONTENT_EXPORT NotificationObserver {
public:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) = 0;
protected:
NotificationObserver() {}
virtual ~NotificationObserver() {}
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
## Instruction:
content: Remove unnecessary constructor from NotificationObserver.
BUG=98716
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10449076
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@139931 0039d316-1c4b-4281-b951-d872f2087c98
## Code After:
// Copyright (c) 2012 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_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#define CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
#pragma once
#include "content/common/content_export.h"
namespace content {
class NotificationDetails;
class NotificationSource;
// This is the base class for notification observers. When a matching
// notification is posted to the notification service, Observe is called.
class CONTENT_EXPORT NotificationObserver {
public:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) = 0;
protected:
virtual ~NotificationObserver() {}
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_NOTIFICATION_OBSERVER_H_
|
// ... existing code ...
const NotificationDetails& details) = 0;
protected:
virtual ~NotificationObserver() {}
};
// ... rest of the code ...
|
0c293a54874e708538f7564d48eb160c71f2ebfa
|
library/src/main/java/com/novoda/downloadmanager/CallbackThrottleByTime.java
|
library/src/main/java/com/novoda/downloadmanager/CallbackThrottleByTime.java
|
package com.novoda.downloadmanager;
import java.util.Timer;
import java.util.TimerTask;
class CallbackThrottleByTime implements CallbackThrottle {
private final long periodInMillis;
private static final long DELAY = 0;
private DownloadBatchStatus downloadBatchStatus;
private Timer timer;
private TimerTask timerTask;
private DownloadBatchCallback callback;
CallbackThrottleByTime(long periodInMillis) {
this.periodInMillis = periodInMillis;
}
@Override
public void setCallback(final DownloadBatchCallback callback) {
this.callback = callback;
timerTask = new TimerTask() {
@Override
public void run() {
callback.onUpdate(downloadBatchStatus);
}
};
}
@Override
public void update(DownloadBatchStatus downloadBatchStatus) {
if (timerTask == null) {
return;
}
this.downloadBatchStatus = downloadBatchStatus;
startUpdateIfNecessary();
}
private void startUpdateIfNecessary() {
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, DELAY, periodInMillis);
}
}
@Override
public void stopUpdates() {
if (callback != null) {
callback.onUpdate(downloadBatchStatus);
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
|
package com.novoda.downloadmanager;
import java.util.Timer;
import java.util.TimerTask;
class CallbackThrottleByTime implements CallbackThrottle {
private static final long DELAY_IN_MILLIS = 0;
private DownloadBatchStatus downloadBatchStatus;
private Timer timer;
private TimerTask timerTask;
private final long periodInMillis;
private DownloadBatchCallback callback;
CallbackThrottleByTime(long periodInMillis) {
this.periodInMillis = periodInMillis;
}
@Override
public void setCallback(final DownloadBatchCallback callback) {
this.callback = callback;
timerTask = new TimerTask() {
@Override
public void run() {
callback.onUpdate(downloadBatchStatus);
}
};
}
@Override
public void update(DownloadBatchStatus downloadBatchStatus) {
if (timerTask == null) {
return;
}
this.downloadBatchStatus = downloadBatchStatus;
startUpdateIfNecessary();
}
private void startUpdateIfNecessary() {
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, DELAY_IN_MILLIS, periodInMillis);
}
}
@Override
public void stopUpdates() {
if (callback != null) {
callback.onUpdate(downloadBatchStatus);
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
|
Add time unit to DELAY.
|
Add time unit to DELAY.
|
Java
|
apache-2.0
|
novoda/download-manager
|
java
|
## Code Before:
package com.novoda.downloadmanager;
import java.util.Timer;
import java.util.TimerTask;
class CallbackThrottleByTime implements CallbackThrottle {
private final long periodInMillis;
private static final long DELAY = 0;
private DownloadBatchStatus downloadBatchStatus;
private Timer timer;
private TimerTask timerTask;
private DownloadBatchCallback callback;
CallbackThrottleByTime(long periodInMillis) {
this.periodInMillis = periodInMillis;
}
@Override
public void setCallback(final DownloadBatchCallback callback) {
this.callback = callback;
timerTask = new TimerTask() {
@Override
public void run() {
callback.onUpdate(downloadBatchStatus);
}
};
}
@Override
public void update(DownloadBatchStatus downloadBatchStatus) {
if (timerTask == null) {
return;
}
this.downloadBatchStatus = downloadBatchStatus;
startUpdateIfNecessary();
}
private void startUpdateIfNecessary() {
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, DELAY, periodInMillis);
}
}
@Override
public void stopUpdates() {
if (callback != null) {
callback.onUpdate(downloadBatchStatus);
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
## Instruction:
Add time unit to DELAY.
## Code After:
package com.novoda.downloadmanager;
import java.util.Timer;
import java.util.TimerTask;
class CallbackThrottleByTime implements CallbackThrottle {
private static final long DELAY_IN_MILLIS = 0;
private DownloadBatchStatus downloadBatchStatus;
private Timer timer;
private TimerTask timerTask;
private final long periodInMillis;
private DownloadBatchCallback callback;
CallbackThrottleByTime(long periodInMillis) {
this.periodInMillis = periodInMillis;
}
@Override
public void setCallback(final DownloadBatchCallback callback) {
this.callback = callback;
timerTask = new TimerTask() {
@Override
public void run() {
callback.onUpdate(downloadBatchStatus);
}
};
}
@Override
public void update(DownloadBatchStatus downloadBatchStatus) {
if (timerTask == null) {
return;
}
this.downloadBatchStatus = downloadBatchStatus;
startUpdateIfNecessary();
}
private void startUpdateIfNecessary() {
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, DELAY_IN_MILLIS, periodInMillis);
}
}
@Override
public void stopUpdates() {
if (callback != null) {
callback.onUpdate(downloadBatchStatus);
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
|
# ... existing code ...
class CallbackThrottleByTime implements CallbackThrottle {
private static final long DELAY_IN_MILLIS = 0;
private DownloadBatchStatus downloadBatchStatus;
private Timer timer;
private TimerTask timerTask;
private final long periodInMillis;
private DownloadBatchCallback callback;
CallbackThrottleByTime(long periodInMillis) {
# ... modified code ...
private void startUpdateIfNecessary() {
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, DELAY_IN_MILLIS, periodInMillis);
}
}
# ... rest of the code ...
|
abd31a208639f0be773f35d1c161fe7fdcb138db
|
src/main/entity/components/SkillComponent.h
|
src/main/entity/components/SkillComponent.h
|
/**
* Data structure to represent an Entity's skill.
*/
typedef struct
{
int ranks; ///< Current ranks in the skill
int xp; ///< Amount of XP earned towards next rank
} SkillComponent;
/**
* Enumeration for identifying different skills.
*/
enum skill_t {
NOSKILL,
Melee,
Swords,
BastardSword,
Maces,
SpikedMace,
FirstAid
};
/**
* This array defines our parent skill relationships.
*
* If a skill's parent is NOSKILL, it has no parent.
*/
const skill_t* PARENT_SKILLS = { NOSKILL, NOSKILL, Melee, Swords, Melee, Maces, NOSKILL };
#endif
|
/**
* Data structure to represent an Entity's skill.
*/
typedef struct
{
int ranks; ///< Current ranks in the skill
int xp; ///< Amount of XP earned towards next rank
} SkillComponent;
/**
* Enumeration for identifying different skills.
*/
enum skill_t {
Melee,
Swords,
BastardSword,
Maces,
SpikedMace,
FirstAid
};
/**
* This array defines our parent skill relationships.
*
* If a skill's parent is itself, it has no parent.
*/
const skill_t PARENT_SKILLS[] = { Melee, Melee, Swords, Melee, Maces, FirstAid };
#endif
|
Fix PARENT_SKILLS declaration; remove NOSKILL
|
Fix PARENT_SKILLS declaration; remove NOSKILL
Why would anyone want to be unskilled anyway?
|
C
|
mit
|
Kromey/roglick
|
c
|
## Code Before:
/**
* Data structure to represent an Entity's skill.
*/
typedef struct
{
int ranks; ///< Current ranks in the skill
int xp; ///< Amount of XP earned towards next rank
} SkillComponent;
/**
* Enumeration for identifying different skills.
*/
enum skill_t {
NOSKILL,
Melee,
Swords,
BastardSword,
Maces,
SpikedMace,
FirstAid
};
/**
* This array defines our parent skill relationships.
*
* If a skill's parent is NOSKILL, it has no parent.
*/
const skill_t* PARENT_SKILLS = { NOSKILL, NOSKILL, Melee, Swords, Melee, Maces, NOSKILL };
#endif
## Instruction:
Fix PARENT_SKILLS declaration; remove NOSKILL
Why would anyone want to be unskilled anyway?
## Code After:
/**
* Data structure to represent an Entity's skill.
*/
typedef struct
{
int ranks; ///< Current ranks in the skill
int xp; ///< Amount of XP earned towards next rank
} SkillComponent;
/**
* Enumeration for identifying different skills.
*/
enum skill_t {
Melee,
Swords,
BastardSword,
Maces,
SpikedMace,
FirstAid
};
/**
* This array defines our parent skill relationships.
*
* If a skill's parent is itself, it has no parent.
*/
const skill_t PARENT_SKILLS[] = { Melee, Melee, Swords, Melee, Maces, FirstAid };
#endif
|
# ... existing code ...
* Enumeration for identifying different skills.
*/
enum skill_t {
Melee,
Swords,
BastardSword,
# ... modified code ...
/**
* This array defines our parent skill relationships.
*
* If a skill's parent is itself, it has no parent.
*/
const skill_t PARENT_SKILLS[] = { Melee, Melee, Swords, Melee, Maces, FirstAid };
#endif
# ... rest of the code ...
|
31d43423ffede992fc53fef1e9b07d591fa4f8e0
|
src/main/resources/archetype-resources/src/main/java/__name__Plugin.java
|
src/main/resources/archetype-resources/src/main/java/__name__Plugin.java
|
package ${package};
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
public class ${name}Plugin extends JavaPlugin {
@Override
public void onEnable() {
log("Hello world!");
}
@Override
public void onDisable() {
// Do nothing
}
protected Logger getLogger() {
return getServer().getLogger();
}
public void log(Level level, String message) {
message = "[${name}] " + message;
getLogger().log(level, message);
}
public void log(String message) {
log(Level.INFO, message);
}
}
|
package ${package};
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
public class ${name}Plugin extends JavaPlugin {
public void onEnable() {
log("Hello world!");
}
public void onDisable() {
// Do nothing
}
protected Logger getLogger() {
return getServer().getLogger();
}
public void log(Level level, String message) {
message = "[${name}] " + message;
getLogger().log(level, message);
}
public void log(String message) {
log(Level.INFO, message);
}
}
|
Remove invalid @Override annotations from plugin class
|
Remove invalid @Override annotations from plugin class
|
Java
|
mit
|
stratomine/bukkit-plugin-archetype
|
java
|
## Code Before:
package ${package};
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
public class ${name}Plugin extends JavaPlugin {
@Override
public void onEnable() {
log("Hello world!");
}
@Override
public void onDisable() {
// Do nothing
}
protected Logger getLogger() {
return getServer().getLogger();
}
public void log(Level level, String message) {
message = "[${name}] " + message;
getLogger().log(level, message);
}
public void log(String message) {
log(Level.INFO, message);
}
}
## Instruction:
Remove invalid @Override annotations from plugin class
## Code After:
package ${package};
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
public class ${name}Plugin extends JavaPlugin {
public void onEnable() {
log("Hello world!");
}
public void onDisable() {
// Do nothing
}
protected Logger getLogger() {
return getServer().getLogger();
}
public void log(Level level, String message) {
message = "[${name}] " + message;
getLogger().log(level, message);
}
public void log(String message) {
log(Level.INFO, message);
}
}
|
...
public class ${name}Plugin extends JavaPlugin {
public void onEnable() {
log("Hello world!");
}
public void onDisable() {
// Do nothing
}
...
|
1d43d69899afcb7faff1132af17201fcb557837e
|
src/main/java/org/ndexbio/model/object/NetworkSet.java
|
src/main/java/org/ndexbio/model/object/NetworkSet.java
|
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
}
|
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
private boolean showcased;
private Map<String, Object> properties;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
properties = new HashMap<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public boolean isShowcased() {
return showcased;
}
public void setShowcased(boolean showcased) {
this.showcased = showcased;
}
}
|
Add showcase flag in networkset.
|
Add showcase flag in networkset.
|
Java
|
bsd-3-clause
|
ndexbio/ndex-object-model
|
java
|
## Code Before:
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
}
## Instruction:
Add showcase flag in networkset.
## Code After:
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
private boolean showcased;
private Map<String, Object> properties;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
properties = new HashMap<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public boolean isShowcased() {
return showcased;
}
public void setShowcased(boolean showcased) {
this.showcased = showcased;
}
}
|
# ... existing code ...
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
# ... modified code ...
private String description;
private UUID ownerId;
private List<UUID> networks;
private boolean showcased;
private Map<String, Object> properties;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
properties = new HashMap<>();
}
public String getName() {
...
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public boolean isShowcased() {
return showcased;
}
public void setShowcased(boolean showcased) {
this.showcased = showcased;
}
}
# ... rest of the code ...
|
7cb68f6a749a38fef9820004a857e301c12a3044
|
morenines/util.py
|
morenines/util.py
|
import os
import hashlib
from fnmatch import fnmatchcase
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
|
import os
import hashlib
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames[:] = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
|
Fix in-place os.walk() dirs modification
|
Fix in-place os.walk() dirs modification
|
Python
|
mit
|
mcgid/morenines,mcgid/morenines
|
python
|
## Code Before:
import os
import hashlib
from fnmatch import fnmatchcase
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
## Instruction:
Fix in-place os.walk() dirs modification
## Code After:
import os
import hashlib
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames[:] = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
|
# ... existing code ...
import os
import hashlib
def get_files(index):
# ... modified code ...
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames[:] = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
# ... rest of the code ...
|
118523251af8861d20b92ce754b48e9911f100c7
|
odsimport.py
|
odsimport.py
|
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.getAttribute('name')] = db_table
for row in table.getElementsByType(TableRow):
db_row = []
db_table.append(db_row)
for cell in row.getElementsByType(TableCell):
db_value = '\n'.join(map(str, cell.getElementsByType(P)))
try:
db_value = float(db_value)
except:
pass
db_row.append(db_value)
return db
|
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.namespaces import TABLENS
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.getAttribute('name')] = db_table
for row in table.getElementsByType(TableRow):
db_row = []
db_table.append(db_row)
for cell in row.getElementsByType(TableCell):
db_value = '\n'.join(map(str, cell.getElementsByType(P)))
try:
db_value = float(db_value)
except:
pass
try:
repeat_count = int(cell.getAttribute('numbercolumnsrepeated'))
except:
repeat_count = 1
if not cell.nextSibling:
repeat_count = 1
for i in range(repeat_count):
db_row.append(db_value)
return db
|
Fix ods-import for column repeat
|
Fix ods-import for column repeat
|
Python
|
bsd-2-clause
|
aholkner/PoliticalRPG,aholkner/PoliticalRPG
|
python
|
## Code Before:
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.getAttribute('name')] = db_table
for row in table.getElementsByType(TableRow):
db_row = []
db_table.append(db_row)
for cell in row.getElementsByType(TableCell):
db_value = '\n'.join(map(str, cell.getElementsByType(P)))
try:
db_value = float(db_value)
except:
pass
db_row.append(db_value)
return db
## Instruction:
Fix ods-import for column repeat
## Code After:
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.namespaces import TABLENS
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.getAttribute('name')] = db_table
for row in table.getElementsByType(TableRow):
db_row = []
db_table.append(db_row)
for cell in row.getElementsByType(TableCell):
db_value = '\n'.join(map(str, cell.getElementsByType(P)))
try:
db_value = float(db_value)
except:
pass
try:
repeat_count = int(cell.getAttribute('numbercolumnsrepeated'))
except:
repeat_count = 1
if not cell.nextSibling:
repeat_count = 1
for i in range(repeat_count):
db_row.append(db_value)
return db
|
...
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.namespaces import TABLENS
from odf.text import P
def import_ods(path):
...
db_value = float(db_value)
except:
pass
try:
repeat_count = int(cell.getAttribute('numbercolumnsrepeated'))
except:
repeat_count = 1
if not cell.nextSibling:
repeat_count = 1
for i in range(repeat_count):
db_row.append(db_value)
return db
...
|
c1b1cca3d72de4e871e0d1cdb174712509cf4c3b
|
src/main/java/org/vanilladb/bench/remote/sp/VanillaDbSpResultSet.java
|
src/main/java/org/vanilladb/bench/remote/sp/VanillaDbSpResultSet.java
|
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
message = records[0].toString();
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
|
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
if (records.length > 0)
message = records[0].toString();
else
message = "";
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
|
Add a check for printing results
|
Add a check for printing results
|
Java
|
apache-2.0
|
vanilladb/vanillabench
|
java
|
## Code Before:
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
message = records[0].toString();
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
## Instruction:
Add a check for printing results
## Code After:
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
if (records.length > 0)
message = records[0].toString();
else
message = "";
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
|
# ... existing code ...
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
if (records.length > 0)
message = records[0].toString();
else
message = "";
isCommitted = result.isCommitted();
}
# ... rest of the code ...
|
7356dd66137cbb606c3026802ff42ab666af6c08
|
jmbo_twitter/admin.py
|
jmbo_twitter/admin.py
|
from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
|
from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
# Once a newer version of jmbo is out the try-except can be removed
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
|
Add a comment explaining AttributeError
|
Add a comment explaining AttributeError
|
Python
|
bsd-3-clause
|
praekelt/jmbo-twitter,praekelt/jmbo-twitter,praekelt/jmbo-twitter
|
python
|
## Code Before:
from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
## Instruction:
Add a comment explaining AttributeError
## Code After:
from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
# Once a newer version of jmbo is out the try-except can be removed
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
|
// ... existing code ...
_image.allow_tags = True
def _actions(self, obj):
# Once a newer version of jmbo is out the try-except can be removed
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
// ... rest of the code ...
|
8090fa9c072656497ff383e9b76d49af2955e420
|
examples/hopv/hopv_graph_conv.py
|
examples/hopv/hopv_graph_conv.py
|
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvTensorGraph(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
Fix GraphConvTensorGraph to GraphConvModel in hopv example
|
Fix GraphConvTensorGraph to GraphConvModel in hopv example
|
Python
|
mit
|
Agent007/deepchem,lilleswing/deepchem,lilleswing/deepchem,Agent007/deepchem,peastman/deepchem,miaecle/deepchem,peastman/deepchem,ktaneishi/deepchem,miaecle/deepchem,Agent007/deepchem,deepchem/deepchem,ktaneishi/deepchem,deepchem/deepchem,ktaneishi/deepchem,miaecle/deepchem,lilleswing/deepchem
|
python
|
## Code Before:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvTensorGraph(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
## Instruction:
Fix GraphConvTensorGraph to GraphConvModel in hopv example
## Code After:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
# ... existing code ...
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
# ... modified code ...
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
# ... rest of the code ...
|
be2ed67f8cdc06a40224d741d8e611bbe2eb6f4a
|
src/main/java/com/jakewharton/telecine/TelecineActivity.java
|
src/main/java/com/jakewharton/telecine/TelecineActivity.java
|
package com.jakewharton.telecine;
import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public final class TelecineActivity extends Activity {
private static final int CREATE_SCREEN_CAPTURE = 4242;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.launch) void onLaunchClicked() {
Timber.d("Attempting to acquire permission to screen capture.");
MediaProjectionManager manager =
(MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CREATE_SCREEN_CAPTURE:
Timber.d("Acquired permission to screen capture. Starting service.");
startService(TelecineService.newIntent(this, resultCode, data));
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
package com.jakewharton.telecine;
import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public final class TelecineActivity extends Activity {
private static final int CREATE_SCREEN_CAPTURE = 4242;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.launch) void onLaunchClicked() {
Timber.d("Attempting to acquire permission to screen capture.");
MediaProjectionManager manager =
(MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CREATE_SCREEN_CAPTURE:
if (resultCode == 0) {
Timber.d("Failed to acquire permission to screen capture.");
} else {
Timber.d("Acquired permission to screen capture. Starting service.");
startService(TelecineService.newIntent(this, resultCode, data));
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
Handle when the user presses cancel on the permission prompt.
|
Handle when the user presses cancel on the permission prompt.
|
Java
|
apache-2.0
|
poovarasanvasudevan/Telecine,hatiboy/Telecine,TotalCaesar659/Telecine,TotalCaesar659/Telecine,vipulshah2010/Telecine,monxalo/Telecine,TeamEOS/Telecine,msdgwzhy6/Telecine,zz676/Telecine,msdgwzhy6/Telecine,JakeWharton/Telecine,JakeWharton/Telecine,vipulshah2010/Telecine,ceosilvajr/Telecine,tsdl2013/Telecine,poovarasanvasudevan/Telecine,zz676/Telecine,0359xiaodong/Telecine,vsvankhede/Telecine,dingkple/Telecine,tasomaniac/Telecine,pratamawijaya/Telecine,olayinkasf/Telecine,0359xiaodong/Telecine,tsdl2013/Telecine,hatiboy/Telecine,Dreezydraig/Telecine,vaginessa/Telecine,pratamawijaya/Telecine,dingkple/Telecine,ceosilvajr/Telecine,sanjaykushwaha/Telecine,xfumihiro/Telecine,vaginessa/Telecine,monxalo/Telecine,NightlyNexus/Telecine,vsvankhede/Telecine,sanjaykushwaha/Telecine,olayinkasf/Telecine,xfumihiro/Telecine,tasomaniac/Telecine,TeamEOS/Telecine,Dreezydraig/Telecine,NightlyNexus/Telecine
|
java
|
## Code Before:
package com.jakewharton.telecine;
import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public final class TelecineActivity extends Activity {
private static final int CREATE_SCREEN_CAPTURE = 4242;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.launch) void onLaunchClicked() {
Timber.d("Attempting to acquire permission to screen capture.");
MediaProjectionManager manager =
(MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CREATE_SCREEN_CAPTURE:
Timber.d("Acquired permission to screen capture. Starting service.");
startService(TelecineService.newIntent(this, resultCode, data));
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
## Instruction:
Handle when the user presses cancel on the permission prompt.
## Code After:
package com.jakewharton.telecine;
import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public final class TelecineActivity extends Activity {
private static final int CREATE_SCREEN_CAPTURE = 4242;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.launch) void onLaunchClicked() {
Timber.d("Attempting to acquire permission to screen capture.");
MediaProjectionManager manager =
(MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CREATE_SCREEN_CAPTURE:
if (resultCode == 0) {
Timber.d("Failed to acquire permission to screen capture.");
} else {
Timber.d("Acquired permission to screen capture. Starting service.");
startService(TelecineService.newIntent(this, resultCode, data));
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
...
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CREATE_SCREEN_CAPTURE:
if (resultCode == 0) {
Timber.d("Failed to acquire permission to screen capture.");
} else {
Timber.d("Acquired permission to screen capture. Starting service.");
startService(TelecineService.newIntent(this, resultCode, data));
}
break;
default:
...
|
690c2e22d48c37fa590e9e93595fc5c5ee0d1eab
|
include/clang/CodeGen/ModuleBuilder.h
|
include/clang/CodeGen/ModuleBuilder.h
|
//===--- CodeGen/ModuleBuilder.h - Build LLVM from ASTs ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ModuleBuilder interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#include "clang/AST/ASTConsumer.h"
#include <string>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class Diagnostic;
class LangOptions;
class CodeGenOptions;
class CodeGenerator : public ASTConsumer {
public:
virtual llvm::Module* GetModule() = 0;
virtual llvm::Module* ReleaseModule() = 0;
};
CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags,
const std::string &ModuleName,
const CodeGenOptions &CGO,
llvm::LLVMContext& C);
}
#endif
|
//===--- CodeGen/ModuleBuilder.h - Build LLVM from ASTs ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ModuleBuilder interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#include "clang/AST/ASTConsumer.h"
#include <string>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class Diagnostic;
class LangOptions;
class CodeGenOptions;
class CodeGenerator : public ASTConsumer {
public:
virtual llvm::Module* GetModule() = 0;
virtual llvm::Module* ReleaseModule() = 0;
};
/// CreateLLVMCodeGen - Create a CodeGenerator instance.
/// It is the responsibility of the caller to call delete on
/// the allocated CodeGenerator instance.
CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags,
const std::string &ModuleName,
const CodeGenOptions &CGO,
llvm::LLVMContext& C);
}
#endif
|
Add a comment to mention the memory ownership situation.
|
Add a comment to mention the memory ownership situation.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@104886 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang
|
c
|
## Code Before:
//===--- CodeGen/ModuleBuilder.h - Build LLVM from ASTs ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ModuleBuilder interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#include "clang/AST/ASTConsumer.h"
#include <string>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class Diagnostic;
class LangOptions;
class CodeGenOptions;
class CodeGenerator : public ASTConsumer {
public:
virtual llvm::Module* GetModule() = 0;
virtual llvm::Module* ReleaseModule() = 0;
};
CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags,
const std::string &ModuleName,
const CodeGenOptions &CGO,
llvm::LLVMContext& C);
}
#endif
## Instruction:
Add a comment to mention the memory ownership situation.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@104886 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
//===--- CodeGen/ModuleBuilder.h - Build LLVM from ASTs ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ModuleBuilder interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#include "clang/AST/ASTConsumer.h"
#include <string>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class Diagnostic;
class LangOptions;
class CodeGenOptions;
class CodeGenerator : public ASTConsumer {
public:
virtual llvm::Module* GetModule() = 0;
virtual llvm::Module* ReleaseModule() = 0;
};
/// CreateLLVMCodeGen - Create a CodeGenerator instance.
/// It is the responsibility of the caller to call delete on
/// the allocated CodeGenerator instance.
CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags,
const std::string &ModuleName,
const CodeGenOptions &CGO,
llvm::LLVMContext& C);
}
#endif
|
// ... existing code ...
virtual llvm::Module* ReleaseModule() = 0;
};
/// CreateLLVMCodeGen - Create a CodeGenerator instance.
/// It is the responsibility of the caller to call delete on
/// the allocated CodeGenerator instance.
CodeGenerator *CreateLLVMCodeGen(Diagnostic &Diags,
const std::string &ModuleName,
const CodeGenOptions &CGO,
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.