repo
stringlengths 8
50
| commit
stringlengths 40
40
| path
stringlengths 5
171
| lang
stringclasses 5
values | license
stringclasses 13
values | message
stringlengths 21
1.33k
| old_code
stringlengths 15
2.4k
| new_code
stringlengths 140
2.61k
| n_added
int64 0
81
| n_removed
int64 0
58
| n_hunks
int64 1
8
| change_kind
stringclasses 3
values | udiff
stringlengths 88
3.33k
| udiff-h
stringlengths 85
3.32k
| udiff-l
stringlengths 95
3.57k
| search-replace
stringlengths 89
3.36k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-asset-admin
|
a6a108b572c5ba81cc74135bde8fedd550801ecf
|
client/src/state/confirmDeletion/ConfirmDeletionActions.js
|
javascript
|
bsd-3-clause
|
Fix bad description for bulk delete actions
|
import ACTION_TYPES from './ConfirmDeletionActionTypes';
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function confirm(files) {
return {
type: ACTION_TYPES.CONFIRM_DELETION_ASK,
payload: { files },
};
}
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function deleting() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_CONFIRM,
payload: { },
};
}
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function cancel() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_CANCEL,
payload: { },
};
}
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function reset() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_RESET,
payload: { },
};
}
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function modalClose() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_MODAL_CLOSE,
payload: { },
};
}
|
import ACTION_TYPES from './ConfirmDeletionActionTypes';
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function confirm(files) {
return {
type: ACTION_TYPES.CONFIRM_DELETION_ASK,
payload: { files },
};
}
/**
* The GraphQL request for deleting files has started.
*
*/
export function deleting() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_CONFIRM,
payload: { },
};
}
/**
* User has changed their mind and doesn't want to delete files any more.
*
*/
export function cancel() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_CANCEL,
payload: { },
};
}
/**
* Deletion workflow was completed and we're returning to our regular state.
*
*/
export function reset() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_RESET,
payload: { },
};
}
/**
* Modal has closed, we can stop rendering it.
*
*/
export function modalClose() {
return {
type: ACTION_TYPES.CONFIRM_DELETION_MODAL_CLOSE,
payload: { },
};
}
| 4
| 8
| 4
|
mixed
|
--- a/client/src/state/confirmDeletion/ConfirmDeletionActions.js
+++ b/client/src/state/confirmDeletion/ConfirmDeletionActions.js
@@ -15,5 +15,4 @@
/**
- * Ask for permission to delete
+ * The GraphQL request for deleting files has started.
*
- * @param {Object[]} List of files we want to delete
*/
@@ -27,5 +26,4 @@
/**
- * Ask for permission to delete
+ * User has changed their mind and doesn't want to delete files any more.
*
- * @param {Object[]} List of files we want to delete
*/
@@ -39,5 +37,4 @@
/**
- * Ask for permission to delete
+ * Deletion workflow was completed and we're returning to our regular state.
*
- * @param {Object[]} List of files we want to delete
*/
@@ -51,5 +48,4 @@
/**
- * Ask for permission to delete
+ * Modal has closed, we can stop rendering it.
*
- * @param {Object[]} List of files we want to delete
*/
|
--- a/client/src/state/confirmDeletion/ConfirmDeletionActions.js
+++ b/client/src/state/confirmDeletion/ConfirmDeletionActions.js
@@ ... @@
/**
- * Ask for permission to delete
+ * The GraphQL request for deleting files has started.
*
- * @param {Object[]} List of files we want to delete
*/
@@ ... @@
/**
- * Ask for permission to delete
+ * User has changed their mind and doesn't want to delete files any more.
*
- * @param {Object[]} List of files we want to delete
*/
@@ ... @@
/**
- * Ask for permission to delete
+ * Deletion workflow was completed and we're returning to our regular state.
*
- * @param {Object[]} List of files we want to delete
*/
@@ ... @@
/**
- * Ask for permission to delete
+ * Modal has closed, we can stop rendering it.
*
- * @param {Object[]} List of files we want to delete
*/
|
--- a/client/src/state/confirmDeletion/ConfirmDeletionActions.js
+++ b/client/src/state/confirmDeletion/ConfirmDeletionActions.js
@@ -15,5 +15,4 @@
CON /**
DEL * Ask for permission to delete
ADD * The GraphQL request for deleting files has started.
CON *
DEL * @param {Object[]} List of files we want to delete
CON */
@@ -27,5 +26,4 @@
CON /**
DEL * Ask for permission to delete
ADD * User has changed their mind and doesn't want to delete files any more.
CON *
DEL * @param {Object[]} List of files we want to delete
CON */
@@ -39,5 +37,4 @@
CON /**
DEL * Ask for permission to delete
ADD * Deletion workflow was completed and we're returning to our regular state.
CON *
DEL * @param {Object[]} List of files we want to delete
CON */
@@ -51,5 +48,4 @@
CON /**
DEL * Ask for permission to delete
ADD * Modal has closed, we can stop rendering it.
CON *
DEL * @param {Object[]} List of files we want to delete
CON */
|
<<<<<<< SEARCH
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function deleting() {
=======
/**
* The GraphQL request for deleting files has started.
*
*/
export function deleting() {
>>>>>>> REPLACE
<<<<<<< SEARCH
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function cancel() {
=======
/**
* User has changed their mind and doesn't want to delete files any more.
*
*/
export function cancel() {
>>>>>>> REPLACE
<<<<<<< SEARCH
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function reset() {
=======
/**
* Deletion workflow was completed and we're returning to our regular state.
*
*/
export function reset() {
>>>>>>> REPLACE
<<<<<<< SEARCH
/**
* Ask for permission to delete
*
* @param {Object[]} List of files we want to delete
*/
export function modalClose() {
=======
/**
* Modal has closed, we can stop rendering it.
*
*/
export function modalClose() {
>>>>>>> REPLACE
|
talkhouse/noyes
|
3afdb5e467b4e31e2de98786c2b84467061fe181
|
lib/java_impl/talkhouse/Segmenter.java
|
java
|
bsd-2-clause
|
Update Java segmenter to use the same formula as the C version.
|
package talkhouse;
public class Segmenter {
private double[] buf=null;
int winsz;
int winshift;
static final int MIN_SEGMENTS = 3;
public Segmenter(int winsz, int winshift) {
this.winsz = winsz;
this.winshift = winshift;
}
public double[][] apply(double[] data) {
double[] combo;
if (buf != null) {
combo = new double[buf.length + data.length];
System.arraycopy(buf, 0, combo, 0, buf.length);
System.arraycopy(data, 0, combo, buf.length, data.length);
} else {
combo = data;
}
if (combo.length < winsz + winshift * MIN_SEGMENTS){
buf = combo;
return null;
} else {
buf = null;
}
double[][] result = new double[(combo.length-winsz)/winshift+1][];
int i = 0;
int j=0;
while (i+winsz <= combo.length) {
double[] seg = new double[winsz];
System.arraycopy(combo, i, seg, 0, winsz);
result[j++] = seg;
i+=winshift;
}
int bufsize = combo.length - i;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
buf = new double[bufsize];
}
System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
} else {
buf = null;
}
return result;
}
};
|
package talkhouse;
public class Segmenter {
private double[] buf=null;
int winsz;
int winshift;
static final int MIN_SEGMENTS = 3;
public Segmenter(int winsz, int winshift) {
this.winsz = winsz;
this.winshift = winshift;
}
public double[][] apply(double[] data) {
double[] combo;
if (buf != null) {
combo = new double[buf.length + data.length];
System.arraycopy(buf, 0, combo, 0, buf.length);
System.arraycopy(data, 0, combo, buf.length, data.length);
} else {
combo = data;
}
if (combo.length < winsz + winshift * MIN_SEGMENTS){
buf = combo;
return null;
} else {
buf = null;
}
int rows = (combo.length - combo.length % winshift - winsz +
winshift)/ winshift;
double[][] result = new double[rows][];
for (int i=0;i<rows;++i) {
double[] seg = new double[winsz];
System.arraycopy(combo, i*winshift, seg, 0, winsz);
result[i] = seg;
}
int bufsize = combo.length - rows * winshift;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
buf = new double[bufsize];
}
System.arraycopy(combo, combo.length - bufsize, buf, 0, bufsize);
} else {
buf = null;
}
return result;
}
};
| 8
| 8
| 1
|
mixed
|
--- a/lib/java_impl/talkhouse/Segmenter.java
+++ b/lib/java_impl/talkhouse/Segmenter.java
@@ -28,13 +28,13 @@
}
- double[][] result = new double[(combo.length-winsz)/winshift+1][];
- int i = 0;
- int j=0;
- while (i+winsz <= combo.length) {
+ int rows = (combo.length - combo.length % winshift - winsz +
+ winshift)/ winshift;
+ double[][] result = new double[rows][];
+
+ for (int i=0;i<rows;++i) {
double[] seg = new double[winsz];
- System.arraycopy(combo, i, seg, 0, winsz);
- result[j++] = seg;
- i+=winshift;
+ System.arraycopy(combo, i*winshift, seg, 0, winsz);
+ result[i] = seg;
}
- int bufsize = combo.length - i;
+ int bufsize = combo.length - rows * winshift;
if (bufsize > 0) {
|
--- a/lib/java_impl/talkhouse/Segmenter.java
+++ b/lib/java_impl/talkhouse/Segmenter.java
@@ ... @@
}
- double[][] result = new double[(combo.length-winsz)/winshift+1][];
- int i = 0;
- int j=0;
- while (i+winsz <= combo.length) {
+ int rows = (combo.length - combo.length % winshift - winsz +
+ winshift)/ winshift;
+ double[][] result = new double[rows][];
+
+ for (int i=0;i<rows;++i) {
double[] seg = new double[winsz];
- System.arraycopy(combo, i, seg, 0, winsz);
- result[j++] = seg;
- i+=winshift;
+ System.arraycopy(combo, i*winshift, seg, 0, winsz);
+ result[i] = seg;
}
- int bufsize = combo.length - i;
+ int bufsize = combo.length - rows * winshift;
if (bufsize > 0) {
|
--- a/lib/java_impl/talkhouse/Segmenter.java
+++ b/lib/java_impl/talkhouse/Segmenter.java
@@ -28,13 +28,13 @@
CON }
DEL double[][] result = new double[(combo.length-winsz)/winshift+1][];
DEL int i = 0;
DEL int j=0;
DEL while (i+winsz <= combo.length) {
ADD int rows = (combo.length - combo.length % winshift - winsz +
ADD winshift)/ winshift;
ADD double[][] result = new double[rows][];
ADD
ADD for (int i=0;i<rows;++i) {
CON double[] seg = new double[winsz];
DEL System.arraycopy(combo, i, seg, 0, winsz);
DEL result[j++] = seg;
DEL i+=winshift;
ADD System.arraycopy(combo, i*winshift, seg, 0, winsz);
ADD result[i] = seg;
CON }
CON
DEL int bufsize = combo.length - i;
ADD int bufsize = combo.length - rows * winshift;
CON if (bufsize > 0) {
|
<<<<<<< SEARCH
buf = null;
}
double[][] result = new double[(combo.length-winsz)/winshift+1][];
int i = 0;
int j=0;
while (i+winsz <= combo.length) {
double[] seg = new double[winsz];
System.arraycopy(combo, i, seg, 0, winsz);
result[j++] = seg;
i+=winshift;
}
int bufsize = combo.length - i;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
=======
buf = null;
}
int rows = (combo.length - combo.length % winshift - winsz +
winshift)/ winshift;
double[][] result = new double[rows][];
for (int i=0;i<rows;++i) {
double[] seg = new double[winsz];
System.arraycopy(combo, i*winshift, seg, 0, winsz);
result[i] = seg;
}
int bufsize = combo.length - rows * winshift;
if (bufsize > 0) {
if (buf == null || buf.length != bufsize) {
>>>>>>> REPLACE
|
maslowis/twitter-ripper
|
33fb88068a5efd068cef7f7067b45f0bb1f78ad7
|
src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
|
java
|
mit
|
Change reference on the twitter's singleton
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ivan Maslov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package info.maslowis.twitterripper.command;
import twitter4j.Twitter;
/**
* The superclass for any twitter command
*
* @author Ivan Maslov
*/
public abstract class TwitterCommand extends Command {
protected Twitter twitter;
protected TwitterCommand(Twitter twitter) {
super();
this.twitter = twitter;
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ivan Maslov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package info.maslowis.twitterripper.command;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
/**
* The superclass for any twitter command
*
* @author Ivan Maslov
*/
public abstract class TwitterCommand extends Command {
protected Twitter twitter;
protected TwitterCommand() {
super();
this.twitter = TwitterFactory.getSingleton();
}
}
| 3
| 2
| 2
|
mixed
|
--- a/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
+++ b/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
@@ -27,2 +27,3 @@
import twitter4j.Twitter;
+import twitter4j.TwitterFactory;
@@ -36,5 +37,5 @@
- protected TwitterCommand(Twitter twitter) {
+ protected TwitterCommand() {
super();
- this.twitter = twitter;
+ this.twitter = TwitterFactory.getSingleton();
}
|
--- a/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
+++ b/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
@@ ... @@
import twitter4j.Twitter;
+import twitter4j.TwitterFactory;
@@ ... @@
- protected TwitterCommand(Twitter twitter) {
+ protected TwitterCommand() {
super();
- this.twitter = twitter;
+ this.twitter = TwitterFactory.getSingleton();
}
|
--- a/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
+++ b/src/main/java/info/maslowis/twitterripper/command/TwitterCommand.java
@@ -27,2 +27,3 @@
CON import twitter4j.Twitter;
ADD import twitter4j.TwitterFactory;
CON
@@ -36,5 +37,5 @@
CON
DEL protected TwitterCommand(Twitter twitter) {
ADD protected TwitterCommand() {
CON super();
DEL this.twitter = twitter;
ADD this.twitter = TwitterFactory.getSingleton();
CON }
|
<<<<<<< SEARCH
import twitter4j.Twitter;
/**
=======
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
protected Twitter twitter;
protected TwitterCommand(Twitter twitter) {
super();
this.twitter = twitter;
}
}
=======
protected Twitter twitter;
protected TwitterCommand() {
super();
this.twitter = TwitterFactory.getSingleton();
}
}
>>>>>>> REPLACE
|
sergey-dryabzhinsky/denyhosts_sync
|
2c3dbcaaa4eee9b2d48670fe0db5094044eb49af
|
setup.py
|
python
|
agpl-3.0
|
Install static files, templates and docs
|
#!/usr/bin/env python
from setuptools import setup
from glob import glob
from dh_syncserver import version
etcpath = "/etc"
setup(name='dh_syncserver',
version=version,
description='DenyHosts Synchronisation Server',
author='Jan-Pascal van Best',
author_email='janpascal@vanbest.org',
url='http://www.github.com/janpascal/denyhosts_sync_server',
packages=['dh_syncserver'],
install_requires=["Twisted", "twistar", "ipaddr", "jinja2", "pygal", "GeoIP"],
scripts=['scripts/dh_syncserver'],
data_files=[
],
license="""
Copyright (C) 2015 Jan-Pascal van Best <janpascal@vanbest.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
)
|
#!/usr/bin/env python
from setuptools import setup
from glob import glob
from dh_syncserver import version
etcpath = "/etc"
setup(name='dh_syncserver',
version=version,
description='DenyHosts Synchronisation Server',
author='Jan-Pascal van Best',
author_email='janpascal@vanbest.org',
url='http://www.github.com/janpascal/denyhosts_sync_server',
packages=['dh_syncserver'],
install_requires=["Twisted", "twistar", "ipaddr", "jinja2", "pygal", "GeoIP"],
scripts=['scripts/dh_syncserver'],
data_files=[
('static/js', glob('static/js/*.js')),
('static/css', glob('static/css/*.css')),
('static/graph', glob('static/graph/README')),
('template', glob('template/*')),
('docs', glob('docs/*')),
],
license="""
Copyright (C) 2015 Jan-Pascal van Best <janpascal@vanbest.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
)
| 5
| 0
| 1
|
add_only
|
--- a/setup.py
+++ b/setup.py
@@ -18,2 +18,7 @@
data_files=[
+ ('static/js', glob('static/js/*.js')),
+ ('static/css', glob('static/css/*.css')),
+ ('static/graph', glob('static/graph/README')),
+ ('template', glob('template/*')),
+ ('docs', glob('docs/*')),
],
|
--- a/setup.py
+++ b/setup.py
@@ ... @@
data_files=[
+ ('static/js', glob('static/js/*.js')),
+ ('static/css', glob('static/css/*.css')),
+ ('static/graph', glob('static/graph/README')),
+ ('template', glob('template/*')),
+ ('docs', glob('docs/*')),
],
|
--- a/setup.py
+++ b/setup.py
@@ -18,2 +18,7 @@
CON data_files=[
ADD ('static/js', glob('static/js/*.js')),
ADD ('static/css', glob('static/css/*.css')),
ADD ('static/graph', glob('static/graph/README')),
ADD ('template', glob('template/*')),
ADD ('docs', glob('docs/*')),
CON ],
|
<<<<<<< SEARCH
scripts=['scripts/dh_syncserver'],
data_files=[
],
license="""
=======
scripts=['scripts/dh_syncserver'],
data_files=[
('static/js', glob('static/js/*.js')),
('static/css', glob('static/css/*.css')),
('static/graph', glob('static/graph/README')),
('template', glob('template/*')),
('docs', glob('docs/*')),
],
license="""
>>>>>>> REPLACE
|
yingyun001/ovirt-engine
|
0a2bc6bf8105841c34b45fbb4e8e43a6d4a2e34b
|
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
|
java
|
apache-2.0
|
common: Change GetConfiguration query not to refresh session
Bug-Url: https://bugzilla.redhat.com/1168842
Change-Id: I9ec8cb46e3fba206d9e1a93df9f985d5c2477fa8
Signed-off-by: Yair Zaslavsky <e2db7378c71f96998c1e6c0ce01fa87adf291bd0@redhat.com>
|
package org.ovirt.engine.core.common.queries;
public class GetConfigurationValueParameters extends VdcQueryParametersBase {
private static final long serialVersionUID = -5889171970595969719L;
public GetConfigurationValueParameters(ConfigurationValues cVal) {
_configValue = cVal;
}
private ConfigurationValues _configValue;
public ConfigurationValues getConfigValue() {
return _configValue;
}
private String privateVersion;
public String getVersion() {
return privateVersion;
}
public void setVersion(String value) {
privateVersion = value;
}
public GetConfigurationValueParameters(ConfigurationValues cVal, String version) {
_configValue = cVal;
privateVersion = version;
}
public GetConfigurationValueParameters() {
_configValue = ConfigurationValues.MaxNumOfVmCpus;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(50);
builder.append("version: "); //$NON-NLS-1$
builder.append(getVersion());
builder.append(", configuration value: ");
builder.append(getConfigValue());
builder.append(", ");
builder.append(super.toString());
return builder.toString();
}
}
|
package org.ovirt.engine.core.common.queries;
public class GetConfigurationValueParameters extends VdcQueryParametersBase {
private static final long serialVersionUID = -5889171970595969719L;
public GetConfigurationValueParameters(ConfigurationValues cVal) {
this(cVal, null);
}
private ConfigurationValues _configValue;
public ConfigurationValues getConfigValue() {
return _configValue;
}
private String privateVersion;
public String getVersion() {
return privateVersion;
}
public void setVersion(String value) {
privateVersion = value;
}
public GetConfigurationValueParameters(ConfigurationValues cVal, String version) {
_configValue = cVal;
privateVersion = version;
setRefresh(false);
}
public GetConfigurationValueParameters() {
this(ConfigurationValues.MaxNumOfVmCpus);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(50);
builder.append("version: "); //$NON-NLS-1$
builder.append(getVersion());
builder.append(", configuration value: ");
builder.append(getConfigValue());
builder.append(", ");
builder.append(super.toString());
return builder.toString();
}
}
| 3
| 2
| 3
|
mixed
|
--- a/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
+++ b/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
@@ -6,3 +6,3 @@
public GetConfigurationValueParameters(ConfigurationValues cVal) {
- _configValue = cVal;
+ this(cVal, null);
}
@@ -28,2 +28,3 @@
privateVersion = version;
+ setRefresh(false);
}
@@ -31,3 +32,3 @@
public GetConfigurationValueParameters() {
- _configValue = ConfigurationValues.MaxNumOfVmCpus;
+ this(ConfigurationValues.MaxNumOfVmCpus);
}
|
--- a/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
+++ b/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
@@ ... @@
public GetConfigurationValueParameters(ConfigurationValues cVal) {
- _configValue = cVal;
+ this(cVal, null);
}
@@ ... @@
privateVersion = version;
+ setRefresh(false);
}
@@ ... @@
public GetConfigurationValueParameters() {
- _configValue = ConfigurationValues.MaxNumOfVmCpus;
+ this(ConfigurationValues.MaxNumOfVmCpus);
}
|
--- a/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
+++ b/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetConfigurationValueParameters.java
@@ -6,3 +6,3 @@
CON public GetConfigurationValueParameters(ConfigurationValues cVal) {
DEL _configValue = cVal;
ADD this(cVal, null);
CON }
@@ -28,2 +28,3 @@
CON privateVersion = version;
ADD setRefresh(false);
CON }
@@ -31,3 +32,3 @@
CON public GetConfigurationValueParameters() {
DEL _configValue = ConfigurationValues.MaxNumOfVmCpus;
ADD this(ConfigurationValues.MaxNumOfVmCpus);
CON }
|
<<<<<<< SEARCH
public GetConfigurationValueParameters(ConfigurationValues cVal) {
_configValue = cVal;
}
=======
public GetConfigurationValueParameters(ConfigurationValues cVal) {
this(cVal, null);
}
>>>>>>> REPLACE
<<<<<<< SEARCH
_configValue = cVal;
privateVersion = version;
}
public GetConfigurationValueParameters() {
_configValue = ConfigurationValues.MaxNumOfVmCpus;
}
=======
_configValue = cVal;
privateVersion = version;
setRefresh(false);
}
public GetConfigurationValueParameters() {
this(ConfigurationValues.MaxNumOfVmCpus);
}
>>>>>>> REPLACE
|
erinspace/scrapi
|
b62c8c905cdd332a0073ce462be3e5c5b17b282d
|
api/webview/views.py
|
python
|
apache-2.0
|
Make the view List only remove Create
|
from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListCreateAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListCreateAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
|
from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
| 2
| 2
| 2
|
mixed
|
--- a/api/webview/views.py
+++ b/api/webview/views.py
@@ -10,3 +10,3 @@
-class DocumentList(generics.ListCreateAPIView):
+class DocumentList(generics.ListAPIView):
"""
@@ -26,3 +26,3 @@
-class DocumentsFromSource(generics.ListCreateAPIView):
+class DocumentsFromSource(generics.ListAPIView):
"""
|
--- a/api/webview/views.py
+++ b/api/webview/views.py
@@ ... @@
-class DocumentList(generics.ListCreateAPIView):
+class DocumentList(generics.ListAPIView):
"""
@@ ... @@
-class DocumentsFromSource(generics.ListCreateAPIView):
+class DocumentsFromSource(generics.ListAPIView):
"""
|
--- a/api/webview/views.py
+++ b/api/webview/views.py
@@ -10,3 +10,3 @@
CON
DEL class DocumentList(generics.ListCreateAPIView):
ADD class DocumentList(generics.ListAPIView):
CON """
@@ -26,3 +26,3 @@
CON
DEL class DocumentsFromSource(generics.ListCreateAPIView):
ADD class DocumentsFromSource(generics.ListAPIView):
CON """
|
<<<<<<< SEARCH
class DocumentList(generics.ListCreateAPIView):
"""
List all documents in the SHARE API
=======
class DocumentList(generics.ListAPIView):
"""
List all documents in the SHARE API
>>>>>>> REPLACE
<<<<<<< SEARCH
class DocumentsFromSource(generics.ListCreateAPIView):
"""
List all documents from a particular source
=======
class DocumentsFromSource(generics.ListAPIView):
"""
List all documents from a particular source
>>>>>>> REPLACE
|
gpbl/react-day-picker
|
689efdc1a4b5593a180f3ab805f41bc41ab03843
|
docs/src/code-samples/examples/input-custom-overlay.js
|
javascript
|
mit
|
Make sure we pass the correct props to the overlay
|
import React from 'react';
import PropTypes from 'prop-types';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';
function CustomOverlay({ classNames, selectedDay, children }) {
return (
<div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}>
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
<p>
{selectedDay
? `You picked: ${selectedDay.toLocaleDateString()}`
: 'Please pick a day'}
</p>
{children}
</div>
</div>
);
}
CustomOverlay.propTypes = {
classNames: PropTypes.object.isRequired,
selectedDay: PropTypes.oneOfType([Date]),
children: PropTypes.number.isRequired,
};
export default function Example() {
return (
<DayPickerInput
overlayComponent={CustomOverlay}
dayPickerProps={{
todayButton: 'Today',
}}
/>
);
}
|
import React from 'react';
import PropTypes from 'prop-types';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';
function CustomOverlay({ classNames, selectedDay, children, ...props }) {
return (
<div
className={classNames.overlayWrapper}
style={{ marginLeft: -100 }}
{...props}
>
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
<button onClick={() => console.log('clicked!')}>button</button>
<p>
{selectedDay
? `You picked: ${selectedDay.toLocaleDateString()}`
: 'Please pick a day'}
</p>
{children}
</div>
</div>
);
}
CustomOverlay.propTypes = {
classNames: PropTypes.object.isRequired,
selectedDay: PropTypes.instanceOf(Date),
children: PropTypes.node.isRequired,
};
export default function Example() {
return (
<DayPickerInput
overlayComponent={CustomOverlay}
dayPickerProps={{
todayButton: 'Today',
}}
/>
);
}
| 9
| 4
| 2
|
mixed
|
--- a/docs/src/code-samples/examples/input-custom-overlay.js
+++ b/docs/src/code-samples/examples/input-custom-overlay.js
@@ -6,7 +6,12 @@
-function CustomOverlay({ classNames, selectedDay, children }) {
+function CustomOverlay({ classNames, selectedDay, children, ...props }) {
return (
- <div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}>
+ <div
+ className={classNames.overlayWrapper}
+ style={{ marginLeft: -100 }}
+ {...props}
+ >
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
+ <button onClick={() => console.log('clicked!')}>button</button>
<p>
@@ -24,4 +29,4 @@
classNames: PropTypes.object.isRequired,
- selectedDay: PropTypes.oneOfType([Date]),
- children: PropTypes.number.isRequired,
+ selectedDay: PropTypes.instanceOf(Date),
+ children: PropTypes.node.isRequired,
};
|
--- a/docs/src/code-samples/examples/input-custom-overlay.js
+++ b/docs/src/code-samples/examples/input-custom-overlay.js
@@ ... @@
-function CustomOverlay({ classNames, selectedDay, children }) {
+function CustomOverlay({ classNames, selectedDay, children, ...props }) {
return (
- <div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}>
+ <div
+ className={classNames.overlayWrapper}
+ style={{ marginLeft: -100 }}
+ {...props}
+ >
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
+ <button onClick={() => console.log('clicked!')}>button</button>
<p>
@@ ... @@
classNames: PropTypes.object.isRequired,
- selectedDay: PropTypes.oneOfType([Date]),
- children: PropTypes.number.isRequired,
+ selectedDay: PropTypes.instanceOf(Date),
+ children: PropTypes.node.isRequired,
};
|
--- a/docs/src/code-samples/examples/input-custom-overlay.js
+++ b/docs/src/code-samples/examples/input-custom-overlay.js
@@ -6,7 +6,12 @@
CON
DEL function CustomOverlay({ classNames, selectedDay, children }) {
ADD function CustomOverlay({ classNames, selectedDay, children, ...props }) {
CON return (
DEL <div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}>
ADD <div
ADD className={classNames.overlayWrapper}
ADD style={{ marginLeft: -100 }}
ADD {...props}
ADD >
CON <div className={classNames.overlay}>
CON <h3>Hello day picker!</h3>
ADD <button onClick={() => console.log('clicked!')}>button</button>
CON <p>
@@ -24,4 +29,4 @@
CON classNames: PropTypes.object.isRequired,
DEL selectedDay: PropTypes.oneOfType([Date]),
DEL children: PropTypes.number.isRequired,
ADD selectedDay: PropTypes.instanceOf(Date),
ADD children: PropTypes.node.isRequired,
CON };
|
<<<<<<< SEARCH
import 'react-day-picker/lib/style.css';
function CustomOverlay({ classNames, selectedDay, children }) {
return (
<div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}>
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
<p>
{selectedDay
=======
import 'react-day-picker/lib/style.css';
function CustomOverlay({ classNames, selectedDay, children, ...props }) {
return (
<div
className={classNames.overlayWrapper}
style={{ marginLeft: -100 }}
{...props}
>
<div className={classNames.overlay}>
<h3>Hello day picker!</h3>
<button onClick={() => console.log('clicked!')}>button</button>
<p>
{selectedDay
>>>>>>> REPLACE
<<<<<<< SEARCH
CustomOverlay.propTypes = {
classNames: PropTypes.object.isRequired,
selectedDay: PropTypes.oneOfType([Date]),
children: PropTypes.number.isRequired,
};
=======
CustomOverlay.propTypes = {
classNames: PropTypes.object.isRequired,
selectedDay: PropTypes.instanceOf(Date),
children: PropTypes.node.isRequired,
};
>>>>>>> REPLACE
|
FilipFilipov/Java-Slide-Puzzle
|
439349c41bcd31e22e281d8dad0d8bfc2449cd56
|
SlidePuzzle/src/Board.java
|
java
|
unlicense
|
Implement split image board with a variable number of tiles.
|
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Board extends JPanel {
private JButton[][] buttons = new JButton[5][5];
public Board() {
super(new GridLayout(5,5));
for(int row=0; row<buttons.length; row++){
for(int col=0; col<buttons.length; col++){
JButton b = new JButton ("("+row+","+col+")");
this.buttons[row][col] = b;
this.add(b);
}
}
}
public JButton getSpot(int x, int y) {
return buttons[x][y];
}
}
|
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Board extends JPanel {
Tile[][] buttons;
public Board(int rows, int cols) {
super(new GridLayout(rows, cols));
buttons = new Tile[rows][cols];
BufferedImage puzzle = null;
try {
puzzle = ImageIO.read(new File("Images/pic1.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
int width = puzzle.getWidth();
int height = puzzle.getHeight();
for(int row = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
Tile tile = new Tile(row, col);
buttons[row][col] = tile;
if (!(row == 0 && col == 0)) {
BufferedImage cropped = puzzle.getSubimage(
col * width / cols, row * height / rows, width / cols, height / rows);
tile.setIcon(new ImageIcon(cropped));
}
tile.setBackground(Color.GRAY);
//tile.addActionListener(new TileListener());
this.add(tile);
}
}
}
public void checkIfComplete() {
for (Tile[] tiles : buttons) {
for (Tile tile : tiles) {
if (!tile.hasRightImage()) {
return;
}
}
}
// Window.endGame();
}
}
| 47
| 21
| 1
|
mixed
|
--- a/SlidePuzzle/src/Board.java
+++ b/SlidePuzzle/src/Board.java
@@ -1,27 +1,53 @@
+
+import java.awt.Color;
import java.awt.GridLayout;
-import javax.swing.JButton;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+
+import javax.imageio.ImageIO;
+import javax.swing.ImageIcon;
import javax.swing.JPanel;
+public class Board extends JPanel {
+ Tile[][] buttons;
-public class Board extends JPanel {
- private JButton[][] buttons = new JButton[5][5];
+ public Board(int rows, int cols) {
+ super(new GridLayout(rows, cols));
+ buttons = new Tile[rows][cols];
+ BufferedImage puzzle = null;
+ try {
+ puzzle = ImageIO.read(new File("Images/pic1.jpg"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ int width = puzzle.getWidth();
+ int height = puzzle.getHeight();
- public Board() {
- super(new GridLayout(5,5));
-
- for(int row=0; row<buttons.length; row++){
- for(int col=0; col<buttons.length; col++){
-
- JButton b = new JButton ("("+row+","+col+")");
- this.buttons[row][col] = b;
- this.add(b);
-
- }
- }
-
- }
-
- public JButton getSpot(int x, int y) {
- return buttons[x][y];
- }
+ for(int row = 0; row < rows; row++){
+ for(int col = 0; col < cols; col++){
+ Tile tile = new Tile(row, col);
+ buttons[row][col] = tile;
+ if (!(row == 0 && col == 0)) {
+ BufferedImage cropped = puzzle.getSubimage(
+ col * width / cols, row * height / rows, width / cols, height / rows);
+ tile.setIcon(new ImageIcon(cropped));
+ }
+ tile.setBackground(Color.GRAY);
+ //tile.addActionListener(new TileListener());
+ this.add(tile);
+ }
+ }
+ }
+
+ public void checkIfComplete() {
+ for (Tile[] tiles : buttons) {
+ for (Tile tile : tiles) {
+ if (!tile.hasRightImage()) {
+ return;
+ }
+ }
+ }
+// Window.endGame();
+ }
|
--- a/SlidePuzzle/src/Board.java
+++ b/SlidePuzzle/src/Board.java
@@ ... @@
+
+import java.awt.Color;
import java.awt.GridLayout;
-import javax.swing.JButton;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+
+import javax.imageio.ImageIO;
+import javax.swing.ImageIcon;
import javax.swing.JPanel;
+public class Board extends JPanel {
+ Tile[][] buttons;
-public class Board extends JPanel {
- private JButton[][] buttons = new JButton[5][5];
+ public Board(int rows, int cols) {
+ super(new GridLayout(rows, cols));
+ buttons = new Tile[rows][cols];
+ BufferedImage puzzle = null;
+ try {
+ puzzle = ImageIO.read(new File("Images/pic1.jpg"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ int width = puzzle.getWidth();
+ int height = puzzle.getHeight();
- public Board() {
- super(new GridLayout(5,5));
-
- for(int row=0; row<buttons.length; row++){
- for(int col=0; col<buttons.length; col++){
-
- JButton b = new JButton ("("+row+","+col+")");
- this.buttons[row][col] = b;
- this.add(b);
-
- }
- }
-
- }
-
- public JButton getSpot(int x, int y) {
- return buttons[x][y];
- }
+ for(int row = 0; row < rows; row++){
+ for(int col = 0; col < cols; col++){
+ Tile tile = new Tile(row, col);
+ buttons[row][col] = tile;
+ if (!(row == 0 && col == 0)) {
+ BufferedImage cropped = puzzle.getSubimage(
+ col * width / cols, row * height / rows, width / cols, height / rows);
+ tile.setIcon(new ImageIcon(cropped));
+ }
+ tile.setBackground(Color.GRAY);
+ //tile.addActionListener(new TileListener());
+ this.add(tile);
+ }
+ }
+ }
+
+ public void checkIfComplete() {
+ for (Tile[] tiles : buttons) {
+ for (Tile tile : tiles) {
+ if (!tile.hasRightImage()) {
+ return;
+ }
+ }
+ }
+// Window.endGame();
+ }
|
--- a/SlidePuzzle/src/Board.java
+++ b/SlidePuzzle/src/Board.java
@@ -1,27 +1,53 @@
ADD
ADD import java.awt.Color;
CON import java.awt.GridLayout;
DEL import javax.swing.JButton;
ADD import java.awt.image.BufferedImage;
ADD import java.io.File;
ADD import java.io.IOException;
ADD
ADD import javax.imageio.ImageIO;
ADD import javax.swing.ImageIcon;
CON import javax.swing.JPanel;
CON
ADD public class Board extends JPanel {
ADD Tile[][] buttons;
CON
DEL public class Board extends JPanel {
DEL private JButton[][] buttons = new JButton[5][5];
ADD public Board(int rows, int cols) {
ADD super(new GridLayout(rows, cols));
ADD buttons = new Tile[rows][cols];
ADD BufferedImage puzzle = null;
ADD try {
ADD puzzle = ImageIO.read(new File("Images/pic1.jpg"));
ADD } catch (IOException e) {
ADD e.printStackTrace();
ADD }
ADD int width = puzzle.getWidth();
ADD int height = puzzle.getHeight();
CON
DEL public Board() {
DEL super(new GridLayout(5,5));
DEL
DEL for(int row=0; row<buttons.length; row++){
DEL for(int col=0; col<buttons.length; col++){
DEL
DEL JButton b = new JButton ("("+row+","+col+")");
DEL this.buttons[row][col] = b;
DEL this.add(b);
DEL
DEL }
DEL }
DEL
DEL }
DEL
DEL public JButton getSpot(int x, int y) {
DEL return buttons[x][y];
DEL }
ADD for(int row = 0; row < rows; row++){
ADD for(int col = 0; col < cols; col++){
ADD Tile tile = new Tile(row, col);
ADD buttons[row][col] = tile;
ADD if (!(row == 0 && col == 0)) {
ADD BufferedImage cropped = puzzle.getSubimage(
ADD col * width / cols, row * height / rows, width / cols, height / rows);
ADD tile.setIcon(new ImageIcon(cropped));
ADD }
ADD tile.setBackground(Color.GRAY);
ADD //tile.addActionListener(new TileListener());
ADD this.add(tile);
ADD }
ADD }
ADD }
ADD
ADD public void checkIfComplete() {
ADD for (Tile[] tiles : buttons) {
ADD for (Tile tile : tiles) {
ADD if (!tile.hasRightImage()) {
ADD return;
ADD }
ADD }
ADD }
ADD // Window.endGame();
ADD }
CON
|
<<<<<<< SEARCH
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Board extends JPanel {
private JButton[][] buttons = new JButton[5][5];
public Board() {
super(new GridLayout(5,5));
for(int row=0; row<buttons.length; row++){
for(int col=0; col<buttons.length; col++){
JButton b = new JButton ("("+row+","+col+")");
this.buttons[row][col] = b;
this.add(b);
}
}
}
public JButton getSpot(int x, int y) {
return buttons[x][y];
}
}
=======
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Board extends JPanel {
Tile[][] buttons;
public Board(int rows, int cols) {
super(new GridLayout(rows, cols));
buttons = new Tile[rows][cols];
BufferedImage puzzle = null;
try {
puzzle = ImageIO.read(new File("Images/pic1.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
int width = puzzle.getWidth();
int height = puzzle.getHeight();
for(int row = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
Tile tile = new Tile(row, col);
buttons[row][col] = tile;
if (!(row == 0 && col == 0)) {
BufferedImage cropped = puzzle.getSubimage(
col * width / cols, row * height / rows, width / cols, height / rows);
tile.setIcon(new ImageIcon(cropped));
}
tile.setBackground(Color.GRAY);
//tile.addActionListener(new TileListener());
this.add(tile);
}
}
}
public void checkIfComplete() {
for (Tile[] tiles : buttons) {
for (Tile tile : tiles) {
if (!tile.hasRightImage()) {
return;
}
}
}
// Window.endGame();
}
}
>>>>>>> REPLACE
|
jstourac/undertow
|
91b56ee8e376ffe1e26e1c397108b10c2ff00ff7
|
core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
|
java
|
apache-2.0
|
Add to secure hash map test
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.util;
import org.junit.Test;
/**
* @author Stuart Douglas
*/
public class SecureHashMapTestCase {
@Test
public void testGetNonExistentDoesNotNPE(){
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
map.get("nothing");
}
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.util;
import io.undertow.server.session.SecureRandomSessionIdGenerator;
import io.undertow.server.session.SessionIdGenerator;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* @author Stuart Douglas
*/
public class SecureHashMapTestCase {
@Test
public void testGetNonExistentDoesNotNPE() {
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
map.get("nothing");
}
@Test
public void testLotsOfPutsAndGets() {
SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
final Map<String, String> reference = new HashMap<String, String>();
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
for (int i = 0; i < 10000; ++i) {
String key = generator.createSessionId();
String value = generator.createSessionId();
map.put(key, value);
reference.put(key, value);
}
for (Map.Entry<String, String> entry : reference.entrySet()) {
Assert.assertEquals(entry.getValue(), map.get(entry.getKey()));
Assert.assertEquals(entry.getValue(), map.remove(entry.getKey()));
}
Assert.assertEquals(0, map.size());
}
}
| 29
| 1
| 3
|
mixed
|
--- a/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
+++ b/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
@@ -20,3 +20,9 @@
+import io.undertow.server.session.SecureRandomSessionIdGenerator;
+import io.undertow.server.session.SessionIdGenerator;
+import org.junit.Assert;
import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
@@ -28,3 +34,3 @@
@Test
- public void testGetNonExistentDoesNotNPE(){
+ public void testGetNonExistentDoesNotNPE() {
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
@@ -32,2 +38,24 @@
}
+
+
+ @Test
+ public void testLotsOfPutsAndGets() {
+
+ SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
+ final Map<String, String> reference = new HashMap<String, String>();
+ final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
+ for (int i = 0; i < 10000; ++i) {
+ String key = generator.createSessionId();
+ String value = generator.createSessionId();
+ map.put(key, value);
+ reference.put(key, value);
+ }
+ for (Map.Entry<String, String> entry : reference.entrySet()) {
+ Assert.assertEquals(entry.getValue(), map.get(entry.getKey()));
+ Assert.assertEquals(entry.getValue(), map.remove(entry.getKey()));
+ }
+ Assert.assertEquals(0, map.size());
+ }
+
+
}
|
--- a/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
+++ b/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
@@ ... @@
+import io.undertow.server.session.SecureRandomSessionIdGenerator;
+import io.undertow.server.session.SessionIdGenerator;
+import org.junit.Assert;
import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
@@ ... @@
@Test
- public void testGetNonExistentDoesNotNPE(){
+ public void testGetNonExistentDoesNotNPE() {
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
@@ ... @@
}
+
+
+ @Test
+ public void testLotsOfPutsAndGets() {
+
+ SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
+ final Map<String, String> reference = new HashMap<String, String>();
+ final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
+ for (int i = 0; i < 10000; ++i) {
+ String key = generator.createSessionId();
+ String value = generator.createSessionId();
+ map.put(key, value);
+ reference.put(key, value);
+ }
+ for (Map.Entry<String, String> entry : reference.entrySet()) {
+ Assert.assertEquals(entry.getValue(), map.get(entry.getKey()));
+ Assert.assertEquals(entry.getValue(), map.remove(entry.getKey()));
+ }
+ Assert.assertEquals(0, map.size());
+ }
+
+
}
|
--- a/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
+++ b/core/src/test/java/io/undertow/util/SecureHashMapTestCase.java
@@ -20,3 +20,9 @@
CON
ADD import io.undertow.server.session.SecureRandomSessionIdGenerator;
ADD import io.undertow.server.session.SessionIdGenerator;
ADD import org.junit.Assert;
CON import org.junit.Test;
ADD
ADD import java.util.HashMap;
ADD import java.util.Map;
CON
@@ -28,3 +34,3 @@
CON @Test
DEL public void testGetNonExistentDoesNotNPE(){
ADD public void testGetNonExistentDoesNotNPE() {
CON final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
@@ -32,2 +38,24 @@
CON }
ADD
ADD
ADD @Test
ADD public void testLotsOfPutsAndGets() {
ADD
ADD SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
ADD final Map<String, String> reference = new HashMap<String, String>();
ADD final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
ADD for (int i = 0; i < 10000; ++i) {
ADD String key = generator.createSessionId();
ADD String value = generator.createSessionId();
ADD map.put(key, value);
ADD reference.put(key, value);
ADD }
ADD for (Map.Entry<String, String> entry : reference.entrySet()) {
ADD Assert.assertEquals(entry.getValue(), map.get(entry.getKey()));
ADD Assert.assertEquals(entry.getValue(), map.remove(entry.getKey()));
ADD }
ADD Assert.assertEquals(0, map.size());
ADD }
ADD
ADD
CON }
|
<<<<<<< SEARCH
package io.undertow.util;
import org.junit.Test;
/**
=======
package io.undertow.util;
import io.undertow.server.session.SecureRandomSessionIdGenerator;
import io.undertow.server.session.SessionIdGenerator;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
@Test
public void testGetNonExistentDoesNotNPE(){
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
map.get("nothing");
}
}
=======
@Test
public void testGetNonExistentDoesNotNPE() {
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
map.get("nothing");
}
@Test
public void testLotsOfPutsAndGets() {
SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
final Map<String, String> reference = new HashMap<String, String>();
final SecureHashMap<String, String> map = new SecureHashMap<String, String>();
for (int i = 0; i < 10000; ++i) {
String key = generator.createSessionId();
String value = generator.createSessionId();
map.put(key, value);
reference.put(key, value);
}
for (Map.Entry<String, String> entry : reference.entrySet()) {
Assert.assertEquals(entry.getValue(), map.get(entry.getKey()));
Assert.assertEquals(entry.getValue(), map.remove(entry.getKey()));
}
Assert.assertEquals(0, map.size());
}
}
>>>>>>> REPLACE
|
girder/girder_worker
|
e9e4c622ff667e475986e1544ec78b0604b8a511
|
girder_worker/tasks.py
|
python
|
apache-2.0
|
Fix typo from bad conflict resolution during merge
|
import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
kwargs['_job_manager'] = task.job_manager \
if hasattr(task, 'job_manager') else None
kwargs['status'] = JobStatus.RUNNING
return core.run(*pargs, **kwargs)
@app.task(name='girder_worker.convert')
def convert(*pargs, **kwargs):
return core.convert(*pargs, **kwargs)
@app.task(name='girder_worker.validators')
def validators(*pargs, **kwargs):
_type, _format = pargs
nodes = []
for (node, data) in core.format.conv_graph.nodes(data=True):
if ((_type is None) or (_type == node.type)) and \
((_format is None) or (_format == node.format)):
nodes.append({'type': node.type,
'format': node.format,
'validator': data})
return nodes
|
import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task, 'job_manager') else None
kwargs['status'] = JobStatus.RUNNING
return core.run(*pargs, **kwargs)
@app.task(name='girder_worker.convert')
def convert(*pargs, **kwargs):
return core.convert(*pargs, **kwargs)
@app.task(name='girder_worker.validators')
def validators(*pargs, **kwargs):
_type, _format = pargs
nodes = []
for (node, data) in core.format.conv_graph.nodes(data=True):
if ((_type is None) or (_type == node.type)) and \
((_format is None) or (_format == node.format)):
nodes.append({'type': node.type,
'format': node.format,
'validator': data})
return nodes
| 1
| 4
| 1
|
mixed
|
--- a/girder_worker/tasks.py
+++ b/girder_worker/tasks.py
@@ -10,6 +10,3 @@
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
-def run(tasks, *pargs, **kwargs):
- jobInfo = kwargs.pop('jobInfo', {})
- retval = 0
-
+def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
|
--- a/girder_worker/tasks.py
+++ b/girder_worker/tasks.py
@@ ... @@
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
-def run(tasks, *pargs, **kwargs):
- jobInfo = kwargs.pop('jobInfo', {})
- retval = 0
-
+def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
|
--- a/girder_worker/tasks.py
+++ b/girder_worker/tasks.py
@@ -10,6 +10,3 @@
CON @app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
DEL def run(tasks, *pargs, **kwargs):
DEL jobInfo = kwargs.pop('jobInfo', {})
DEL retval = 0
DEL
ADD def run(task, *pargs, **kwargs):
CON kwargs['_job_manager'] = task.job_manager \
|
<<<<<<< SEARCH
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
kwargs['_job_manager'] = task.job_manager \
if hasattr(task, 'job_manager') else None
=======
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task, 'job_manager') else None
>>>>>>> REPLACE
|
pyamsoft/pydroid
|
05fe1bd28984e80dfdfe04f2ecc5e531ad6cd481
|
pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
|
kotlin
|
apache-2.0
|
Enforce scheduler at creation time
|
/*
* Copyright (C) 2018 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.presenter
import io.reactivex.Scheduler
abstract class SchedulerPresenter<V : Any> protected constructor(
protected val computationScheduler: Scheduler,
protected val ioScheduler: Scheduler,
protected val mainThreadScheduler: Scheduler
) : Presenter<V>()
|
/*
* Copyright (C) 2018 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.presenter
import com.pyamsoft.pydroid.data.enforceComputation
import com.pyamsoft.pydroid.data.enforceIo
import com.pyamsoft.pydroid.data.enforceMainThread
import io.reactivex.Scheduler
abstract class SchedulerPresenter<V : Any> protected constructor(
protected val computationScheduler: Scheduler,
protected val ioScheduler: Scheduler,
protected val mainThreadScheduler: Scheduler,
enforce: Boolean = true
) : Presenter<V>() {
constructor(
computationScheduler: Scheduler,
ioScheduler: Scheduler,
mainThreadScheduler: Scheduler
) : this(computationScheduler, ioScheduler, mainThreadScheduler, enforce = false)
init {
if (enforce) {
computationScheduler.enforceComputation()
ioScheduler.enforceIo()
mainThreadScheduler.enforceMainThread()
}
}
}
| 21
| 2
| 2
|
mixed
|
--- a/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
+++ b/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
@@ -18,2 +18,5 @@
+import com.pyamsoft.pydroid.data.enforceComputation
+import com.pyamsoft.pydroid.data.enforceIo
+import com.pyamsoft.pydroid.data.enforceMainThread
import io.reactivex.Scheduler
@@ -23,3 +26,19 @@
protected val ioScheduler: Scheduler,
- protected val mainThreadScheduler: Scheduler
-) : Presenter<V>()
+ protected val mainThreadScheduler: Scheduler,
+ enforce: Boolean = true
+) : Presenter<V>() {
+
+ constructor(
+ computationScheduler: Scheduler,
+ ioScheduler: Scheduler,
+ mainThreadScheduler: Scheduler
+ ) : this(computationScheduler, ioScheduler, mainThreadScheduler, enforce = false)
+
+ init {
+ if (enforce) {
+ computationScheduler.enforceComputation()
+ ioScheduler.enforceIo()
+ mainThreadScheduler.enforceMainThread()
+ }
+ }
+}
|
--- a/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
+++ b/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
@@ ... @@
+import com.pyamsoft.pydroid.data.enforceComputation
+import com.pyamsoft.pydroid.data.enforceIo
+import com.pyamsoft.pydroid.data.enforceMainThread
import io.reactivex.Scheduler
@@ ... @@
protected val ioScheduler: Scheduler,
- protected val mainThreadScheduler: Scheduler
-) : Presenter<V>()
+ protected val mainThreadScheduler: Scheduler,
+ enforce: Boolean = true
+) : Presenter<V>() {
+
+ constructor(
+ computationScheduler: Scheduler,
+ ioScheduler: Scheduler,
+ mainThreadScheduler: Scheduler
+ ) : this(computationScheduler, ioScheduler, mainThreadScheduler, enforce = false)
+
+ init {
+ if (enforce) {
+ computationScheduler.enforceComputation()
+ ioScheduler.enforceIo()
+ mainThreadScheduler.enforceMainThread()
+ }
+ }
+}
|
--- a/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
+++ b/pydroid/src/main/java/com/pyamsoft/pydroid/presenter/SchedulerPresenter.kt
@@ -18,2 +18,5 @@
CON
ADD import com.pyamsoft.pydroid.data.enforceComputation
ADD import com.pyamsoft.pydroid.data.enforceIo
ADD import com.pyamsoft.pydroid.data.enforceMainThread
CON import io.reactivex.Scheduler
@@ -23,3 +26,19 @@
CON protected val ioScheduler: Scheduler,
DEL protected val mainThreadScheduler: Scheduler
DEL ) : Presenter<V>()
ADD protected val mainThreadScheduler: Scheduler,
ADD enforce: Boolean = true
ADD ) : Presenter<V>() {
ADD
ADD constructor(
ADD computationScheduler: Scheduler,
ADD ioScheduler: Scheduler,
ADD mainThreadScheduler: Scheduler
ADD ) : this(computationScheduler, ioScheduler, mainThreadScheduler, enforce = false)
ADD
ADD init {
ADD if (enforce) {
ADD computationScheduler.enforceComputation()
ADD ioScheduler.enforceIo()
ADD mainThreadScheduler.enforceMainThread()
ADD }
ADD }
ADD }
|
<<<<<<< SEARCH
package com.pyamsoft.pydroid.presenter
import io.reactivex.Scheduler
abstract class SchedulerPresenter<V : Any> protected constructor(
protected val computationScheduler: Scheduler,
protected val ioScheduler: Scheduler,
protected val mainThreadScheduler: Scheduler
) : Presenter<V>()
=======
package com.pyamsoft.pydroid.presenter
import com.pyamsoft.pydroid.data.enforceComputation
import com.pyamsoft.pydroid.data.enforceIo
import com.pyamsoft.pydroid.data.enforceMainThread
import io.reactivex.Scheduler
abstract class SchedulerPresenter<V : Any> protected constructor(
protected val computationScheduler: Scheduler,
protected val ioScheduler: Scheduler,
protected val mainThreadScheduler: Scheduler,
enforce: Boolean = true
) : Presenter<V>() {
constructor(
computationScheduler: Scheduler,
ioScheduler: Scheduler,
mainThreadScheduler: Scheduler
) : this(computationScheduler, ioScheduler, mainThreadScheduler, enforce = false)
init {
if (enforce) {
computationScheduler.enforceComputation()
ioScheduler.enforceIo()
mainThreadScheduler.enforceMainThread()
}
}
}
>>>>>>> REPLACE
|
Hacker0x01/coffee-to-es2015-codemod
|
946ac45b84f4c0a4e79323333cca0f7d09ec1283
|
transforms/test/transforms-test.js
|
javascript
|
mit
|
Use require all the way
Babel seems to move `import` statements up the tree, which feels strange to me. For now I decided to just keep using require in this file.
|
import fs from "fs";
import path from "path";
const jscodeshift = require("jscodeshift");
const test = (coffeeOutputFilename, transform) => {
const testName = path.basename(coffeeOutputFilename, ".coffee-output");
it(testName, () => {
const expectedPath = coffeeOutputFilename.replace(".coffee-output", ".expected");
const coffeeOut = fs.readFileSync(coffeeOutputFilename).toString();
const expected = fs.readFileSync(expectedPath).toString();
const output = transform({
path: coffeeOutputFilename,
source: coffeeOut,
}, { jscodeshift }, {});
expect(output.trim()).toEqual(expected.trim());
});
};
const findAndRunTestsForDirectory = directory => {
const filePaths = fs.readdirSync(directory);
const coffeeFiles = filePaths
.map(file => path.join(__dirname, path.basename(directory), file))
.filter(file =>
/\.coffee-output$/.test(file)
);
describe(`#${path.basename(directory)}`, () => {
const transformPath = path.join(directory, "..", "..", path.basename(directory));
const transform = require(transformPath);
coffeeFiles.forEach(coffeeFile => test(coffeeFile, transform));
});
};
const allFiles = fs.readdirSync(`${__dirname}/`);
const directories = allFiles
// Turn paths absolute
.map(file => path.join(__dirname, file))
// Filter out directories
.filter(file => fs.statSync(file).isDirectory());
directories.forEach(findAndRunTestsForDirectory);
|
const fs = require("fs");
const path = require("path");
const jscodeshift = require("jscodeshift");
const test = (coffeeOutputFilename, transform) => {
const testName = path.basename(coffeeOutputFilename, ".coffee-output");
it(testName, () => {
const expectedPath = coffeeOutputFilename.replace(".coffee-output", ".expected");
const coffeeOut = fs.readFileSync(coffeeOutputFilename).toString();
const expected = fs.readFileSync(expectedPath).toString();
const output = transform({
path: coffeeOutputFilename,
source: coffeeOut,
}, { jscodeshift }, {});
expect(output.trim()).toEqual(expected.trim());
});
};
const findAndRunTestsForDirectory = directory => {
const filePaths = fs.readdirSync(directory);
const coffeeFiles = filePaths
.map(file => path.join(__dirname, path.basename(directory), file))
.filter(file =>
/\.coffee-output$/.test(file)
);
describe(`#${path.basename(directory)}`, () => {
const transformPath = path.join(directory, "..", "..", path.basename(directory));
const transform = require(transformPath);
coffeeFiles.forEach(coffeeFile => test(coffeeFile, transform));
});
};
const allFiles = fs.readdirSync(`${__dirname}/`);
const directories = allFiles
// Turn paths absolute
.map(file => path.join(__dirname, file))
// Filter out directories
.filter(file => fs.statSync(file).isDirectory());
directories.forEach(findAndRunTestsForDirectory);
| 2
| 2
| 1
|
mixed
|
--- a/transforms/test/transforms-test.js
+++ b/transforms/test/transforms-test.js
@@ -1,3 +1,3 @@
-import fs from "fs";
-import path from "path";
+const fs = require("fs");
+const path = require("path");
const jscodeshift = require("jscodeshift");
|
--- a/transforms/test/transforms-test.js
+++ b/transforms/test/transforms-test.js
@@ ... @@
-import fs from "fs";
-import path from "path";
+const fs = require("fs");
+const path = require("path");
const jscodeshift = require("jscodeshift");
|
--- a/transforms/test/transforms-test.js
+++ b/transforms/test/transforms-test.js
@@ -1,3 +1,3 @@
DEL import fs from "fs";
DEL import path from "path";
ADD const fs = require("fs");
ADD const path = require("path");
CON const jscodeshift = require("jscodeshift");
|
<<<<<<< SEARCH
import fs from "fs";
import path from "path";
const jscodeshift = require("jscodeshift");
=======
const fs = require("fs");
const path = require("path");
const jscodeshift = require("jscodeshift");
>>>>>>> REPLACE
|
realityforge-experiments/star-punk
|
295e8e430555d85dc19e5b5977e45b84b29be25e
|
src/main/java/starpunk/GameScreen.java
|
java
|
apache-2.0
|
Clear the screen on render
|
package starpunk;
import com.badlogic.gdx.Screen;
public class GameScreen
implements Screen
{
@Override
public void render( final float delta )
{
}
@Override
public void resize( int width, int height )
{
}
@Override
public void show()
{
}
@Override
public void hide()
{
}
@Override
public void pause()
{
}
@Override
public void resume()
{
}
@Override
public void dispose()
{
}
}
|
package starpunk;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
public class GameScreen
implements Screen
{
@Override
public void render( final float delta )
{
Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
}
@Override
public void resize( int width, int height )
{
}
@Override
public void show()
{
}
@Override
public void hide()
{
}
@Override
public void pause()
{
}
@Override
public void resume()
{
}
@Override
public void dispose()
{
}
}
| 3
| 0
| 2
|
add_only
|
--- a/src/main/java/starpunk/GameScreen.java
+++ b/src/main/java/starpunk/GameScreen.java
@@ -2,3 +2,5 @@
+import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
+import com.badlogic.gdx.graphics.GL10;
@@ -10,2 +12,3 @@
{
+ Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
}
|
--- a/src/main/java/starpunk/GameScreen.java
+++ b/src/main/java/starpunk/GameScreen.java
@@ ... @@
+import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
+import com.badlogic.gdx.graphics.GL10;
@@ ... @@
{
+ Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
}
|
--- a/src/main/java/starpunk/GameScreen.java
+++ b/src/main/java/starpunk/GameScreen.java
@@ -2,3 +2,5 @@
CON
ADD import com.badlogic.gdx.Gdx;
CON import com.badlogic.gdx.Screen;
ADD import com.badlogic.gdx.graphics.GL10;
CON
@@ -10,2 +12,3 @@
CON {
ADD Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
CON }
|
<<<<<<< SEARCH
package starpunk;
import com.badlogic.gdx.Screen;
public class GameScreen
=======
package starpunk;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
public class GameScreen
>>>>>>> REPLACE
<<<<<<< SEARCH
public void render( final float delta )
{
}
=======
public void render( final float delta )
{
Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
}
>>>>>>> REPLACE
|
Logicalshift/gossyp
|
966bf159c612692d059602153177d68676f29398
|
src/script/lex_script_tool.rs
|
rust
|
apache-2.0
|
Add some tests to make sure we can parse the syntax JSON file
|
use serde_json::*;
use super::super::lex::*;
///
/// Creates a lexing tool for the scripting language
///
pub fn create_lex_script_tool() -> StringLexingTool {
// Parse the lexer
let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json")).unwrap();
// The name isn't used here, but define it anyway
let lex_defn = LexToolInput {
new_tool_name: String::from("lex-script"),
symbols: script_json
};
// Create the lexing tool with this definition
StringLexingTool::from_lex_tool_input(&lex_defn)
}
|
use serde_json::*;
use super::super::lex::*;
///
/// Creates a lexing tool for the scripting language
///
pub fn create_lex_script_tool() -> StringLexingTool {
// Parse the lexer
let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json")).unwrap();
// The name isn't used here, but define it anyway
let lex_defn = LexToolInput {
new_tool_name: String::from("lex-script"),
symbols: script_json
};
// Create the lexing tool with this definition
StringLexingTool::from_lex_tool_input(&lex_defn)
}
#[cfg(test)]
mod test {
use std::error::Error;
use super::*;
#[test]
fn can_parse_syntax_json() {
let script_json = from_str::<Value>(include_str!("syntax_lexer.json"));
if script_json.is_err() {
println!("{:?}", script_json);
println!("{:?}", script_json.unwrap_err().description());
assert!(false);
}
}
#[test]
fn json_can_be_deserialized() {
let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json"));
if script_json.is_err() {
println!("{:?}", script_json);
}
script_json.unwrap();
}
#[test]
fn can_create_tool() {
let _tool = create_lex_script_tool();
}
}
| 34
| 0
| 1
|
add_only
|
--- a/src/script/lex_script_tool.rs
+++ b/src/script/lex_script_tool.rs
@@ -20 +20,35 @@
}
+
+#[cfg(test)]
+mod test {
+ use std::error::Error;
+ use super::*;
+
+ #[test]
+ fn can_parse_syntax_json() {
+ let script_json = from_str::<Value>(include_str!("syntax_lexer.json"));
+
+ if script_json.is_err() {
+ println!("{:?}", script_json);
+ println!("{:?}", script_json.unwrap_err().description());
+
+ assert!(false);
+ }
+ }
+
+ #[test]
+ fn json_can_be_deserialized() {
+ let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json"));
+
+ if script_json.is_err() {
+ println!("{:?}", script_json);
+ }
+
+ script_json.unwrap();
+ }
+
+ #[test]
+ fn can_create_tool() {
+ let _tool = create_lex_script_tool();
+ }
+}
|
--- a/src/script/lex_script_tool.rs
+++ b/src/script/lex_script_tool.rs
@@ ... @@
}
+
+#[cfg(test)]
+mod test {
+ use std::error::Error;
+ use super::*;
+
+ #[test]
+ fn can_parse_syntax_json() {
+ let script_json = from_str::<Value>(include_str!("syntax_lexer.json"));
+
+ if script_json.is_err() {
+ println!("{:?}", script_json);
+ println!("{:?}", script_json.unwrap_err().description());
+
+ assert!(false);
+ }
+ }
+
+ #[test]
+ fn json_can_be_deserialized() {
+ let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json"));
+
+ if script_json.is_err() {
+ println!("{:?}", script_json);
+ }
+
+ script_json.unwrap();
+ }
+
+ #[test]
+ fn can_create_tool() {
+ let _tool = create_lex_script_tool();
+ }
+}
|
--- a/src/script/lex_script_tool.rs
+++ b/src/script/lex_script_tool.rs
@@ -20 +20,35 @@
CON }
ADD
ADD #[cfg(test)]
ADD mod test {
ADD use std::error::Error;
ADD use super::*;
ADD
ADD #[test]
ADD fn can_parse_syntax_json() {
ADD let script_json = from_str::<Value>(include_str!("syntax_lexer.json"));
ADD
ADD if script_json.is_err() {
ADD println!("{:?}", script_json);
ADD println!("{:?}", script_json.unwrap_err().description());
ADD
ADD assert!(false);
ADD }
ADD }
ADD
ADD #[test]
ADD fn json_can_be_deserialized() {
ADD let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json"));
ADD
ADD if script_json.is_err() {
ADD println!("{:?}", script_json);
ADD }
ADD
ADD script_json.unwrap();
ADD }
ADD
ADD #[test]
ADD fn can_create_tool() {
ADD let _tool = create_lex_script_tool();
ADD }
ADD }
|
<<<<<<< SEARCH
StringLexingTool::from_lex_tool_input(&lex_defn)
}
=======
StringLexingTool::from_lex_tool_input(&lex_defn)
}
#[cfg(test)]
mod test {
use std::error::Error;
use super::*;
#[test]
fn can_parse_syntax_json() {
let script_json = from_str::<Value>(include_str!("syntax_lexer.json"));
if script_json.is_err() {
println!("{:?}", script_json);
println!("{:?}", script_json.unwrap_err().description());
assert!(false);
}
}
#[test]
fn json_can_be_deserialized() {
let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json"));
if script_json.is_err() {
println!("{:?}", script_json);
}
script_json.unwrap();
}
#[test]
fn can_create_tool() {
let _tool = create_lex_script_tool();
}
}
>>>>>>> REPLACE
|
OpenMined/PySyft
|
8be6b576007f89fad50ea1dfacad46614c0a97c5
|
apps/domain/src/main/core/exceptions.py
|
python
|
apache-2.0
|
ADD new exception -> EnvironmentNotFound!
|
"""Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operation!"
super().__init__(message)
class RoleNotFoundError(PyGridError):
def __init__(self):
message = "Role ID not found!"
super().__init__(message)
class UserNotFoundError(PyGridError):
def __init__(self):
message = "User not found!"
super().__init__(message)
class GroupNotFoundError(PyGridError):
def __init__(self):
message = "Group ID not found!"
super().__init__(message)
class InvalidRequestKeyError(PyGridError):
def __init__(self):
message = "Invalid request key!"
super().__init__(message)
class InvalidCredentialsError(PyGridError):
def __init__(self):
message = "Invalid credentials!"
super().__init__(message)
class MissingRequestKeyError(PyGridError):
def __init__(self, message=""):
if not message:
message = "Missing request key!"
super().__init__(message)
|
"""Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operation!"
super().__init__(message)
class RoleNotFoundError(PyGridError):
def __init__(self):
message = "Role ID not found!"
super().__init__(message)
class UserNotFoundError(PyGridError):
def __init__(self):
message = "User not found!"
super().__init__(message)
class EnvironmentNotFoundError(PyGridError):
def __init__(self):
message = "Environment not found!"
super().__init__(message)
class GroupNotFoundError(PyGridError):
def __init__(self):
message = "Group ID not found!"
super().__init__(message)
class InvalidRequestKeyError(PyGridError):
def __init__(self):
message = "Invalid request key!"
super().__init__(message)
class InvalidCredentialsError(PyGridError):
def __init__(self):
message = "Invalid credentials!"
super().__init__(message)
class MissingRequestKeyError(PyGridError):
def __init__(self, message=""):
if not message:
message = "Missing request key!"
super().__init__(message)
| 6
| 0
| 1
|
add_only
|
--- a/apps/domain/src/main/core/exceptions.py
+++ b/apps/domain/src/main/core/exceptions.py
@@ -27,2 +27,8 @@
+class EnvironmentNotFoundError(PyGridError):
+ def __init__(self):
+ message = "Environment not found!"
+ super().__init__(message)
+
+
class GroupNotFoundError(PyGridError):
|
--- a/apps/domain/src/main/core/exceptions.py
+++ b/apps/domain/src/main/core/exceptions.py
@@ ... @@
+class EnvironmentNotFoundError(PyGridError):
+ def __init__(self):
+ message = "Environment not found!"
+ super().__init__(message)
+
+
class GroupNotFoundError(PyGridError):
|
--- a/apps/domain/src/main/core/exceptions.py
+++ b/apps/domain/src/main/core/exceptions.py
@@ -27,2 +27,8 @@
CON
ADD class EnvironmentNotFoundError(PyGridError):
ADD def __init__(self):
ADD message = "Environment not found!"
ADD super().__init__(message)
ADD
ADD
CON class GroupNotFoundError(PyGridError):
|
<<<<<<< SEARCH
class GroupNotFoundError(PyGridError):
def __init__(self):
=======
class EnvironmentNotFoundError(PyGridError):
def __init__(self):
message = "Environment not found!"
super().__init__(message)
class GroupNotFoundError(PyGridError):
def __init__(self):
>>>>>>> REPLACE
|
digammas/damas
|
fd945057e6539c6d8b3d8d8f546152241f5d9c7c
|
solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
|
kotlin
|
mit
|
Fix error in role name
* Fix error introduced by commit 10226c.
|
package solutions.digamma.damas.jcr.repo
import solutions.digamma.damas.auth.JaasConfiguration
import solutions.digamma.damas.jcr.content.JcrFile
import solutions.digamma.damas.jcr.names.TypeNamespace
import solutions.digamma.damas.jcr.repo.job.NodeCreation
import solutions.digamma.damas.jcr.repo.job.RepositoryJob
import solutions.digamma.damas.jcr.sys.SystemRole
import solutions.digamma.damas.jcr.user.JcrSubject
import java.security.Principal
import javax.inject.Singleton
import javax.jcr.nodetype.NodeType
import javax.jcr.security.Privilege
/**
* Built-in repository job.
*
* @author Ahmad Shahwan
*/
@Singleton
internal object TopLevelNodeCreationJob : RepositoryJob {
/**
* List convert nodes to be created.
*
* @return
*/
override val nodes: List<NodeCreation> = listOf(
NodeCreation(
path = ".",
type = NodeType.NT_BASE,
accessRights = mapOf(
JaasConfiguration.SYS_SHADOW to listOf(Privilege.JCR_ALL),
),
),
NodeCreation(
path = JcrFile.ROOT_PATH,
type = TypeNamespace.FOLDER,
),
NodeCreation(JcrSubject.ROOT_PATH, TypeNamespace.DIRECTORY)
)
}
|
package solutions.digamma.damas.jcr.repo
import solutions.digamma.damas.auth.JaasConfiguration
import solutions.digamma.damas.jcr.content.JcrFile
import solutions.digamma.damas.jcr.names.TypeNamespace
import solutions.digamma.damas.jcr.repo.job.NodeCreation
import solutions.digamma.damas.jcr.repo.job.RepositoryJob
import solutions.digamma.damas.jcr.sys.SystemRole
import solutions.digamma.damas.jcr.user.JcrSubject
import java.security.Principal
import javax.inject.Singleton
import javax.jcr.nodetype.NodeType
import javax.jcr.security.Privilege
/**
* Built-in repository job.
*
* @author Ahmad Shahwan
*/
@Singleton
internal object TopLevelNodeCreationJob : RepositoryJob {
/**
* List convert nodes to be created.
*
* @return
*/
override val nodes: List<NodeCreation> = listOf(
NodeCreation(
path = ".",
type = NodeType.NT_BASE,
accessRights = mapOf(
SystemRole.READWRITE.principalName to listOf(Privilege.JCR_ALL),
),
),
NodeCreation(
path = JcrFile.ROOT_PATH,
type = TypeNamespace.FOLDER,
),
NodeCreation(JcrSubject.ROOT_PATH, TypeNamespace.DIRECTORY)
)
}
| 1
| 1
| 1
|
mixed
|
--- a/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
+++ b/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
@@ -32,3 +32,3 @@
accessRights = mapOf(
- JaasConfiguration.SYS_SHADOW to listOf(Privilege.JCR_ALL),
+ SystemRole.READWRITE.principalName to listOf(Privilege.JCR_ALL),
),
|
--- a/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
+++ b/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
@@ ... @@
accessRights = mapOf(
- JaasConfiguration.SYS_SHADOW to listOf(Privilege.JCR_ALL),
+ SystemRole.READWRITE.principalName to listOf(Privilege.JCR_ALL),
),
|
--- a/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
+++ b/solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/repo/TopLevelNodeCreationJob.kt
@@ -32,3 +32,3 @@
CON accessRights = mapOf(
DEL JaasConfiguration.SYS_SHADOW to listOf(Privilege.JCR_ALL),
ADD SystemRole.READWRITE.principalName to listOf(Privilege.JCR_ALL),
CON ),
|
<<<<<<< SEARCH
type = NodeType.NT_BASE,
accessRights = mapOf(
JaasConfiguration.SYS_SHADOW to listOf(Privilege.JCR_ALL),
),
),
=======
type = NodeType.NT_BASE,
accessRights = mapOf(
SystemRole.READWRITE.principalName to listOf(Privilege.JCR_ALL),
),
),
>>>>>>> REPLACE
|
breadwallet/breadwallet-core
|
af28b26d906cc51fc5e592e7b77df997efd6062f
|
Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
|
java
|
mit
|
CORE-601: Update Java handling of eth_blockNumber RPC result
|
/*
* Created by Michael Carrara <michael.carrara@breadwallet.com> on 7/1/19.
* Copyright (c) 2019 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.breadwallet.crypto.blockchaindb.apis.brd;
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
import com.breadwallet.crypto.utility.CompletionHandler;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.json.JSONObject;
public class EthBlockApi {
private final BrdApiClient client;
public EthBlockApi(BrdApiClient client) {
this.client = client;
}
public void getBlockNumberAsEth(String networkName, int rid, CompletionHandler<String, QueryError> handler) {
JSONObject json = new JSONObject(ImmutableMap.of(
"jsonrpc", "2.0",
"method", "eth_blockNumber",
"params", ImmutableList.of(),
"id", rid
));
client.sendJsonRequest(networkName, json, handler);
}
}
|
/*
* Created by Michael Carrara <michael.carrara@breadwallet.com> on 7/1/19.
* Copyright (c) 2019 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.breadwallet.crypto.blockchaindb.apis.brd;
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
import com.breadwallet.crypto.blockchaindb.errors.QueryNoDataError;
import com.breadwallet.crypto.utility.CompletionHandler;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.json.JSONObject;
public class EthBlockApi {
private final BrdApiClient client;
public EthBlockApi(BrdApiClient client) {
this.client = client;
}
public void getBlockNumberAsEth(String networkName, int rid, CompletionHandler<String, QueryError> handler) {
JSONObject json = new JSONObject(ImmutableMap.of(
"jsonrpc", "2.0",
"method", "eth_blockNumber",
"params", ImmutableList.of(),
"id", rid
));
client.sendJsonRequest(networkName, json, new CompletionHandler<String, QueryError>() {
@Override
public void handleData(String data) {
// If we get a successful response, but the provided blocknumber is "0" then
// that indicates that the JSON-RPC node is syncing. Thus, if "0" transform
// to a .failure
if (!"0".equals(data) && !"0x".equals(data)) {
handler.handleData(data);
} else {
handler.handleError(new QueryNoDataError());
}
}
@Override
public void handleError(QueryError error) {
handler.handleError(error);
}
});
}
}
| 19
| 1
| 2
|
mixed
|
--- a/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
+++ b/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
@@ -10,2 +10,3 @@
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
+import com.breadwallet.crypto.blockchaindb.errors.QueryNoDataError;
import com.breadwallet.crypto.utility.CompletionHandler;
@@ -32,3 +33,20 @@
- client.sendJsonRequest(networkName, json, handler);
+ client.sendJsonRequest(networkName, json, new CompletionHandler<String, QueryError>() {
+ @Override
+ public void handleData(String data) {
+ // If we get a successful response, but the provided blocknumber is "0" then
+ // that indicates that the JSON-RPC node is syncing. Thus, if "0" transform
+ // to a .failure
+ if (!"0".equals(data) && !"0x".equals(data)) {
+ handler.handleData(data);
+ } else {
+ handler.handleError(new QueryNoDataError());
+ }
+ }
+
+ @Override
+ public void handleError(QueryError error) {
+ handler.handleError(error);
+ }
+ });
}
|
--- a/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
+++ b/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
@@ ... @@
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
+import com.breadwallet.crypto.blockchaindb.errors.QueryNoDataError;
import com.breadwallet.crypto.utility.CompletionHandler;
@@ ... @@
- client.sendJsonRequest(networkName, json, handler);
+ client.sendJsonRequest(networkName, json, new CompletionHandler<String, QueryError>() {
+ @Override
+ public void handleData(String data) {
+ // If we get a successful response, but the provided blocknumber is "0" then
+ // that indicates that the JSON-RPC node is syncing. Thus, if "0" transform
+ // to a .failure
+ if (!"0".equals(data) && !"0x".equals(data)) {
+ handler.handleData(data);
+ } else {
+ handler.handleError(new QueryNoDataError());
+ }
+ }
+
+ @Override
+ public void handleError(QueryError error) {
+ handler.handleError(error);
+ }
+ });
}
|
--- a/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
+++ b/Java/Crypto/src/main/java/com/breadwallet/crypto/blockchaindb/apis/brd/EthBlockApi.java
@@ -10,2 +10,3 @@
CON import com.breadwallet.crypto.blockchaindb.errors.QueryError;
ADD import com.breadwallet.crypto.blockchaindb.errors.QueryNoDataError;
CON import com.breadwallet.crypto.utility.CompletionHandler;
@@ -32,3 +33,20 @@
CON
DEL client.sendJsonRequest(networkName, json, handler);
ADD client.sendJsonRequest(networkName, json, new CompletionHandler<String, QueryError>() {
ADD @Override
ADD public void handleData(String data) {
ADD // If we get a successful response, but the provided blocknumber is "0" then
ADD // that indicates that the JSON-RPC node is syncing. Thus, if "0" transform
ADD // to a .failure
ADD if (!"0".equals(data) && !"0x".equals(data)) {
ADD handler.handleData(data);
ADD } else {
ADD handler.handleError(new QueryNoDataError());
ADD }
ADD }
ADD
ADD @Override
ADD public void handleError(QueryError error) {
ADD handler.handleError(error);
ADD }
ADD });
CON }
|
<<<<<<< SEARCH
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
import com.breadwallet.crypto.utility.CompletionHandler;
import com.google.common.collect.ImmutableList;
=======
import com.breadwallet.crypto.blockchaindb.errors.QueryError;
import com.breadwallet.crypto.blockchaindb.errors.QueryNoDataError;
import com.breadwallet.crypto.utility.CompletionHandler;
import com.google.common.collect.ImmutableList;
>>>>>>> REPLACE
<<<<<<< SEARCH
));
client.sendJsonRequest(networkName, json, handler);
}
}
=======
));
client.sendJsonRequest(networkName, json, new CompletionHandler<String, QueryError>() {
@Override
public void handleData(String data) {
// If we get a successful response, but the provided blocknumber is "0" then
// that indicates that the JSON-RPC node is syncing. Thus, if "0" transform
// to a .failure
if (!"0".equals(data) && !"0x".equals(data)) {
handler.handleData(data);
} else {
handler.handleError(new QueryNoDataError());
}
}
@Override
public void handleError(QueryError error) {
handler.handleError(error);
}
});
}
}
>>>>>>> REPLACE
|
MichaelRocks/lightsaber
|
cd9e42e42b438524fce7ef8ccebb1821ceadd25d
|
processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
|
kotlin
|
apache-2.0
|
Add a mergeTo() extension function for the Map interface
|
/*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.commons
import java.util.*
fun <K, V> Map<K, Collection<V>>.mergeWith(
map: Map<K, Collection<V>>,
collection: () -> MutableCollection<V> = { ArrayList() }
): Map<K, Collection<V>> {
val result = mapValuesTo(HashMap()) { entry ->
collection().apply { addAll(entry.value) }
}
for ((key, value) in map) {
result.getOrPut(key, collection).addAll(value)
}
return result
}
|
/*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.commons
import java.util.*
fun <K, V> Map<K, Collection<V>>.mergeWith(
map: Map<K, Collection<V>>,
collection: () -> MutableCollection<V> = { ArrayList() }
): Map<K, Collection<V>> {
val result = mapValuesTo(HashMap()) { entry ->
collection().apply { addAll(entry.value) }
}
map.mergeTo(result, collection)
return result
}
fun <K, V> Map<K, Collection<V>>.mergeTo(
destination: MutableMap<K, MutableCollection<V>>,
collection: () -> MutableCollection<V> = { ArrayList() }
): Map<K, Collection<V>> {
for ((key, value) in this) {
destination.getOrPut(key, collection).addAll(value)
}
return destination
}
| 11
| 3
| 1
|
mixed
|
--- a/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
+++ b/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
@@ -27,6 +27,14 @@
}
- for ((key, value) in map) {
- result.getOrPut(key, collection).addAll(value)
- }
+ map.mergeTo(result, collection)
return result
}
+
+fun <K, V> Map<K, Collection<V>>.mergeTo(
+ destination: MutableMap<K, MutableCollection<V>>,
+ collection: () -> MutableCollection<V> = { ArrayList() }
+): Map<K, Collection<V>> {
+ for ((key, value) in this) {
+ destination.getOrPut(key, collection).addAll(value)
+ }
+ return destination
+}
|
--- a/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
+++ b/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
@@ ... @@
}
- for ((key, value) in map) {
- result.getOrPut(key, collection).addAll(value)
- }
+ map.mergeTo(result, collection)
return result
}
+
+fun <K, V> Map<K, Collection<V>>.mergeTo(
+ destination: MutableMap<K, MutableCollection<V>>,
+ collection: () -> MutableCollection<V> = { ArrayList() }
+): Map<K, Collection<V>> {
+ for ((key, value) in this) {
+ destination.getOrPut(key, collection).addAll(value)
+ }
+ return destination
+}
|
--- a/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
+++ b/processor/src/main/kotlin/io/michaelrocks/lightsaber/processor/commons/MapExtensions.kt
@@ -27,6 +27,14 @@
CON }
DEL for ((key, value) in map) {
DEL result.getOrPut(key, collection).addAll(value)
DEL }
ADD map.mergeTo(result, collection)
CON return result
CON }
ADD
ADD fun <K, V> Map<K, Collection<V>>.mergeTo(
ADD destination: MutableMap<K, MutableCollection<V>>,
ADD collection: () -> MutableCollection<V> = { ArrayList() }
ADD ): Map<K, Collection<V>> {
ADD for ((key, value) in this) {
ADD destination.getOrPut(key, collection).addAll(value)
ADD }
ADD return destination
ADD }
|
<<<<<<< SEARCH
collection().apply { addAll(entry.value) }
}
for ((key, value) in map) {
result.getOrPut(key, collection).addAll(value)
}
return result
}
=======
collection().apply { addAll(entry.value) }
}
map.mergeTo(result, collection)
return result
}
fun <K, V> Map<K, Collection<V>>.mergeTo(
destination: MutableMap<K, MutableCollection<V>>,
collection: () -> MutableCollection<V> = { ArrayList() }
): Map<K, Collection<V>> {
for ((key, value) in this) {
destination.getOrPut(key, collection).addAll(value)
}
return destination
}
>>>>>>> REPLACE
|
toastkidjp/Jitte
|
f2f030270f3b6ee3b01f9dcb93585f9f2767714d
|
app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
|
kotlin
|
epl-1.0
|
Add Orma initialization in Application class.
|
package jp.toastkid.yobidashi
import android.app.Application
import com.squareup.leakcanary.LeakCanary
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
import jp.toastkid.yobidashi.notification.widget.NotificationWidget
import jp.toastkid.yobidashi.settings.color.SavedColors
import timber.log.Timber
/**
* For using LeakCanary and so on...
* @author toastkidjp
*/
class ExtendedApplication : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.install(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
val preferenceApplier = PreferenceApplier(this)
if (preferenceApplier.isFirstLaunch) {
SavedColors.insertDefaultColors(this)
preferenceApplier.updateLastAd()
BookmarkInitializer.invoke(this)
}
if (preferenceApplier.useNotificationWidget()) {
NotificationWidget.show(this)
}
}
}
|
package jp.toastkid.yobidashi
import android.app.Application
import com.squareup.leakcanary.LeakCanary
import io.reactivex.Completable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.libs.db.DbInitter
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
import jp.toastkid.yobidashi.notification.widget.NotificationWidget
import jp.toastkid.yobidashi.settings.color.SavedColors
import timber.log.Timber
/**
* For using LeakCanary and so on...
*
* @author toastkidjp
*/
class ExtendedApplication : Application() {
val disposables = CompositeDisposable()
override fun onCreate() {
super.onCreate()
disposables.add(
Completable.create { e ->
LeakCanary.install(this)
e.onComplete()
}.subscribeOn(Schedulers.computation())
.subscribe({}, {Timber.e(it)})
)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
val preferenceApplier = PreferenceApplier(this)
if (preferenceApplier.isFirstLaunch) {
SavedColors.insertDefaultColors(this)
preferenceApplier.updateLastAd()
BookmarkInitializer.invoke(this)
} else {
disposables.add(
Completable.create { e ->
DbInitter.init(this)
e.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe({}, {Timber.e(it)})
)
}
if (preferenceApplier.useNotificationWidget()) {
NotificationWidget.show(this)
}
}
override fun onTerminate() {
super.onTerminate()
disposables.dispose()
}
}
| 27
| 2
| 5
|
mixed
|
--- a/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
+++ b/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
@@ -4,3 +4,7 @@
import com.squareup.leakcanary.LeakCanary
+import io.reactivex.Completable
+import io.reactivex.disposables.CompositeDisposable
+import io.reactivex.schedulers.Schedulers
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
+import jp.toastkid.yobidashi.libs.db.DbInitter
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
@@ -12,3 +16,3 @@
* For using LeakCanary and so on...
-
+ *
* @author toastkidjp
@@ -17,5 +21,13 @@
+ val disposables = CompositeDisposable()
+
override fun onCreate() {
super.onCreate()
- LeakCanary.install(this)
+ disposables.add(
+ Completable.create { e ->
+ LeakCanary.install(this)
+ e.onComplete()
+ }.subscribeOn(Schedulers.computation())
+ .subscribe({}, {Timber.e(it)})
+ )
@@ -31,2 +43,10 @@
BookmarkInitializer.invoke(this)
+ } else {
+ disposables.add(
+ Completable.create { e ->
+ DbInitter.init(this)
+ e.onComplete()
+ }.subscribeOn(Schedulers.io())
+ .subscribe({}, {Timber.e(it)})
+ )
}
@@ -38,2 +58,7 @@
+ override fun onTerminate() {
+ super.onTerminate()
+ disposables.dispose()
+ }
+
}
|
--- a/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
+++ b/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
@@ ... @@
import com.squareup.leakcanary.LeakCanary
+import io.reactivex.Completable
+import io.reactivex.disposables.CompositeDisposable
+import io.reactivex.schedulers.Schedulers
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
+import jp.toastkid.yobidashi.libs.db.DbInitter
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
@@ ... @@
* For using LeakCanary and so on...
-
+ *
* @author toastkidjp
@@ ... @@
+ val disposables = CompositeDisposable()
+
override fun onCreate() {
super.onCreate()
- LeakCanary.install(this)
+ disposables.add(
+ Completable.create { e ->
+ LeakCanary.install(this)
+ e.onComplete()
+ }.subscribeOn(Schedulers.computation())
+ .subscribe({}, {Timber.e(it)})
+ )
@@ ... @@
BookmarkInitializer.invoke(this)
+ } else {
+ disposables.add(
+ Completable.create { e ->
+ DbInitter.init(this)
+ e.onComplete()
+ }.subscribeOn(Schedulers.io())
+ .subscribe({}, {Timber.e(it)})
+ )
}
@@ ... @@
+ override fun onTerminate() {
+ super.onTerminate()
+ disposables.dispose()
+ }
+
}
|
--- a/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
+++ b/app/src/main/java/jp/toastkid/yobidashi/ExtendedApplication.kt
@@ -4,3 +4,7 @@
CON import com.squareup.leakcanary.LeakCanary
ADD import io.reactivex.Completable
ADD import io.reactivex.disposables.CompositeDisposable
ADD import io.reactivex.schedulers.Schedulers
CON import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
ADD import jp.toastkid.yobidashi.libs.db.DbInitter
CON import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
@@ -12,3 +16,3 @@
CON * For using LeakCanary and so on...
DEL
ADD *
CON * @author toastkidjp
@@ -17,5 +21,13 @@
CON
ADD val disposables = CompositeDisposable()
ADD
CON override fun onCreate() {
CON super.onCreate()
DEL LeakCanary.install(this)
ADD disposables.add(
ADD Completable.create { e ->
ADD LeakCanary.install(this)
ADD e.onComplete()
ADD }.subscribeOn(Schedulers.computation())
ADD .subscribe({}, {Timber.e(it)})
ADD )
CON
@@ -31,2 +43,10 @@
CON BookmarkInitializer.invoke(this)
ADD } else {
ADD disposables.add(
ADD Completable.create { e ->
ADD DbInitter.init(this)
ADD e.onComplete()
ADD }.subscribeOn(Schedulers.io())
ADD .subscribe({}, {Timber.e(it)})
ADD )
CON }
@@ -38,2 +58,7 @@
CON
ADD override fun onTerminate() {
ADD super.onTerminate()
ADD disposables.dispose()
ADD }
ADD
CON }
|
<<<<<<< SEARCH
import android.app.Application
import com.squareup.leakcanary.LeakCanary
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
import jp.toastkid.yobidashi.notification.widget.NotificationWidget
=======
import android.app.Application
import com.squareup.leakcanary.LeakCanary
import io.reactivex.Completable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.libs.db.DbInitter
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier
import jp.toastkid.yobidashi.notification.widget.NotificationWidget
>>>>>>> REPLACE
<<<<<<< SEARCH
/**
* For using LeakCanary and so on...
* @author toastkidjp
*/
class ExtendedApplication : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.install(this)
if (BuildConfig.DEBUG) {
=======
/**
* For using LeakCanary and so on...
*
* @author toastkidjp
*/
class ExtendedApplication : Application() {
val disposables = CompositeDisposable()
override fun onCreate() {
super.onCreate()
disposables.add(
Completable.create { e ->
LeakCanary.install(this)
e.onComplete()
}.subscribeOn(Schedulers.computation())
.subscribe({}, {Timber.e(it)})
)
if (BuildConfig.DEBUG) {
>>>>>>> REPLACE
<<<<<<< SEARCH
preferenceApplier.updateLastAd()
BookmarkInitializer.invoke(this)
}
=======
preferenceApplier.updateLastAd()
BookmarkInitializer.invoke(this)
} else {
disposables.add(
Completable.create { e ->
DbInitter.init(this)
e.onComplete()
}.subscribeOn(Schedulers.io())
.subscribe({}, {Timber.e(it)})
)
}
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
=======
}
override fun onTerminate() {
super.onTerminate()
disposables.dispose()
}
}
>>>>>>> REPLACE
|
virtool/virtool
|
3cc473fb6316fffa3c19980115f800518dcee115
|
setup.py
|
python
|
mit
|
Fix missing raven.processors in build
|
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format"
],
"namespace_packages": [
"virtool"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options)
|
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format"
"raven.processors"
"namespace_packages": [
"virtool"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options)
| 1
| 1
| 1
|
mixed
|
--- a/setup.py
+++ b/setup.py
@@ -23,3 +23,3 @@
"numpy.lib.format"
- ],
+ "raven.processors"
"namespace_packages": [
|
--- a/setup.py
+++ b/setup.py
@@ ... @@
"numpy.lib.format"
- ],
+ "raven.processors"
"namespace_packages": [
|
--- a/setup.py
+++ b/setup.py
@@ -23,3 +23,3 @@
CON "numpy.lib.format"
DEL ],
ADD "raven.processors"
CON "namespace_packages": [
|
<<<<<<< SEARCH
"numpy.lib",
"numpy.lib.format"
],
"namespace_packages": [
"virtool"
=======
"numpy.lib",
"numpy.lib.format"
"raven.processors"
"namespace_packages": [
"virtool"
>>>>>>> REPLACE
|
ruud-v-a/hound
|
ff6709a7ad156826964d65e87e31e43c4b192a22
|
fuzz/fuzzers/decode_full.rs
|
rust
|
apache-2.0
|
Work around memory error in fuzzer
|
// Hound -- A wav encoding and decoding library in Rust
// Copyright (C) 2017 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
#![no_main]
extern crate libfuzzer_sys;
extern crate hound;
use std::io::Cursor;
#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
let cursor = Cursor::new(data);
let mut reader = match hound::WavReader::new(cursor) {
Ok(r) => r,
Err(..) => return,
};
for sample in reader.samples::<i32>() {
match sample {
Ok(..) => { }
Err(..) => return,
}
}
}
|
// Hound -- A wav encoding and decoding library in Rust
// Copyright (C) 2017 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
#![no_main]
extern crate libfuzzer_sys;
extern crate hound;
use std::io::Cursor;
#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
let cursor = Cursor::new(data);
let mut reader = match hound::WavReader::new(cursor) {
Ok(r) => r,
Err(..) => return,
};
// TODO: For some reason, the iterator-based approach crashes with an
// obscure memory error, but the while-let-based method works perfectly
// fine.
// for sample in reader.samples::<i32>() {
// match sample {
// Ok(..) => { }
// Err(..) => return,
// }
// }
let mut iter = reader.samples::<i32>();
while let Some(sample) = iter.next() {
match sample {
Ok(..) => { }
Err(..) => return,
}
}
}
| 12
| 1
| 1
|
mixed
|
--- a/fuzz/fuzzers/decode_full.rs
+++ b/fuzz/fuzzers/decode_full.rs
@@ -22,3 +22,14 @@
- for sample in reader.samples::<i32>() {
+ // TODO: For some reason, the iterator-based approach crashes with an
+ // obscure memory error, but the while-let-based method works perfectly
+ // fine.
+ // for sample in reader.samples::<i32>() {
+ // match sample {
+ // Ok(..) => { }
+ // Err(..) => return,
+ // }
+ // }
+
+ let mut iter = reader.samples::<i32>();
+ while let Some(sample) = iter.next() {
match sample {
|
--- a/fuzz/fuzzers/decode_full.rs
+++ b/fuzz/fuzzers/decode_full.rs
@@ ... @@
- for sample in reader.samples::<i32>() {
+ // TODO: For some reason, the iterator-based approach crashes with an
+ // obscure memory error, but the while-let-based method works perfectly
+ // fine.
+ // for sample in reader.samples::<i32>() {
+ // match sample {
+ // Ok(..) => { }
+ // Err(..) => return,
+ // }
+ // }
+
+ let mut iter = reader.samples::<i32>();
+ while let Some(sample) = iter.next() {
match sample {
|
--- a/fuzz/fuzzers/decode_full.rs
+++ b/fuzz/fuzzers/decode_full.rs
@@ -22,3 +22,14 @@
CON
DEL for sample in reader.samples::<i32>() {
ADD // TODO: For some reason, the iterator-based approach crashes with an
ADD // obscure memory error, but the while-let-based method works perfectly
ADD // fine.
ADD // for sample in reader.samples::<i32>() {
ADD // match sample {
ADD // Ok(..) => { }
ADD // Err(..) => return,
ADD // }
ADD // }
ADD
ADD let mut iter = reader.samples::<i32>();
ADD while let Some(sample) = iter.next() {
CON match sample {
|
<<<<<<< SEARCH
};
for sample in reader.samples::<i32>() {
match sample {
Ok(..) => { }
=======
};
// TODO: For some reason, the iterator-based approach crashes with an
// obscure memory error, but the while-let-based method works perfectly
// fine.
// for sample in reader.samples::<i32>() {
// match sample {
// Ok(..) => { }
// Err(..) => return,
// }
// }
let mut iter = reader.samples::<i32>();
while let Some(sample) = iter.next() {
match sample {
Ok(..) => { }
>>>>>>> REPLACE
|
Slikey/EffectLib
|
63d8f8f18a89d096957effe5b038d95575aed0a5
|
src/main/java/de/slikey/effectlib/effect/BleedEffect.java
|
java
|
mit
|
Change Bleed effect to use a material rather than a mysterious color id
|
package de.slikey.effectlib.effect;
import de.slikey.effectlib.EffectManager;
import de.slikey.effectlib.EffectType;
import de.slikey.effectlib.util.RandomUtils;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
public class BleedEffect extends de.slikey.effectlib.Effect {
/**
* Play the Hurt Effect for the Player
*/
public boolean hurt = true;
/**
* Height of the blood spurt
*/
public double height = 1.75;
/**
* Color of blood. Default is red (152)
*/
public int color = 152;
public BleedEffect(EffectManager effectManager) {
super(effectManager);
type = EffectType.REPEATING;
period = 4;
iterations = 25;
}
@Override
public void onRun() {
// Location to spawn the blood-item.
Location location = getLocation();
location.add(0, RandomUtils.random.nextFloat() * height, 0);
location.getWorld().playEffect(location, Effect.STEP_SOUND, color);
Entity entity = getEntity();
if (hurt && entity != null) {
entity.playEffect(org.bukkit.EntityEffect.HURT);
}
}
}
|
package de.slikey.effectlib.effect;
import de.slikey.effectlib.EffectManager;
import de.slikey.effectlib.EffectType;
import de.slikey.effectlib.util.RandomUtils;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
public class BleedEffect extends de.slikey.effectlib.Effect {
/**
* Play the Hurt Effect for the Player
*/
public boolean hurt = true;
/**
* Height of the blood spurt
*/
public double height = 1.75;
/**
* Color of blood. Default is red (152)
*/
public Material material = Material.REDSTONE_BLOCK;
public BleedEffect(EffectManager effectManager) {
super(effectManager);
type = EffectType.REPEATING;
period = 4;
iterations = 25;
}
@Override
public void onRun() {
// Location to spawn the blood-item.
Location location = getLocation();
location.add(0, RandomUtils.random.nextFloat() * height, 0);
location.getWorld().playEffect(location, Effect.STEP_SOUND, material);
Entity entity = getEntity();
if (hurt && entity != null) {
entity.playEffect(org.bukkit.EntityEffect.HURT);
}
}
}
| 3
| 2
| 3
|
mixed
|
--- a/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
+++ b/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
@@ -7,2 +7,3 @@
import org.bukkit.Location;
+import org.bukkit.Material;
import org.bukkit.entity.Entity;
@@ -24,3 +25,3 @@
*/
- public int color = 152;
+ public Material material = Material.REDSTONE_BLOCK;
@@ -38,3 +39,3 @@
location.add(0, RandomUtils.random.nextFloat() * height, 0);
- location.getWorld().playEffect(location, Effect.STEP_SOUND, color);
+ location.getWorld().playEffect(location, Effect.STEP_SOUND, material);
|
--- a/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
+++ b/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
@@ ... @@
import org.bukkit.Location;
+import org.bukkit.Material;
import org.bukkit.entity.Entity;
@@ ... @@
*/
- public int color = 152;
+ public Material material = Material.REDSTONE_BLOCK;
@@ ... @@
location.add(0, RandomUtils.random.nextFloat() * height, 0);
- location.getWorld().playEffect(location, Effect.STEP_SOUND, color);
+ location.getWorld().playEffect(location, Effect.STEP_SOUND, material);
|
--- a/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
+++ b/src/main/java/de/slikey/effectlib/effect/BleedEffect.java
@@ -7,2 +7,3 @@
CON import org.bukkit.Location;
ADD import org.bukkit.Material;
CON import org.bukkit.entity.Entity;
@@ -24,3 +25,3 @@
CON */
DEL public int color = 152;
ADD public Material material = Material.REDSTONE_BLOCK;
CON
@@ -38,3 +39,3 @@
CON location.add(0, RandomUtils.random.nextFloat() * height, 0);
DEL location.getWorld().playEffect(location, Effect.STEP_SOUND, color);
ADD location.getWorld().playEffect(location, Effect.STEP_SOUND, material);
CON
|
<<<<<<< SEARCH
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
=======
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
>>>>>>> REPLACE
<<<<<<< SEARCH
* Color of blood. Default is red (152)
*/
public int color = 152;
public BleedEffect(EffectManager effectManager) {
=======
* Color of blood. Default is red (152)
*/
public Material material = Material.REDSTONE_BLOCK;
public BleedEffect(EffectManager effectManager) {
>>>>>>> REPLACE
<<<<<<< SEARCH
Location location = getLocation();
location.add(0, RandomUtils.random.nextFloat() * height, 0);
location.getWorld().playEffect(location, Effect.STEP_SOUND, color);
Entity entity = getEntity();
=======
Location location = getLocation();
location.add(0, RandomUtils.random.nextFloat() * height, 0);
location.getWorld().playEffect(location, Effect.STEP_SOUND, material);
Entity entity = getEntity();
>>>>>>> REPLACE
|
roguexz/rogue.io
|
55304d5f3ab8d219b8faf373188bd984a1f1db3d
|
modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
|
java
|
apache-2.0
|
Use AbstractMap.SimpleEntry since HashMap.Entry is not serializable.
|
package rogue.app.framework.view.faces.bean;
import rogue.app.framework.view.faces.CommandInvocation;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Command invocation that can be associated with a login action.
*/
@SessionScoped
public class LoginAction extends CommandInvocation<String>
{
@Inject
private Instance<AuthenticationManager> authenticationManager;
private List<Map.Entry<String, String>> loginLinks;
public LoginAction()
{
}
/**
* Get a list of configured authentication providers.
*
* @return a list of configured authentication providers.
*/
public Set<String> getProviders()
{
return authenticationManager.get().getProviders();
}
/**
* Get the entry set of login links.
*
* @return the map of login links.
*/
public List<Map.Entry<String, String>> getLoginLinks()
{
// Because ui:repeat does not support the collection interface.
if (loginLinks == null)
{
loginLinks = new ArrayList<>();
loginLinks.addAll(authenticationManager.get().getLoginLinks().entrySet());
}
return loginLinks;
}
}
|
package rogue.app.framework.view.faces.bean;
import rogue.app.framework.view.faces.CommandInvocation;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.*;
/**
* Command invocation that can be associated with a login action.
*/
@SessionScoped
public class LoginAction extends CommandInvocation<String>
{
@Inject
private Instance<AuthenticationManager> authenticationManager;
private List<Map.Entry<String, String>> loginLinks;
public LoginAction()
{
}
/**
* Get a list of configured authentication providers.
*
* @return a list of configured authentication providers.
*/
public Set<String> getProviders()
{
return authenticationManager.get().getProviders();
}
/**
* Get the entry set of login links.
*
* @return the map of login links.
*/
public List<Map.Entry<String, String>> getLoginLinks()
{
// Because ui:repeat does not support the collection interface.
if (loginLinks == null)
{
loginLinks = new ArrayList<>();
for (Map.Entry<String, String> entry : authenticationManager.get().getLoginLinks().entrySet())
{
loginLinks.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
}
}
return loginLinks;
}
}
| 5
| 5
| 2
|
mixed
|
--- a/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
+++ b/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
@@ -7,6 +7,3 @@
import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
@@ -48,3 +45,6 @@
loginLinks = new ArrayList<>();
- loginLinks.addAll(authenticationManager.get().getLoginLinks().entrySet());
+ for (Map.Entry<String, String> entry : authenticationManager.get().getLoginLinks().entrySet())
+ {
+ loginLinks.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
+ }
}
|
--- a/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
+++ b/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
@@ ... @@
import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
@@ ... @@
loginLinks = new ArrayList<>();
- loginLinks.addAll(authenticationManager.get().getLoginLinks().entrySet());
+ for (Map.Entry<String, String> entry : authenticationManager.get().getLoginLinks().entrySet())
+ {
+ loginLinks.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
+ }
}
|
--- a/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
+++ b/modules/framework-view/src/main/java/rogue/app/framework/view/faces/bean/LoginAction.java
@@ -7,6 +7,3 @@
CON import javax.inject.Inject;
DEL import java.util.ArrayList;
DEL import java.util.List;
DEL import java.util.Map;
DEL import java.util.Set;
ADD import java.util.*;
CON
@@ -48,3 +45,6 @@
CON loginLinks = new ArrayList<>();
DEL loginLinks.addAll(authenticationManager.get().getLoginLinks().entrySet());
ADD for (Map.Entry<String, String> entry : authenticationManager.get().getLoginLinks().entrySet())
ADD {
ADD loginLinks.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
ADD }
CON }
|
<<<<<<< SEARCH
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
=======
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.util.*;
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
{
loginLinks = new ArrayList<>();
loginLinks.addAll(authenticationManager.get().getLoginLinks().entrySet());
}
return loginLinks;
=======
{
loginLinks = new ArrayList<>();
for (Map.Entry<String, String> entry : authenticationManager.get().getLoginLinks().entrySet())
{
loginLinks.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
}
}
return loginLinks;
>>>>>>> REPLACE
|
emag/wildfly-swarm-examples
|
d397eba295a95828a5c36bf0e716f1aa32b6e3db
|
transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
|
java
|
apache-2.0
|
Remove subsystem() usage in favor of fraction()
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.wildfly.swarm.examples.transactions;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.transactions.TransactionsFraction;
/**
* @author nmcl
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
/*
* Use specific TransactionFraction even though it doesn't do
* any more than the default one - for now.
*/
container.subsystem(new TransactionsFraction(4712, 4713));
// Start the container
container.start();
/*
* Now register JAX-RS resource class.
*/
JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
appDeployment.addResource(MyResource.class);
container.deploy(appDeployment);
}
}
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.wildfly.swarm.examples.transactions;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.transactions.TransactionsFraction;
/**
* @author nmcl
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
/*
* Use specific TransactionFraction even though it doesn't do
* any more than the default one - for now.
*/
container.fraction(new TransactionsFraction(4712, 4713));
// Start the container
container.start();
/*
* Now register JAX-RS resource class.
*/
JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
appDeployment.addResource(MyResource.class);
container.deploy(appDeployment);
}
}
| 1
| 1
| 1
|
mixed
|
--- a/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
+++ b/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
@@ -25,3 +25,3 @@
- container.subsystem(new TransactionsFraction(4712, 4713));
+ container.fraction(new TransactionsFraction(4712, 4713));
|
--- a/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
+++ b/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
@@ ... @@
- container.subsystem(new TransactionsFraction(4712, 4713));
+ container.fraction(new TransactionsFraction(4712, 4713));
|
--- a/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
+++ b/transactions/src/main/java/org/wildfly/swarm/examples/transactions/Main.java
@@ -25,3 +25,3 @@
CON
DEL container.subsystem(new TransactionsFraction(4712, 4713));
ADD container.fraction(new TransactionsFraction(4712, 4713));
CON
|
<<<<<<< SEARCH
*/
container.subsystem(new TransactionsFraction(4712, 4713));
// Start the container
=======
*/
container.fraction(new TransactionsFraction(4712, 4713));
// Start the container
>>>>>>> REPLACE
|
CS2103JAN2017-T16-B2/main
|
3061d376e680f7a0e24b68ac05b23712e11605f1
|
src/main/java/seedu/address/logic/commands/UndoCommand.java
|
java
|
mit
|
Add header comment for class and change isMutating to true
|
package seedu.address.logic.commands;
import javafx.collections.ObservableList;
import seedu.address.commons.exceptions.InvalidUndoCommandException;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.undo.UndoManager;
import seedu.address.model.datastructure.UndoPair;
import seedu.address.model.label.Label;
import seedu.address.model.task.ReadOnlyTask;
//@@author A0162877N
public class UndoCommand extends Command {
public static final String COMMAND_WORD = "undo";
public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n"
+ "To Redo past command, hit the up arrow key.";
public static final String MESSAGE_USAGE = COMMAND_WORD;
public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo.";
@Override
public CommandResult execute() throws CommandException {
assert model != null;
try {
if (!UndoManager.getInstance().isEmpty()) {
UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair =
UndoManager.getInstance().getUndoData();
model.undoPrevious(pair.getLeft(), pair.getRight());
return new CommandResult(String.format(MESSAGE_SUCCESS));
} else {
throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO);
}
} catch (InvalidUndoCommandException e) {
throw new CommandException(e.getMessage());
}
}
@Override
public boolean isMutating() {
return false;
}
}
|
package seedu.address.logic.commands;
import javafx.collections.ObservableList;
import seedu.address.commons.exceptions.InvalidUndoCommandException;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.undo.UndoManager;
import seedu.address.model.datastructure.UndoPair;
import seedu.address.model.label.Label;
import seedu.address.model.task.ReadOnlyTask;
//@@author A0162877N
/**
* Undo the most recent mutating command from the task manager,
* returning the data to the previous state
*/
public class UndoCommand extends Command {
public static final String COMMAND_WORD = "undo";
public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n"
+ "To Redo past command, hit the up arrow key.";
public static final String MESSAGE_USAGE = COMMAND_WORD;
public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo.";
@Override
public CommandResult execute() throws CommandException {
assert model != null;
try {
if (!UndoManager.getInstance().isEmpty()) {
UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair =
UndoManager.getInstance().getUndoData();
model.undoPrevious(pair.getLeft(), pair.getRight());
return new CommandResult(String.format(MESSAGE_SUCCESS));
} else {
throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO);
}
} catch (InvalidUndoCommandException e) {
throw new CommandException(e.getMessage());
}
}
@Override
public boolean isMutating() {
return true;
}
}
| 5
| 1
| 2
|
mixed
|
--- a/src/main/java/seedu/address/logic/commands/UndoCommand.java
+++ b/src/main/java/seedu/address/logic/commands/UndoCommand.java
@@ -11,2 +11,6 @@
//@@author A0162877N
+/**
+ * Undo the most recent mutating command from the task manager,
+ * returning the data to the previous state
+ */
public class UndoCommand extends Command {
@@ -38,3 +42,3 @@
public boolean isMutating() {
- return false;
+ return true;
}
|
--- a/src/main/java/seedu/address/logic/commands/UndoCommand.java
+++ b/src/main/java/seedu/address/logic/commands/UndoCommand.java
@@ ... @@
//@@author A0162877N
+/**
+ * Undo the most recent mutating command from the task manager,
+ * returning the data to the previous state
+ */
public class UndoCommand extends Command {
@@ ... @@
public boolean isMutating() {
- return false;
+ return true;
}
|
--- a/src/main/java/seedu/address/logic/commands/UndoCommand.java
+++ b/src/main/java/seedu/address/logic/commands/UndoCommand.java
@@ -11,2 +11,6 @@
CON //@@author A0162877N
ADD /**
ADD * Undo the most recent mutating command from the task manager,
ADD * returning the data to the previous state
ADD */
CON public class UndoCommand extends Command {
@@ -38,3 +42,3 @@
CON public boolean isMutating() {
DEL return false;
ADD return true;
CON }
|
<<<<<<< SEARCH
//@@author A0162877N
public class UndoCommand extends Command {
=======
//@@author A0162877N
/**
* Undo the most recent mutating command from the task manager,
* returning the data to the previous state
*/
public class UndoCommand extends Command {
>>>>>>> REPLACE
<<<<<<< SEARCH
@Override
public boolean isMutating() {
return false;
}
=======
@Override
public boolean isMutating() {
return true;
}
>>>>>>> REPLACE
|
KILFaT/BudgetKeeper
|
ebf8f3427a82f70a984a0035163a3a3e60e625f8
|
src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
|
java
|
apache-2.0
|
Change data parser, need to add unix timestamp support
|
package com.kilfat.web.model.deserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kilfat.config.ServiceConstants;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DeserializerHelper {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(ServiceConstants.DATE_FORMAT);
public static JsonNode getFieldNode(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field);
}
return null;
}
public static String getField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).textValue();
}
return "";
}
public static Integer getIntegerField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).intValue();
}
return null;
}
public static Long getLongField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).longValue();
}
return null;
}
public static Date getDateField(JsonNode node, String field) {
String dateAsString;
if (node.get(field) == null) {
return null;
}
dateAsString = node.get(field).textValue();
try {
return dateFormat.parse(dateAsString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
|
package com.kilfat.web.model.deserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kilfat.config.ServiceConstants;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DeserializerHelper {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(ServiceConstants.DATE_FORMAT);
public static JsonNode getFieldNode(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field);
}
return null;
}
public static String getField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).textValue();
}
return "";
}
public static Integer getIntegerField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).intValue();
}
return null;
}
public static Long getLongField(JsonNode node, String field) {
if (node.get(field) != null) {
return node.get(field).longValue();
}
return null;
}
public static Date getDateField(JsonNode node, String field) {
long date;
if (node.get(field) == null || node.get(field).isLong() == false) {
return null;
}
date = node.get(field).asLong();
try {
return dateFormat.parse(date*1000L);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
| 4
| 4
| 1
|
mixed
|
--- a/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
+++ b/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
@@ -41,9 +41,9 @@
public static Date getDateField(JsonNode node, String field) {
- String dateAsString;
- if (node.get(field) == null) {
+ long date;
+ if (node.get(field) == null || node.get(field).isLong() == false) {
return null;
}
- dateAsString = node.get(field).textValue();
+ date = node.get(field).asLong();
try {
- return dateFormat.parse(dateAsString);
+ return dateFormat.parse(date*1000L);
} catch (ParseException e) {
|
--- a/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
+++ b/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
@@ ... @@
public static Date getDateField(JsonNode node, String field) {
- String dateAsString;
- if (node.get(field) == null) {
+ long date;
+ if (node.get(field) == null || node.get(field).isLong() == false) {
return null;
}
- dateAsString = node.get(field).textValue();
+ date = node.get(field).asLong();
try {
- return dateFormat.parse(dateAsString);
+ return dateFormat.parse(date*1000L);
} catch (ParseException e) {
|
--- a/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
+++ b/src/main/java/com/kilfat/web/model/deserializer/DeserializerHelper.java
@@ -41,9 +41,9 @@
CON public static Date getDateField(JsonNode node, String field) {
DEL String dateAsString;
DEL if (node.get(field) == null) {
ADD long date;
ADD if (node.get(field) == null || node.get(field).isLong() == false) {
CON return null;
CON }
DEL dateAsString = node.get(field).textValue();
ADD date = node.get(field).asLong();
CON try {
DEL return dateFormat.parse(dateAsString);
ADD return dateFormat.parse(date*1000L);
CON } catch (ParseException e) {
|
<<<<<<< SEARCH
public static Date getDateField(JsonNode node, String field) {
String dateAsString;
if (node.get(field) == null) {
return null;
}
dateAsString = node.get(field).textValue();
try {
return dateFormat.parse(dateAsString);
} catch (ParseException e) {
throw new RuntimeException(e);
=======
public static Date getDateField(JsonNode node, String field) {
long date;
if (node.get(field) == null || node.get(field).isLong() == false) {
return null;
}
date = node.get(field).asLong();
try {
return dateFormat.parse(date*1000L);
} catch (ParseException e) {
throw new RuntimeException(e);
>>>>>>> REPLACE
|
blindpirate/gradle
|
fae15bc929dc60d57c168a1904c9088f66b4549d
|
subprojects/dependency-management/dependency-management.gradle.kts
|
kotlin
|
apache-2.0
|
Change module type of dependency-management project to CORE
|
import org.gradle.build.ClasspathManifest
import org.gradle.gradlebuild.testing.integrationtests.cleanup.EmptyDirectoryCheck
import org.gradle.gradlebuild.unittestandcompile.ModuleType
plugins {
`java-library`
}
dependencies {
api(project(":core"))
api(project(":versionControl"))
implementation(project(":resources"))
implementation(project(":resourcesHttp"))
implementation(library("asm"))
implementation(library("asm_commons"))
implementation(library("asm_util"))
implementation(library("commons_lang"))
implementation(library("commons_io"))
implementation(library("ivy"))
implementation(library("slf4j_api"))
implementation(library("gson"))
implementation(library("jcip"))
implementation(library("maven3"))
runtimeOnly(library("bouncycastle_provider"))
runtimeOnly(project(":installationBeacon"))
testImplementation(library("nekohtml"))
integTestRuntimeOnly(project(":ivy"))
integTestRuntimeOnly(project(":maven"))
integTestRuntimeOnly(project(":resourcesS3"))
integTestRuntimeOnly(project(":resourcesSftp"))
integTestRuntimeOnly(project(":testKit"))
testFixturesImplementation(project(":internalIntegTesting"))
}
gradlebuildJava {
// TODO Source Compatibility was set to 1.6. Why? Is this worker code?
moduleType = ModuleType.WORKER
}
testFixtures {
from(":core")
from(":messaging")
from(":modelCore")
from(":versionControl")
}
testFilesCleanup {
isErrorWhenNotEmpty = false
}
val classpathManifest by tasks.getting(ClasspathManifest::class) {
additionalProjects = listOf(project(":runtimeApiInfo"))
}
|
import org.gradle.build.ClasspathManifest
import org.gradle.gradlebuild.testing.integrationtests.cleanup.EmptyDirectoryCheck
import org.gradle.gradlebuild.unittestandcompile.ModuleType
plugins {
`java-library`
}
dependencies {
api(project(":core"))
api(project(":versionControl"))
implementation(project(":resources"))
implementation(project(":resourcesHttp"))
implementation(library("asm"))
implementation(library("asm_commons"))
implementation(library("asm_util"))
implementation(library("commons_lang"))
implementation(library("commons_io"))
implementation(library("ivy"))
implementation(library("slf4j_api"))
implementation(library("gson"))
implementation(library("jcip"))
implementation(library("maven3"))
runtimeOnly(library("bouncycastle_provider"))
runtimeOnly(project(":installationBeacon"))
testImplementation(library("nekohtml"))
integTestRuntimeOnly(project(":ivy"))
integTestRuntimeOnly(project(":maven"))
integTestRuntimeOnly(project(":resourcesS3"))
integTestRuntimeOnly(project(":resourcesSftp"))
integTestRuntimeOnly(project(":testKit"))
testFixturesImplementation(project(":internalIntegTesting"))
}
gradlebuildJava {
moduleType = ModuleType.CORE
}
testFixtures {
from(":core")
from(":messaging")
from(":modelCore")
from(":versionControl")
}
testFilesCleanup {
isErrorWhenNotEmpty = false
}
val classpathManifest by tasks.getting(ClasspathManifest::class) {
additionalProjects = listOf(project(":runtimeApiInfo"))
}
| 1
| 2
| 1
|
mixed
|
--- a/subprojects/dependency-management/dependency-management.gradle.kts
+++ b/subprojects/dependency-management/dependency-management.gradle.kts
@@ -41,4 +41,3 @@
gradlebuildJava {
- // TODO Source Compatibility was set to 1.6. Why? Is this worker code?
- moduleType = ModuleType.WORKER
+ moduleType = ModuleType.CORE
}
|
--- a/subprojects/dependency-management/dependency-management.gradle.kts
+++ b/subprojects/dependency-management/dependency-management.gradle.kts
@@ ... @@
gradlebuildJava {
- // TODO Source Compatibility was set to 1.6. Why? Is this worker code?
- moduleType = ModuleType.WORKER
+ moduleType = ModuleType.CORE
}
|
--- a/subprojects/dependency-management/dependency-management.gradle.kts
+++ b/subprojects/dependency-management/dependency-management.gradle.kts
@@ -41,4 +41,3 @@
CON gradlebuildJava {
DEL // TODO Source Compatibility was set to 1.6. Why? Is this worker code?
DEL moduleType = ModuleType.WORKER
ADD moduleType = ModuleType.CORE
CON }
|
<<<<<<< SEARCH
gradlebuildJava {
// TODO Source Compatibility was set to 1.6. Why? Is this worker code?
moduleType = ModuleType.WORKER
}
=======
gradlebuildJava {
moduleType = ModuleType.CORE
}
>>>>>>> REPLACE
|
mitsuhiko/flask-babel
|
1fdb94783831bdd8e0608dc95a008f9344753a58
|
setup.py
|
python
|
bsd-3-clause
|
Switch to using README.md for project description on pypi.
|
"""
Flask-Babel
-----------
Adds i18n/l10n support to Flask applications with the help of the
`Babel`_ library.
Links
`````
* `documentation <http://packages.python.org/Flask-Babel>`_
* `development version
<http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_
.. _Babel: http://babel.edgewall.org/
"""
from setuptools import setup
setup(
name='Flask-Babel',
version='0.12.0',
url='http://github.com/python-babel/flask-babel',
license='BSD',
author='Armin Ronacher',
author_email='armin.ronacher@active-4.com',
description='Adds i18n/l10n support to Flask applications',
long_description=__doc__,
packages=['flask_babel'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'Babel>=2.3',
'Jinja2>=2.5'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='Flask-Babel',
version='0.12.0',
url='http://github.com/python-babel/flask-babel',
license='BSD',
author='Armin Ronacher',
author_email='armin.ronacher@active-4.com',
description='Adds i18n/l10n support to Flask applications',
long_description=long_description,
long_description_content_type='text/markdown',
packages=['flask_babel'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'Babel>=2.3',
'Jinja2>=2.5'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| 7
| 17
| 2
|
mixed
|
--- a/setup.py
+++ b/setup.py
@@ -1,19 +1,7 @@
-"""
-Flask-Babel
------------
+from setuptools import setup
-Adds i18n/l10n support to Flask applications with the help of the
-`Babel`_ library.
-
-Links
-`````
-
-* `documentation <http://packages.python.org/Flask-Babel>`_
-* `development version
- <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_
-
-.. _Babel: http://babel.edgewall.org/
-
-"""
-from setuptools import setup
+from os import path
+this_directory = path.abspath(path.dirname(__file__))
+with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
+ long_description = f.read()
@@ -28,3 +16,4 @@
description='Adds i18n/l10n support to Flask applications',
- long_description=__doc__,
+ long_description=long_description,
+ long_description_content_type='text/markdown',
packages=['flask_babel'],
|
--- a/setup.py
+++ b/setup.py
@@ ... @@
-"""
-Flask-Babel
------------
+from setuptools import setup
-Adds i18n/l10n support to Flask applications with the help of the
-`Babel`_ library.
-
-Links
-`````
-
-* `documentation <http://packages.python.org/Flask-Babel>`_
-* `development version
- <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_
-
-.. _Babel: http://babel.edgewall.org/
-
-"""
-from setuptools import setup
+from os import path
+this_directory = path.abspath(path.dirname(__file__))
+with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
+ long_description = f.read()
@@ ... @@
description='Adds i18n/l10n support to Flask applications',
- long_description=__doc__,
+ long_description=long_description,
+ long_description_content_type='text/markdown',
packages=['flask_babel'],
|
--- a/setup.py
+++ b/setup.py
@@ -1,19 +1,7 @@
DEL """
DEL Flask-Babel
DEL -----------
ADD from setuptools import setup
CON
DEL Adds i18n/l10n support to Flask applications with the help of the
DEL `Babel`_ library.
DEL
DEL Links
DEL `````
DEL
DEL * `documentation <http://packages.python.org/Flask-Babel>`_
DEL * `development version
DEL <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_
DEL
DEL .. _Babel: http://babel.edgewall.org/
DEL
DEL """
DEL from setuptools import setup
ADD from os import path
ADD this_directory = path.abspath(path.dirname(__file__))
ADD with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
ADD long_description = f.read()
CON
@@ -28,3 +16,4 @@
CON description='Adds i18n/l10n support to Flask applications',
DEL long_description=__doc__,
ADD long_description=long_description,
ADD long_description_content_type='text/markdown',
CON packages=['flask_babel'],
|
<<<<<<< SEARCH
"""
Flask-Babel
-----------
Adds i18n/l10n support to Flask applications with the help of the
`Babel`_ library.
Links
`````
* `documentation <http://packages.python.org/Flask-Babel>`_
* `development version
<http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_
.. _Babel: http://babel.edgewall.org/
"""
from setuptools import setup
=======
from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
>>>>>>> REPLACE
<<<<<<< SEARCH
author_email='armin.ronacher@active-4.com',
description='Adds i18n/l10n support to Flask applications',
long_description=__doc__,
packages=['flask_babel'],
zip_safe=False,
=======
author_email='armin.ronacher@active-4.com',
description='Adds i18n/l10n support to Flask applications',
long_description=long_description,
long_description_content_type='text/markdown',
packages=['flask_babel'],
zip_safe=False,
>>>>>>> REPLACE
|
pyamsoft/pydroid
|
75aa44651f88563853af4ea5b95d1ea20ee8e168
|
arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
|
kotlin
|
apache-2.0
|
Use a singleton for empty controllers
An empty UI controller has no controller events
|
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.arch
import androidx.annotation.CheckResult
/**
* The UiController drives the events. It orchestrates events between the UiView and UiViewModel
*/
public interface UiController<C : UiControllerEvent> {
/**
* Respond to a published UiControllerEvent
*/
public fun onControllerEvent(event: C)
}
/**
* Create a new anonymous UiController
*
* For when a single Android component serves as multiple UiControllers
*/
@CheckResult
public inline fun <C : UiControllerEvent> newUiController(crossinline onEvent: (C) -> Unit): UiController<C> {
return object : UiController<C> {
override fun onControllerEvent(event: C) {
return onEvent(event)
}
}
}
|
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.arch
import androidx.annotation.CheckResult
/**
* The UiController drives the events. It orchestrates events between the UiView and UiViewModel
*/
public interface UiController<C : UiControllerEvent> {
/**
* Respond to a published UiControllerEvent
*/
public fun onControllerEvent(event: C)
}
/**
* Create a new anonymous UiController
*
* For when a single Android component serves as multiple UiControllers
*/
@CheckResult
public inline fun <C : UiControllerEvent> newUiController(crossinline onEvent: (C) -> Unit): UiController<C> {
return object : UiController<C> {
override fun onControllerEvent(event: C) {
return onEvent(event)
}
}
}
private object UiControllers {
/**
* An empty Ui Controller singleton
*/
val EMPTY = newUiController<UnitControllerEvent> { }
}
/**
* Returns the no-op Empty Controller
*/
@CheckResult
public fun emptyController(): UiController<UnitControllerEvent> {
return UiControllers.EMPTY
}
| 18
| 0
| 1
|
add_only
|
--- a/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
+++ b/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
@@ -44 +44,19 @@
}
+
+private object UiControllers {
+
+ /**
+ * An empty Ui Controller singleton
+ */
+ val EMPTY = newUiController<UnitControllerEvent> { }
+
+}
+
+
+/**
+ * Returns the no-op Empty Controller
+ */
+@CheckResult
+public fun emptyController(): UiController<UnitControllerEvent> {
+ return UiControllers.EMPTY
+}
|
--- a/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
+++ b/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
@@ ... @@
}
+
+private object UiControllers {
+
+ /**
+ * An empty Ui Controller singleton
+ */
+ val EMPTY = newUiController<UnitControllerEvent> { }
+
+}
+
+
+/**
+ * Returns the no-op Empty Controller
+ */
+@CheckResult
+public fun emptyController(): UiController<UnitControllerEvent> {
+ return UiControllers.EMPTY
+}
|
--- a/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
+++ b/arch/src/main/java/com/pyamsoft/pydroid/arch/UiController.kt
@@ -44 +44,19 @@
CON }
ADD
ADD private object UiControllers {
ADD
ADD /**
ADD * An empty Ui Controller singleton
ADD */
ADD val EMPTY = newUiController<UnitControllerEvent> { }
ADD
ADD }
ADD
ADD
ADD /**
ADD * Returns the no-op Empty Controller
ADD */
ADD @CheckResult
ADD public fun emptyController(): UiController<UnitControllerEvent> {
ADD return UiControllers.EMPTY
ADD }
|
<<<<<<< SEARCH
}
}
}
=======
}
}
}
private object UiControllers {
/**
* An empty Ui Controller singleton
*/
val EMPTY = newUiController<UnitControllerEvent> { }
}
/**
* Returns the no-op Empty Controller
*/
@CheckResult
public fun emptyController(): UiController<UnitControllerEvent> {
return UiControllers.EMPTY
}
>>>>>>> REPLACE
|
Yakindu/statecharts
|
951e4508c8d0612dbcecbedb25a0ec60689b5fa5
|
plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
|
java
|
epl-1.0
|
Check if JST is available
|
/*
* generated by Xtext
*/
package org.yakindu.base.expressions.ui;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* Use this class to register components to be used within the IDE.
*/
public class ExpressionsUiModule extends org.yakindu.base.expressions.ui.AbstractExpressionsUiModule {
public ExpressionsUiModule(AbstractUIPlugin plugin) {
super(plugin);
}
}
|
/*
* generated by Xtext
*/
package org.yakindu.base.expressions.ui;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.xtext.ui.editor.model.IResourceForEditorInputFactory;
import org.eclipse.xtext.ui.editor.model.JavaClassPathResourceForIEditorInputFactory;
import org.eclipse.xtext.ui.editor.model.ResourceForIEditorInputFactory;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.eclipse.xtext.ui.resource.SimpleResourceSetProvider;
import org.eclipse.xtext.ui.resource.XtextResourceSetProvider;
import org.eclipse.xtext.ui.shared.Access;
/**
* Use this class to register components to be used within the IDE.
*/
public class ExpressionsUiModule extends org.yakindu.base.expressions.ui.AbstractExpressionsUiModule {
public ExpressionsUiModule(AbstractUIPlugin plugin) {
super(plugin);
}
public com.google.inject.Provider<org.eclipse.xtext.resource.containers.IAllContainersState> provideIAllContainersState() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return Access.getJavaProjectsState();
} else {
return Access.getWorkspaceProjectsState();
}
}
@Override
public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return XtextResourceSetProvider.class;
} else {
return SimpleResourceSetProvider.class;
}
}
@Override
public Class<? extends IResourceForEditorInputFactory> bindIResourceForEditorInputFactory() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return JavaClassPathResourceForIEditorInputFactory.class;
} else {
return ResourceForIEditorInputFactory.class;
}
}
}
| 33
| 0
| 2
|
add_only
|
--- a/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
+++ b/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
@@ -6,2 +6,9 @@
import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipse.xtext.ui.editor.model.IResourceForEditorInputFactory;
+import org.eclipse.xtext.ui.editor.model.JavaClassPathResourceForIEditorInputFactory;
+import org.eclipse.xtext.ui.editor.model.ResourceForIEditorInputFactory;
+import org.eclipse.xtext.ui.resource.IResourceSetProvider;
+import org.eclipse.xtext.ui.resource.SimpleResourceSetProvider;
+import org.eclipse.xtext.ui.resource.XtextResourceSetProvider;
+import org.eclipse.xtext.ui.shared.Access;
@@ -14,2 +21,28 @@
}
+
+ public com.google.inject.Provider<org.eclipse.xtext.resource.containers.IAllContainersState> provideIAllContainersState() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return Access.getJavaProjectsState();
+ } else {
+ return Access.getWorkspaceProjectsState();
+ }
+ }
+
+ @Override
+ public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return XtextResourceSetProvider.class;
+ } else {
+ return SimpleResourceSetProvider.class;
+ }
+ }
+
+ @Override
+ public Class<? extends IResourceForEditorInputFactory> bindIResourceForEditorInputFactory() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return JavaClassPathResourceForIEditorInputFactory.class;
+ } else {
+ return ResourceForIEditorInputFactory.class;
+ }
+ }
}
|
--- a/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
+++ b/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
@@ ... @@
import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipse.xtext.ui.editor.model.IResourceForEditorInputFactory;
+import org.eclipse.xtext.ui.editor.model.JavaClassPathResourceForIEditorInputFactory;
+import org.eclipse.xtext.ui.editor.model.ResourceForIEditorInputFactory;
+import org.eclipse.xtext.ui.resource.IResourceSetProvider;
+import org.eclipse.xtext.ui.resource.SimpleResourceSetProvider;
+import org.eclipse.xtext.ui.resource.XtextResourceSetProvider;
+import org.eclipse.xtext.ui.shared.Access;
@@ ... @@
}
+
+ public com.google.inject.Provider<org.eclipse.xtext.resource.containers.IAllContainersState> provideIAllContainersState() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return Access.getJavaProjectsState();
+ } else {
+ return Access.getWorkspaceProjectsState();
+ }
+ }
+
+ @Override
+ public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return XtextResourceSetProvider.class;
+ } else {
+ return SimpleResourceSetProvider.class;
+ }
+ }
+
+ @Override
+ public Class<? extends IResourceForEditorInputFactory> bindIResourceForEditorInputFactory() {
+ if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
+ return JavaClassPathResourceForIEditorInputFactory.class;
+ } else {
+ return ResourceForIEditorInputFactory.class;
+ }
+ }
}
|
--- a/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
+++ b/plugins/org.yakindu.base.expressions.ui/src/org/yakindu/base/expressions/ui/ExpressionsUiModule.java
@@ -6,2 +6,9 @@
CON import org.eclipse.ui.plugin.AbstractUIPlugin;
ADD import org.eclipse.xtext.ui.editor.model.IResourceForEditorInputFactory;
ADD import org.eclipse.xtext.ui.editor.model.JavaClassPathResourceForIEditorInputFactory;
ADD import org.eclipse.xtext.ui.editor.model.ResourceForIEditorInputFactory;
ADD import org.eclipse.xtext.ui.resource.IResourceSetProvider;
ADD import org.eclipse.xtext.ui.resource.SimpleResourceSetProvider;
ADD import org.eclipse.xtext.ui.resource.XtextResourceSetProvider;
ADD import org.eclipse.xtext.ui.shared.Access;
CON
@@ -14,2 +21,28 @@
CON }
ADD
ADD public com.google.inject.Provider<org.eclipse.xtext.resource.containers.IAllContainersState> provideIAllContainersState() {
ADD if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
ADD return Access.getJavaProjectsState();
ADD } else {
ADD return Access.getWorkspaceProjectsState();
ADD }
ADD }
ADD
ADD @Override
ADD public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
ADD if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
ADD return XtextResourceSetProvider.class;
ADD } else {
ADD return SimpleResourceSetProvider.class;
ADD }
ADD }
ADD
ADD @Override
ADD public Class<? extends IResourceForEditorInputFactory> bindIResourceForEditorInputFactory() {
ADD if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
ADD return JavaClassPathResourceForIEditorInputFactory.class;
ADD } else {
ADD return ResourceForIEditorInputFactory.class;
ADD }
ADD }
CON }
|
<<<<<<< SEARCH
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
=======
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.xtext.ui.editor.model.IResourceForEditorInputFactory;
import org.eclipse.xtext.ui.editor.model.JavaClassPathResourceForIEditorInputFactory;
import org.eclipse.xtext.ui.editor.model.ResourceForIEditorInputFactory;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.eclipse.xtext.ui.resource.SimpleResourceSetProvider;
import org.eclipse.xtext.ui.resource.XtextResourceSetProvider;
import org.eclipse.xtext.ui.shared.Access;
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
super(plugin);
}
}
=======
super(plugin);
}
public com.google.inject.Provider<org.eclipse.xtext.resource.containers.IAllContainersState> provideIAllContainersState() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return Access.getJavaProjectsState();
} else {
return Access.getWorkspaceProjectsState();
}
}
@Override
public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return XtextResourceSetProvider.class;
} else {
return SimpleResourceSetProvider.class;
}
}
@Override
public Class<? extends IResourceForEditorInputFactory> bindIResourceForEditorInputFactory() {
if (Access.getJdtHelper().get().isJavaCoreAvailable()) {
return JavaClassPathResourceForIEditorInputFactory.class;
} else {
return ResourceForIEditorInputFactory.class;
}
}
}
>>>>>>> REPLACE
|
reapp/reapp-kit
|
e8a15274e3a12a2c974051c79f5337c412b06217
|
src/lib/store.js
|
javascript
|
mit
|
Add higher order component for cursor
|
var Fynx = require('fynx');
var Immutable = require('immutable');
var cursor;
const store = function(obj) {
if (obj)
cursor = Fynx.createCursorStore(Immutable.fromJS(obj));
else
return cursor();
}
store.cursor = function() {
return cursor;
}
export default store;
|
import Fynx from 'fynx';
import Immutable from 'immutable';
import React from 'react';
var cursor;
const store = function(obj) {
if (obj)
cursor = Fynx.createCursorStore(Immutable.fromJS(obj));
else
return cursor();
}
store.cursor = function(path, Component) {
if (path) {
if (!Component)
return cursor().getIn(path);
return class CursoredComponent {
setCursors() {
this.cursors = {};
if (Array.isArray(path))
path.forEach(key => {
this.cursors[key] = cursor().get(key);
});
else
Object.keys(path).forEach(key => {
this.cursors[key] = cursor().getIn([].concat(path[key]));
});
}
componentWillMount() {
this.setCursors.call(this);
cursor.listen((newData, path) => {
debugger;
// this.forceRefresh();
});
}
render() {
return <Component {...this.props} {...this.cursors} />
}
};
}
return cursor;
}
export default store;
| 37
| 3
| 2
|
mixed
|
--- a/src/lib/store.js
+++ b/src/lib/store.js
@@ -1,3 +1,4 @@
-var Fynx = require('fynx');
-var Immutable = require('immutable');
+import Fynx from 'fynx';
+import Immutable from 'immutable';
+import React from 'react';
@@ -12,3 +13,36 @@
-store.cursor = function() {
+store.cursor = function(path, Component) {
+ if (path) {
+ if (!Component)
+ return cursor().getIn(path);
+
+ return class CursoredComponent {
+ setCursors() {
+ this.cursors = {};
+
+ if (Array.isArray(path))
+ path.forEach(key => {
+ this.cursors[key] = cursor().get(key);
+ });
+ else
+ Object.keys(path).forEach(key => {
+ this.cursors[key] = cursor().getIn([].concat(path[key]));
+ });
+ }
+
+ componentWillMount() {
+ this.setCursors.call(this);
+
+ cursor.listen((newData, path) => {
+ debugger;
+ // this.forceRefresh();
+ });
+ }
+
+ render() {
+ return <Component {...this.props} {...this.cursors} />
+ }
+ };
+ }
+
return cursor;
|
--- a/src/lib/store.js
+++ b/src/lib/store.js
@@ ... @@
-var Fynx = require('fynx');
-var Immutable = require('immutable');
+import Fynx from 'fynx';
+import Immutable from 'immutable';
+import React from 'react';
@@ ... @@
-store.cursor = function() {
+store.cursor = function(path, Component) {
+ if (path) {
+ if (!Component)
+ return cursor().getIn(path);
+
+ return class CursoredComponent {
+ setCursors() {
+ this.cursors = {};
+
+ if (Array.isArray(path))
+ path.forEach(key => {
+ this.cursors[key] = cursor().get(key);
+ });
+ else
+ Object.keys(path).forEach(key => {
+ this.cursors[key] = cursor().getIn([].concat(path[key]));
+ });
+ }
+
+ componentWillMount() {
+ this.setCursors.call(this);
+
+ cursor.listen((newData, path) => {
+ debugger;
+ // this.forceRefresh();
+ });
+ }
+
+ render() {
+ return <Component {...this.props} {...this.cursors} />
+ }
+ };
+ }
+
return cursor;
|
--- a/src/lib/store.js
+++ b/src/lib/store.js
@@ -1,3 +1,4 @@
DEL var Fynx = require('fynx');
DEL var Immutable = require('immutable');
ADD import Fynx from 'fynx';
ADD import Immutable from 'immutable';
ADD import React from 'react';
CON
@@ -12,3 +13,36 @@
CON
DEL store.cursor = function() {
ADD store.cursor = function(path, Component) {
ADD if (path) {
ADD if (!Component)
ADD return cursor().getIn(path);
ADD
ADD return class CursoredComponent {
ADD setCursors() {
ADD this.cursors = {};
ADD
ADD if (Array.isArray(path))
ADD path.forEach(key => {
ADD this.cursors[key] = cursor().get(key);
ADD });
ADD else
ADD Object.keys(path).forEach(key => {
ADD this.cursors[key] = cursor().getIn([].concat(path[key]));
ADD });
ADD }
ADD
ADD componentWillMount() {
ADD this.setCursors.call(this);
ADD
ADD cursor.listen((newData, path) => {
ADD debugger;
ADD // this.forceRefresh();
ADD });
ADD }
ADD
ADD render() {
ADD return <Component {...this.props} {...this.cursors} />
ADD }
ADD };
ADD }
ADD
CON return cursor;
|
<<<<<<< SEARCH
var Fynx = require('fynx');
var Immutable = require('immutable');
var cursor;
=======
import Fynx from 'fynx';
import Immutable from 'immutable';
import React from 'react';
var cursor;
>>>>>>> REPLACE
<<<<<<< SEARCH
}
store.cursor = function() {
return cursor;
}
=======
}
store.cursor = function(path, Component) {
if (path) {
if (!Component)
return cursor().getIn(path);
return class CursoredComponent {
setCursors() {
this.cursors = {};
if (Array.isArray(path))
path.forEach(key => {
this.cursors[key] = cursor().get(key);
});
else
Object.keys(path).forEach(key => {
this.cursors[key] = cursor().getIn([].concat(path[key]));
});
}
componentWillMount() {
this.setCursors.call(this);
cursor.listen((newData, path) => {
debugger;
// this.forceRefresh();
});
}
render() {
return <Component {...this.props} {...this.cursors} />
}
};
}
return cursor;
}
>>>>>>> REPLACE
|
ec-geolink/d1lod
|
1dade842098292f2201502fa55239a98628dfc2b
|
scheduler/schedule.py
|
python
|
apache-2.0
|
Set update job timeout back to a more reasonable value
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
| 1
| 1
| 1
|
mixed
|
--- a/scheduler/schedule.py
+++ b/scheduler/schedule.py
@@ -18,3 +18,3 @@
def queue_update_job():
- q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
+ q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
|
--- a/scheduler/schedule.py
+++ b/scheduler/schedule.py
@@ ... @@
def queue_update_job():
- q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
+ q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
|
--- a/scheduler/schedule.py
+++ b/scheduler/schedule.py
@@ -18,3 +18,3 @@
CON def queue_update_job():
DEL q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
ADD q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
CON
|
<<<<<<< SEARCH
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
@sched.scheduled_job('interval', minutes=1)
=======
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
>>>>>>> REPLACE
|
adnanademovic/rosrust
|
e7f06b48410c8f78e21e8cd54ebdfe9130f058b6
|
rosrust/src/raw_message.rs
|
rust
|
mit
|
Allow RawMessage as a service pair
|
use crate::{Message, RosMsg};
use std::io;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawMessage(pub Vec<u8>);
#[derive(Clone, Debug, PartialEq)]
pub struct RawMessageDescription {
pub msg_definition: String,
pub md5sum: String,
pub msg_type: String,
}
impl RawMessageDescription {
pub fn from_message<T: Message>() -> Self {
Self {
msg_definition: T::msg_definition(),
md5sum: T::md5sum(),
msg_type: T::msg_type(),
}
}
}
impl Message for RawMessage {
fn msg_definition() -> String {
"*".into()
}
fn md5sum() -> String {
"*".into()
}
fn msg_type() -> String {
"*".into()
}
}
impl RosMsg for RawMessage {
fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> {
w.write_all(&self.0)
}
fn decode<R: io::Read>(mut r: R) -> io::Result<Self> {
let mut data = vec![];
r.read_to_end(&mut data)?;
Ok(Self(data))
}
}
|
use crate::{Message, RosMsg, ServicePair};
use std::io;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawMessage(pub Vec<u8>);
#[derive(Clone, Debug, PartialEq)]
pub struct RawMessageDescription {
pub msg_definition: String,
pub md5sum: String,
pub msg_type: String,
}
impl RawMessageDescription {
pub fn from_message<T: Message>() -> Self {
Self {
msg_definition: T::msg_definition(),
md5sum: T::md5sum(),
msg_type: T::msg_type(),
}
}
}
impl Message for RawMessage {
fn msg_definition() -> String {
"*".into()
}
fn md5sum() -> String {
"*".into()
}
fn msg_type() -> String {
"*".into()
}
}
impl RosMsg for RawMessage {
fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> {
w.write_all(&self.0)
}
fn decode<R: io::Read>(mut r: R) -> io::Result<Self> {
let mut data = vec![];
r.read_to_end(&mut data)?;
Ok(Self(data))
}
}
impl ServicePair for RawMessage {
type Request = RawMessage;
type Response = RawMessage;
}
| 6
| 1
| 2
|
mixed
|
--- a/rosrust/src/raw_message.rs
+++ b/rosrust/src/raw_message.rs
@@ -1,2 +1,2 @@
-use crate::{Message, RosMsg};
+use crate::{Message, RosMsg, ServicePair};
use std::io;
@@ -48 +48,6 @@
}
+
+impl ServicePair for RawMessage {
+ type Request = RawMessage;
+ type Response = RawMessage;
+}
|
--- a/rosrust/src/raw_message.rs
+++ b/rosrust/src/raw_message.rs
@@ ... @@
-use crate::{Message, RosMsg};
+use crate::{Message, RosMsg, ServicePair};
use std::io;
@@ ... @@
}
+
+impl ServicePair for RawMessage {
+ type Request = RawMessage;
+ type Response = RawMessage;
+}
|
--- a/rosrust/src/raw_message.rs
+++ b/rosrust/src/raw_message.rs
@@ -1,2 +1,2 @@
DEL use crate::{Message, RosMsg};
ADD use crate::{Message, RosMsg, ServicePair};
CON use std::io;
@@ -48 +48,6 @@
CON }
ADD
ADD impl ServicePair for RawMessage {
ADD type Request = RawMessage;
ADD type Response = RawMessage;
ADD }
|
<<<<<<< SEARCH
use crate::{Message, RosMsg};
use std::io;
=======
use crate::{Message, RosMsg, ServicePair};
use std::io;
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
=======
}
}
impl ServicePair for RawMessage {
type Request = RawMessage;
type Response = RawMessage;
}
>>>>>>> REPLACE
|
luxons/seven-wonders
|
ff992db4ec52331ceb753cae1e8b73fa90adb334
|
sw-server/build.gradle.kts
|
kotlin
|
mit
|
Upgrade to Spring Boot 2.4.0
|
plugins {
kotlin("jvm")
kotlin("plugin.spring")
id("org.springframework.boot") version "2.3.3.RELEASE"
}
apply(plugin = "io.spring.dependency-management")
dependencies {
implementation(project(":sw-common-model"))
implementation(project(":sw-engine"))
implementation(project(":sw-bot"))
implementation(kotlin("reflect")) // required by Spring 5
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1")
implementation("org.springframework.boot:spring-boot-starter-websocket")
implementation("org.springframework.boot:spring-boot-starter-security")
// required by spring security when using websockets
implementation("org.springframework.security:spring-security-messaging")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("ch.qos.logback:logback-classic:1.1.8")
testImplementation(kotlin("test"))
testImplementation(kotlin("test-junit"))
testImplementation(project(":sw-client"))
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin")
}
tasks.processResources {
// package the frontend app within the jar as static
val frontendBuildDir = project(":sw-ui").buildDir
val frontendDist = frontendBuildDir.toPath().resolve("distributions")
from(frontendDist) {
include("**/*")
into("static")
}
}
// make sure we build the frontend before creating the jar
tasks.processResources.get().dependsOn(":sw-ui:assemble")
|
plugins {
kotlin("jvm")
kotlin("plugin.spring")
id("org.springframework.boot") version "2.4.0"
}
apply(plugin = "io.spring.dependency-management")
dependencies {
implementation(project(":sw-common-model"))
implementation(project(":sw-engine"))
implementation(project(":sw-bot"))
implementation(kotlin("reflect")) // required by Spring 5
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1")
implementation("org.springframework.boot:spring-boot-starter-websocket")
implementation("org.springframework.boot:spring-boot-starter-security")
// required by spring security when using websockets
implementation("org.springframework.security:spring-security-messaging")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("ch.qos.logback:logback-classic:1.1.8")
testImplementation(kotlin("test"))
testImplementation(kotlin("test-junit"))
testImplementation(project(":sw-client"))
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin")
}
tasks.processResources {
// package the frontend app within the jar as static
val frontendBuildDir = project(":sw-ui").buildDir
val frontendDist = frontendBuildDir.toPath().resolve("distributions")
from(frontendDist) {
include("**/*")
into("static")
}
}
// make sure we build the frontend before creating the jar
tasks.processResources.get().dependsOn(":sw-ui:assemble")
| 1
| 1
| 1
|
mixed
|
--- a/sw-server/build.gradle.kts
+++ b/sw-server/build.gradle.kts
@@ -3,3 +3,3 @@
kotlin("plugin.spring")
- id("org.springframework.boot") version "2.3.3.RELEASE"
+ id("org.springframework.boot") version "2.4.0"
}
|
--- a/sw-server/build.gradle.kts
+++ b/sw-server/build.gradle.kts
@@ ... @@
kotlin("plugin.spring")
- id("org.springframework.boot") version "2.3.3.RELEASE"
+ id("org.springframework.boot") version "2.4.0"
}
|
--- a/sw-server/build.gradle.kts
+++ b/sw-server/build.gradle.kts
@@ -3,3 +3,3 @@
CON kotlin("plugin.spring")
DEL id("org.springframework.boot") version "2.3.3.RELEASE"
ADD id("org.springframework.boot") version "2.4.0"
CON }
|
<<<<<<< SEARCH
kotlin("jvm")
kotlin("plugin.spring")
id("org.springframework.boot") version "2.3.3.RELEASE"
}
=======
kotlin("jvm")
kotlin("plugin.spring")
id("org.springframework.boot") version "2.4.0"
}
>>>>>>> REPLACE
|
ECSE456-G29/Untitled
|
fb0774f1838552fe450351325e6e1330442c8962
|
src/main/java/App.java
|
java
|
epl-1.0
|
Add init as a command
resolves #5
|
import parse.GreetParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("greet")) {
GreetParser p = new GreetParser(args);
p.parse();
} else {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
}
}
|
import backend.Core;
import java.io.IOException;
import parse.GreetParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init");
System.exit(1);
}
}
}
| 20
| 2
| 2
|
mixed
|
--- a/src/main/java/App.java
+++ b/src/main/java/App.java
@@ -1 +1,3 @@
+import backend.Core;
+import java.io.IOException;
import parse.GreetParser;
@@ -13,7 +15,23 @@
public static void main(String[] args) {
- if (args.length > 0 && args[0].equals("greet")) {
+ if (args.length < 1) {
+ System.out.println("Available commands:\n\tgreet");
+ System.exit(1);
+ }
+
+ if (args[0].equals("greet")) {
+ // Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
+ } else if (args[0].equals("init")) {
+ // Initializes an empty git repo
+ try {
+ Core.initCore();
+ } catch (IOException e) {
+ System.err.println("Could not init g2t");
+ e.printStackTrace();
+ }
+ System.exit(0);
} else {
- System.out.println("Available commands:\n\tgreet");
+ System.out.println("Available commands:\n"
+ + "\tgreet, init");
System.exit(1);
|
--- a/src/main/java/App.java
+++ b/src/main/java/App.java
@@ ... @@
+import backend.Core;
+import java.io.IOException;
import parse.GreetParser;
@@ ... @@
public static void main(String[] args) {
- if (args.length > 0 && args[0].equals("greet")) {
+ if (args.length < 1) {
+ System.out.println("Available commands:\n\tgreet");
+ System.exit(1);
+ }
+
+ if (args[0].equals("greet")) {
+ // Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
+ } else if (args[0].equals("init")) {
+ // Initializes an empty git repo
+ try {
+ Core.initCore();
+ } catch (IOException e) {
+ System.err.println("Could not init g2t");
+ e.printStackTrace();
+ }
+ System.exit(0);
} else {
- System.out.println("Available commands:\n\tgreet");
+ System.out.println("Available commands:\n"
+ + "\tgreet, init");
System.exit(1);
|
--- a/src/main/java/App.java
+++ b/src/main/java/App.java
@@ -1 +1,3 @@
ADD import backend.Core;
ADD import java.io.IOException;
CON import parse.GreetParser;
@@ -13,7 +15,23 @@
CON public static void main(String[] args) {
DEL if (args.length > 0 && args[0].equals("greet")) {
ADD if (args.length < 1) {
ADD System.out.println("Available commands:\n\tgreet");
ADD System.exit(1);
ADD }
ADD
ADD if (args[0].equals("greet")) {
ADD // Greet just exists as a template for parsing
CON GreetParser p = new GreetParser(args);
CON p.parse();
ADD } else if (args[0].equals("init")) {
ADD // Initializes an empty git repo
ADD try {
ADD Core.initCore();
ADD } catch (IOException e) {
ADD System.err.println("Could not init g2t");
ADD e.printStackTrace();
ADD }
ADD System.exit(0);
CON } else {
DEL System.out.println("Available commands:\n\tgreet");
ADD System.out.println("Available commands:\n"
ADD + "\tgreet, init");
CON System.exit(1);
|
<<<<<<< SEARCH
import parse.GreetParser;
=======
import backend.Core;
import java.io.IOException;
import parse.GreetParser;
>>>>>>> REPLACE
<<<<<<< SEARCH
*/
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("greet")) {
GreetParser p = new GreetParser(args);
p.parse();
} else {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
=======
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init");
System.exit(1);
}
>>>>>>> REPLACE
|
uqbar-project/wiki
|
3ab1b54e222fd82d4cb2b3c19132cad83f6997a0
|
wiki/articles/algo2.build.gradle.kts
|
kotlin
|
lgpl-2.1
|
Update to new version of Kotlin plugin
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.5.31"
jacoco
}
group = "ar.edu.unsam.algo2"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
val kotestVersion = "5.1.0"
dependencies {
implementation(kotlin("stdlib"))
testImplementation("io.mockk:mockk:1.12.2")
testImplementation("io.kotest:kotest-runner-junit5:$kotestVersion")
testImplementation("io.kotest:kotest-assertions-core:$kotestVersion")
testImplementation("io.kotest:kotest-runner-junit5:$kotestVersion")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "14"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.test {
finalizedBy(tasks.jacocoTestReport)
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
}
jacoco {
toolVersion = "0.8.7"
}
tasks.jacocoTestReport {
reports {
xml.isEnabled = true
csv.isEnabled = false
html.isEnabled = false
}
}
tasks.register("runOnGitHub") {
dependsOn("jacocoTestReport")
group = "custom"
description = "$ ./gradlew runOnGitHub # runs on GitHub Action"
}
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.6.10"
jacoco
}
group = "ar.edu.unsam.algo2"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
val kotestVersion = "5.1.0"
dependencies {
implementation(kotlin("stdlib"))
testImplementation("io.mockk:mockk:1.12.2")
testImplementation("io.kotest:kotest-runner-junit5:$kotestVersion")
testImplementation("io.kotest:kotest-assertions-core:$kotestVersion")
testImplementation("io.kotest:kotest-runner-junit5:$kotestVersion")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "14"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.test {
finalizedBy(tasks.jacocoTestReport)
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
}
jacoco {
toolVersion = "0.8.7"
}
tasks.jacocoTestReport {
reports {
xml.isEnabled = true
csv.isEnabled = false
html.isEnabled = false
}
}
tasks.register("runOnGitHub") {
dependsOn("jacocoTestReport")
group = "custom"
description = "$ ./gradlew runOnGitHub # runs on GitHub Action"
}
| 1
| 1
| 1
|
mixed
|
--- a/wiki/articles/algo2.build.gradle.kts
+++ b/wiki/articles/algo2.build.gradle.kts
@@ -3,3 +3,3 @@
plugins {
- kotlin("jvm") version "1.5.31"
+ kotlin("jvm") version "1.6.10"
jacoco
|
--- a/wiki/articles/algo2.build.gradle.kts
+++ b/wiki/articles/algo2.build.gradle.kts
@@ ... @@
plugins {
- kotlin("jvm") version "1.5.31"
+ kotlin("jvm") version "1.6.10"
jacoco
|
--- a/wiki/articles/algo2.build.gradle.kts
+++ b/wiki/articles/algo2.build.gradle.kts
@@ -3,3 +3,3 @@
CON plugins {
DEL kotlin("jvm") version "1.5.31"
ADD kotlin("jvm") version "1.6.10"
CON jacoco
|
<<<<<<< SEARCH
plugins {
kotlin("jvm") version "1.5.31"
jacoco
}
=======
plugins {
kotlin("jvm") version "1.6.10"
jacoco
}
>>>>>>> REPLACE
|
goeckeler/connect4
|
16ccf57c4f5237058fcc3f00a72f0367e48bfe45
|
shared/src/main/java/game/Board.java
|
java
|
apache-2.0
|
Revoke starting player from the board.
|
package game;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Optional;
/**
* Created by Dimitry on 14.05.2016.
*/
public class Board
{
private Player startingPlayer;
private final int numberOfRows;
private final int numberOfColumns;
private Player[][] occupiers;
public Board(final int numberOfRows, final int numberOfColumns) {
this.numberOfRows = numberOfRows;
this.numberOfColumns = numberOfColumns;
occupiers = new Player[numberOfRows][numberOfColumns];
}
public Optional<Player> slotOwner(final int row, final int column) {
if (occupiers[row][column] == null) {
return Optional.empty();
} else {
return Optional.of(occupiers[row][column]);
}
}
public void insertChip(final int columnNumber, final Player player) {
int index = numberOfRows - 1;
while (index >= 0 && occupiers[index][columnNumber] != null) {
index--;
}
checkArgument(index >= 0);
occupiers[index][columnNumber] = player;
}
public int getNumberOfRows() {
return numberOfRows;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
public void setStartingPlayer(final Player player) {
this.startingPlayer = player;
}
public Player getStartingPlayer() {
return startingPlayer;
}
}
|
package game;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Optional;
/**
* Created by Dimitry on 14.05.2016.
*/
public class Board
{
private final int numberOfRows;
private final int numberOfColumns;
private Player[][] occupiers;
public Board(final int numberOfRows, final int numberOfColumns) {
this.numberOfRows = numberOfRows;
this.numberOfColumns = numberOfColumns;
occupiers = new Player[numberOfRows][numberOfColumns];
}
public Optional<Player> slotOwner(final int row, final int column) {
if (occupiers[row][column] == null) {
return Optional.empty();
} else {
return Optional.of(occupiers[row][column]);
}
}
public void insertChip(final int columnNumber, final Player player) {
int index = numberOfRows - 1;
while (index >= 0 && occupiers[index][columnNumber] != null) {
index--;
}
checkArgument(index >= 0);
occupiers[index][columnNumber] = player;
}
public int getNumberOfRows() {
return numberOfRows;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
}
| 0
| 9
| 2
|
del_only
|
--- a/shared/src/main/java/game/Board.java
+++ b/shared/src/main/java/game/Board.java
@@ -11,3 +11,2 @@
{
- private Player startingPlayer;
private final int numberOfRows;
@@ -46,10 +45,2 @@
}
-
- public void setStartingPlayer(final Player player) {
- this.startingPlayer = player;
- }
-
- public Player getStartingPlayer() {
- return startingPlayer;
- }
}
|
--- a/shared/src/main/java/game/Board.java
+++ b/shared/src/main/java/game/Board.java
@@ ... @@
{
- private Player startingPlayer;
private final int numberOfRows;
@@ ... @@
}
-
- public void setStartingPlayer(final Player player) {
- this.startingPlayer = player;
- }
-
- public Player getStartingPlayer() {
- return startingPlayer;
- }
}
|
--- a/shared/src/main/java/game/Board.java
+++ b/shared/src/main/java/game/Board.java
@@ -11,3 +11,2 @@
CON {
DEL private Player startingPlayer;
CON private final int numberOfRows;
@@ -46,10 +45,2 @@
CON }
DEL
DEL public void setStartingPlayer(final Player player) {
DEL this.startingPlayer = player;
DEL }
DEL
DEL public Player getStartingPlayer() {
DEL return startingPlayer;
DEL }
CON }
|
<<<<<<< SEARCH
public class Board
{
private Player startingPlayer;
private final int numberOfRows;
private final int numberOfColumns;
=======
public class Board
{
private final int numberOfRows;
private final int numberOfColumns;
>>>>>>> REPLACE
<<<<<<< SEARCH
return numberOfColumns;
}
public void setStartingPlayer(final Player player) {
this.startingPlayer = player;
}
public Player getStartingPlayer() {
return startingPlayer;
}
}
=======
return numberOfColumns;
}
}
>>>>>>> REPLACE
|
brennie/reviewboard
|
9c46dc1526497e26eea77ad76228df89cd1c03e7
|
reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
|
javascript
|
mit
|
Fix resource paths for user file attachments.
When I fixed the names in the user file attachments resource to make it
available within the API templates, I neglected to actually test the javascript
in the Review Board UI, which was still using the old paths and names. This
change fixes it.
Testing done:
Drag-and-dropped an image into a review header.
Reviewed at https://reviews.reviewboard.org/r/8860/
|
/**
* A new or existing user file attachment.
*
* Model Attributes:
* caption (string):
* The file attachment's caption.
*
* userName (string):
* The username of the owner of the file attachment.
*
* downloadURL (string):
* The URL to download the file, for existing file attachments.
*
* file (file):
* The file to upload. Only works for newly created
* UserFileAttachments.
*
* filename (string):
* The name of the file, for existing file attachments.
*/
RB.UserFileAttachment = RB.BaseResource.extend({
defaults() {
return _.defaults({
caption: null,
userName: '',
downloadURL: null,
file: null,
filename: null
}, RB.BaseResource.prototype.defaults());
},
rspNamespace: 'file_attachment',
payloadFileKeys: ['path'],
attrToJsonMap: {
downloadURL: 'absolute_url',
file: 'path'
},
serializedAttrs: [
'caption',
'file'
],
deserializedAttrs: [
'caption',
'downloadURL',
'filename'
],
serializers: {
file: RB.JSONSerializers.onlyIfValue
},
/**
* Return the URL to use for syncing the model.
*
* Returns:
* string:
* The URL for the resource.
*/
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
}
});
|
/**
* A new or existing user file attachment.
*
* Model Attributes:
* caption (string):
* The file attachment's caption.
*
* userName (string):
* The username of the owner of the file attachment.
*
* downloadURL (string):
* The URL to download the file, for existing file attachments.
*
* file (file):
* The file to upload. Only works for newly created
* UserFileAttachments.
*
* filename (string):
* The name of the file, for existing file attachments.
*/
RB.UserFileAttachment = RB.BaseResource.extend({
defaults() {
return _.defaults({
caption: null,
userName: '',
downloadURL: null,
file: null,
filename: null
}, RB.BaseResource.prototype.defaults());
},
rspNamespace: 'user_file_attachment',
payloadFileKeys: ['path'],
attrToJsonMap: {
downloadURL: 'absolute_url',
file: 'path'
},
serializedAttrs: [
'caption',
'file'
],
deserializedAttrs: [
'caption',
'downloadURL',
'filename'
],
serializers: {
file: RB.JSONSerializers.onlyIfValue
},
/**
* Return the URL to use for syncing the model.
*
* Returns:
* string:
* The URL for the resource.
*/
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
}
});
| 2
| 2
| 2
|
mixed
|
--- a/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
+++ b/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
@@ -31,3 +31,3 @@
- rspNamespace: 'file_attachment',
+ rspNamespace: 'user_file_attachment',
payloadFileKeys: ['path'],
@@ -63,3 +63,3 @@
const username = this.get('userName');
- const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
+ const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
|
--- a/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
+++ b/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
@@ ... @@
- rspNamespace: 'file_attachment',
+ rspNamespace: 'user_file_attachment',
payloadFileKeys: ['path'],
@@ ... @@
const username = this.get('userName');
- const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
+ const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
|
--- a/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
+++ b/reviewboard/static/rb/js/resources/models/userFileAttachmentModel.es6.js
@@ -31,3 +31,3 @@
CON
DEL rspNamespace: 'file_attachment',
ADD rspNamespace: 'user_file_attachment',
CON payloadFileKeys: ['path'],
@@ -63,3 +63,3 @@
CON const username = this.get('userName');
DEL const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
ADD const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
CON
|
<<<<<<< SEARCH
},
rspNamespace: 'file_attachment',
payloadFileKeys: ['path'],
=======
},
rspNamespace: 'user_file_attachment',
payloadFileKeys: ['path'],
>>>>>>> REPLACE
<<<<<<< SEARCH
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
=======
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
>>>>>>> REPLACE
|
dtolnay/syn
|
95bec6aea28ba3d985576a4e7149e9b36e6396fc
|
tests/common/parse.rs
|
rust
|
apache-2.0
|
Update test suite to nightly-2020-01-10
|
extern crate rustc_expand;
extern crate rustc_parse as parse;
extern crate rustc_span;
extern crate syntax;
use rustc_span::source_map::FilePathMapping;
use rustc_span::FileName;
use syntax::ast;
use syntax::ptr::P;
use syntax::sess::ParseSess;
use std::panic;
pub fn libsyntax_expr(input: &str) -> Option<P<ast::Expr>> {
match panic::catch_unwind(|| {
let sess = ParseSess::new(FilePathMapping::empty());
sess.span_diagnostic.set_continue_after_error(false);
let e = parse::new_parser_from_source_str(
&sess,
FileName::Custom("test_precedence".to_string()),
input.to_string(),
)
.parse_expr();
match e {
Ok(expr) => Some(expr),
Err(mut diagnostic) => {
diagnostic.emit();
None
}
}
}) {
Ok(Some(e)) => Some(e),
Ok(None) => None,
Err(_) => {
errorf!("libsyntax panicked\n");
None
}
}
}
pub fn syn_expr(input: &str) -> Option<syn::Expr> {
match syn::parse_str(input) {
Ok(e) => Some(e),
Err(msg) => {
errorf!("syn failed to parse\n{:?}\n", msg);
None
}
}
}
|
extern crate rustc_expand;
extern crate rustc_parse as parse;
extern crate rustc_span;
extern crate syntax;
use rustc_span::source_map::FilePathMapping;
use rustc_span::FileName;
use syntax::ast;
use syntax::ptr::P;
use syntax::sess::ParseSess;
use std::panic;
pub fn libsyntax_expr(input: &str) -> Option<P<ast::Expr>> {
match panic::catch_unwind(|| {
let sess = ParseSess::new(FilePathMapping::empty());
let e = parse::new_parser_from_source_str(
&sess,
FileName::Custom("test_precedence".to_string()),
input.to_string(),
)
.parse_expr();
match e {
Ok(expr) => Some(expr),
Err(mut diagnostic) => {
diagnostic.emit();
None
}
}
}) {
Ok(Some(e)) => Some(e),
Ok(None) => None,
Err(_) => {
errorf!("libsyntax panicked\n");
None
}
}
}
pub fn syn_expr(input: &str) -> Option<syn::Expr> {
match syn::parse_str(input) {
Ok(e) => Some(e),
Err(msg) => {
errorf!("syn failed to parse\n{:?}\n", msg);
None
}
}
}
| 0
| 1
| 1
|
del_only
|
--- a/tests/common/parse.rs
+++ b/tests/common/parse.rs
@@ -16,3 +16,2 @@
let sess = ParseSess::new(FilePathMapping::empty());
- sess.span_diagnostic.set_continue_after_error(false);
let e = parse::new_parser_from_source_str(
|
--- a/tests/common/parse.rs
+++ b/tests/common/parse.rs
@@ ... @@
let sess = ParseSess::new(FilePathMapping::empty());
- sess.span_diagnostic.set_continue_after_error(false);
let e = parse::new_parser_from_source_str(
|
--- a/tests/common/parse.rs
+++ b/tests/common/parse.rs
@@ -16,3 +16,2 @@
CON let sess = ParseSess::new(FilePathMapping::empty());
DEL sess.span_diagnostic.set_continue_after_error(false);
CON let e = parse::new_parser_from_source_str(
|
<<<<<<< SEARCH
match panic::catch_unwind(|| {
let sess = ParseSess::new(FilePathMapping::empty());
sess.span_diagnostic.set_continue_after_error(false);
let e = parse::new_parser_from_source_str(
&sess,
=======
match panic::catch_unwind(|| {
let sess = ParseSess::new(FilePathMapping::empty());
let e = parse::new_parser_from_source_str(
&sess,
>>>>>>> REPLACE
|
squanchy-dev/squanchy-android
|
90850324bd7a250ff63ec4bfec93c5615b8b0301
|
app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
|
kotlin
|
apache-2.0
|
Use @PropertyName for FirestoreTrack fields which use snake_case on the DB
|
package net.squanchy.service.firestore.model.schedule
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
|
package net.squanchy.service.firestore.model.schedule
import com.google.firebase.firestore.PropertyName
import java.util.Date
class FirestoreSchedulePage {
lateinit var day: FirestoreDay
var events: List<FirestoreEvent> = emptyList()
}
class FirestoreDay {
lateinit var id: String
lateinit var date: Date
}
class FirestoreEvent {
lateinit var id: String
lateinit var title: String
lateinit var startTime: Date
lateinit var endTime: Date
var place: FirestorePlace? = null
var track: FirestoreTrack? = null
var speakers: List<FirestoreSpeaker> = emptyList()
var experienceLevel: String? = null
lateinit var type: String
var description: String? = null
}
class FirestorePlace {
lateinit var id: String
lateinit var name: String
var floor: String? = null
}
class FirestoreTrack {
lateinit var id: String
lateinit var name: String
@JvmField
@field:PropertyName("accent_color")
var accentColor: String? = null
@JvmField
@field:PropertyName("text_color")
var textColor: String? = null
@JvmField
@field:PropertyName("icon_url")
var iconUrl: String? = null
}
class FirestoreSpeaker {
lateinit var id: String
lateinit var name: String
lateinit var bio: String
var companyName: String? = null
var companyUrl: String? = null
var personalUrl: String? = null
var photoUrl: String? = null
var twitterUsername: String? = null
}
| 7
| 0
| 2
|
add_only
|
--- a/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
+++ b/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
@@ -2,2 +2,3 @@
+import com.google.firebase.firestore.PropertyName
import java.util.Date
@@ -36,4 +37,10 @@
lateinit var name: String
+ @JvmField
+ @field:PropertyName("accent_color")
var accentColor: String? = null
+ @JvmField
+ @field:PropertyName("text_color")
var textColor: String? = null
+ @JvmField
+ @field:PropertyName("icon_url")
var iconUrl: String? = null
|
--- a/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
+++ b/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
@@ ... @@
+import com.google.firebase.firestore.PropertyName
import java.util.Date
@@ ... @@
lateinit var name: String
+ @JvmField
+ @field:PropertyName("accent_color")
var accentColor: String? = null
+ @JvmField
+ @field:PropertyName("text_color")
var textColor: String? = null
+ @JvmField
+ @field:PropertyName("icon_url")
var iconUrl: String? = null
|
--- a/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
+++ b/app/src/main/java/net/squanchy/service/firestore/model/schedule/FirestoreSchedule.kt
@@ -2,2 +2,3 @@
CON
ADD import com.google.firebase.firestore.PropertyName
CON import java.util.Date
@@ -36,4 +37,10 @@
CON lateinit var name: String
ADD @JvmField
ADD @field:PropertyName("accent_color")
CON var accentColor: String? = null
ADD @JvmField
ADD @field:PropertyName("text_color")
CON var textColor: String? = null
ADD @JvmField
ADD @field:PropertyName("icon_url")
CON var iconUrl: String? = null
|
<<<<<<< SEARCH
package net.squanchy.service.firestore.model.schedule
import java.util.Date
=======
package net.squanchy.service.firestore.model.schedule
import com.google.firebase.firestore.PropertyName
import java.util.Date
>>>>>>> REPLACE
<<<<<<< SEARCH
lateinit var id: String
lateinit var name: String
var accentColor: String? = null
var textColor: String? = null
var iconUrl: String? = null
}
=======
lateinit var id: String
lateinit var name: String
@JvmField
@field:PropertyName("accent_color")
var accentColor: String? = null
@JvmField
@field:PropertyName("text_color")
var textColor: String? = null
@JvmField
@field:PropertyName("icon_url")
var iconUrl: String? = null
}
>>>>>>> REPLACE
|
chimbori/crux
|
dc1151edc09034cef79d028b90b1f315041e02cc
|
build.gradle.kts
|
kotlin
|
apache-2.0
|
Use consistent formatting with specifying the `version` in `plugins`.
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm").version("1.6.20")
id("com.vanniktech.maven.publish") version ("0.19.0")
id("com.github.ben-manes.versions") version "0.42.0"
}
repositories {
mavenCentral()
}
buildscript {
extra["kotlinVersion"] = "1.6.20"
repositories {
mavenCentral()
}
dependencies {
classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
}
}
dependencies {
api("org.jsoup:jsoup:1.14.3")
api("com.squareup.okhttp3:okhttp:4.9.3")
implementation("org.apache.commons:commons-text:1.9")
testImplementation("junit:junit:4.13.2")
}
configurations.all {
// Re-run tests every time test cases are updated, even if sources haven’t changed.
resolutionStrategy.cacheChangingModulesFor(0, "seconds")
}
tasks.jar {
archiveBaseName.set("crux")
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
allWarningsAsErrors = true
}
}
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.6.20"
id("com.vanniktech.maven.publish") version "0.19.0"
id("com.github.ben-manes.versions") version "0.42.0"
}
repositories {
mavenCentral()
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath(kotlin("gradle-plugin", version = "1.6.20"))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
}
}
dependencies {
api("org.jsoup:jsoup:1.14.3")
api("com.squareup.okhttp3:okhttp:4.9.3")
implementation("org.apache.commons:commons-text:1.9")
testImplementation("junit:junit:4.13.2")
}
configurations.all {
// Re-run tests every time test cases are updated, even if sources haven’t changed.
resolutionStrategy.cacheChangingModulesFor(0, "seconds")
}
tasks.jar {
archiveBaseName.set("crux")
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
allWarningsAsErrors = true
}
}
| 3
| 4
| 3
|
mixed
|
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -3,4 +3,4 @@
plugins {
- kotlin("jvm").version("1.6.20")
- id("com.vanniktech.maven.publish") version ("0.19.0")
+ kotlin("jvm") version "1.6.20"
+ id("com.vanniktech.maven.publish") version "0.19.0"
id("com.github.ben-manes.versions") version "0.42.0"
@@ -13,3 +13,2 @@
buildscript {
- extra["kotlinVersion"] = "1.6.20"
repositories {
@@ -18,3 +17,3 @@
dependencies {
- classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
+ classpath(kotlin("gradle-plugin", version = "1.6.20"))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
|
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ ... @@
plugins {
- kotlin("jvm").version("1.6.20")
- id("com.vanniktech.maven.publish") version ("0.19.0")
+ kotlin("jvm") version "1.6.20"
+ id("com.vanniktech.maven.publish") version "0.19.0"
id("com.github.ben-manes.versions") version "0.42.0"
@@ ... @@
buildscript {
- extra["kotlinVersion"] = "1.6.20"
repositories {
@@ ... @@
dependencies {
- classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
+ classpath(kotlin("gradle-plugin", version = "1.6.20"))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
|
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -3,4 +3,4 @@
CON plugins {
DEL kotlin("jvm").version("1.6.20")
DEL id("com.vanniktech.maven.publish") version ("0.19.0")
ADD kotlin("jvm") version "1.6.20"
ADD id("com.vanniktech.maven.publish") version "0.19.0"
CON id("com.github.ben-manes.versions") version "0.42.0"
@@ -13,3 +13,2 @@
CON buildscript {
DEL extra["kotlinVersion"] = "1.6.20"
CON repositories {
@@ -18,3 +17,3 @@
CON dependencies {
DEL classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
ADD classpath(kotlin("gradle-plugin", version = "1.6.20"))
CON classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
|
<<<<<<< SEARCH
plugins {
kotlin("jvm").version("1.6.20")
id("com.vanniktech.maven.publish") version ("0.19.0")
id("com.github.ben-manes.versions") version "0.42.0"
}
=======
plugins {
kotlin("jvm") version "1.6.20"
id("com.vanniktech.maven.publish") version "0.19.0"
id("com.github.ben-manes.versions") version "0.42.0"
}
>>>>>>> REPLACE
<<<<<<< SEARCH
buildscript {
extra["kotlinVersion"] = "1.6.20"
repositories {
mavenCentral()
}
dependencies {
classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
=======
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath(kotlin("gradle-plugin", version = "1.6.20"))
classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
>>>>>>> REPLACE
|
dubrowgn/tcalc
|
382142f35b35f7a371e2c671b9a1ab26c9d5b81a
|
src/macros.rs
|
rust
|
mit
|
Fix warning 'unused macro definition'
|
macro_rules! unwrap {
($expr:expr, $fail_body:block) => (
match $expr {
::std::option::Option::Some(val) => val,
::std::option::Option::None => $fail_body
}
);
}
macro_rules! is_none {
($expr:expr) => (
match $expr {
::std::option::Option::None => true,
_ => false,
}
);
}
macro_rules! is_some {
($expr:expr) => (
match $expr {
::std::option::Option::None => false,
_ => true,
}
);
}
macro_rules! matches {
($expr:expr, $($pattern:tt)+) => (
match $expr {
$($pattern)+ => true,
_ => false,
}
);
}
#[cfg(feature="trace")]
macro_rules! trace {
($fmt:expr) => (println!($fmt));
($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
}
#[cfg(not(feature="trace"))]
macro_rules! trace {
($fmt:expr) => ();
($fmt:expr, $($arg:tt)*) => ();
}
|
macro_rules! unwrap {
($expr:expr, $fail_body:block) => (
match $expr {
::std::option::Option::Some(val) => val,
::std::option::Option::None => $fail_body
}
);
}
macro_rules! matches {
($expr:expr, $($pattern:tt)+) => (
match $expr {
$($pattern)+ => true,
_ => false,
}
);
}
#[cfg(feature="trace")]
macro_rules! trace {
($fmt:expr) => (println!($fmt));
($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
}
#[cfg(not(feature="trace"))]
macro_rules! trace {
($fmt:expr) => ();
($fmt:expr, $($arg:tt)*) => ();
}
| 0
| 18
| 1
|
del_only
|
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -5,20 +5,2 @@
::std::option::Option::None => $fail_body
- }
- );
-}
-
-macro_rules! is_none {
- ($expr:expr) => (
- match $expr {
- ::std::option::Option::None => true,
- _ => false,
- }
- );
-}
-
-macro_rules! is_some {
- ($expr:expr) => (
- match $expr {
- ::std::option::Option::None => false,
- _ => true,
}
|
--- a/src/macros.rs
+++ b/src/macros.rs
@@ ... @@
::std::option::Option::None => $fail_body
- }
- );
-}
-
-macro_rules! is_none {
- ($expr:expr) => (
- match $expr {
- ::std::option::Option::None => true,
- _ => false,
- }
- );
-}
-
-macro_rules! is_some {
- ($expr:expr) => (
- match $expr {
- ::std::option::Option::None => false,
- _ => true,
}
|
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -5,20 +5,2 @@
CON ::std::option::Option::None => $fail_body
DEL }
DEL );
DEL }
DEL
DEL macro_rules! is_none {
DEL ($expr:expr) => (
DEL match $expr {
DEL ::std::option::Option::None => true,
DEL _ => false,
DEL }
DEL );
DEL }
DEL
DEL macro_rules! is_some {
DEL ($expr:expr) => (
DEL match $expr {
DEL ::std::option::Option::None => false,
DEL _ => true,
CON }
|
<<<<<<< SEARCH
::std::option::Option::Some(val) => val,
::std::option::Option::None => $fail_body
}
);
}
macro_rules! is_none {
($expr:expr) => (
match $expr {
::std::option::Option::None => true,
_ => false,
}
);
}
macro_rules! is_some {
($expr:expr) => (
match $expr {
::std::option::Option::None => false,
_ => true,
}
);
=======
::std::option::Option::Some(val) => val,
::std::option::Option::None => $fail_body
}
);
>>>>>>> REPLACE
|
Cwejman/martina
|
f50d3e7a1bd9c5a0c3d93a50902d29f3816b6d67
|
js/controllers.js
|
javascript
|
mit
|
Add scope variable for current nav tab
|
angular.module('controllers', [])
.controller('NavCtrl', function ($scope) {
})
.controller('HomeCtrl', function ($scope, json) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
var size = function (callback) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
if (arguments.length == 1) callback()
}
$scope.getColumns = function() {
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
size()
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(size(function () {
$scope.$apply()
}), 250)
})
})
|
angular.module('controllers', [])
.controller('NavCtrl', function ($scope, $state) {
$scope.state = $state.current.name
})
.controller('HomeCtrl', function ($scope, json) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
var size = function (callback) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
if (arguments.length == 1) callback()
}
$scope.getColumns = function() {
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
size()
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(size(function () {
$scope.$apply()
}), 250)
})
})
| 3
| 1
| 1
|
mixed
|
--- a/js/controllers.js
+++ b/js/controllers.js
@@ -2,3 +2,5 @@
-.controller('NavCtrl', function ($scope) {
+.controller('NavCtrl', function ($scope, $state) {
+
+ $scope.state = $state.current.name
|
--- a/js/controllers.js
+++ b/js/controllers.js
@@ ... @@
-.controller('NavCtrl', function ($scope) {
+.controller('NavCtrl', function ($scope, $state) {
+
+ $scope.state = $state.current.name
|
--- a/js/controllers.js
+++ b/js/controllers.js
@@ -2,3 +2,5 @@
CON
DEL .controller('NavCtrl', function ($scope) {
ADD .controller('NavCtrl', function ($scope, $state) {
ADD
ADD $scope.state = $state.current.name
CON
|
<<<<<<< SEARCH
angular.module('controllers', [])
.controller('NavCtrl', function ($scope) {
})
=======
angular.module('controllers', [])
.controller('NavCtrl', function ($scope, $state) {
$scope.state = $state.current.name
})
>>>>>>> REPLACE
|
fmichea/bracoujl
|
09b2fe8b248e70300470fcf71f6df0741376c548
|
misc/disassemble_linear.py
|
python
|
bsd-3-clause
|
Fix and enhance disassemble miscellaneous script.
|
import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines):
res = ''
for line in lines:
op = proc.CPU_CONF['parse_line'](line)
if op is None:
continue
res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassemble(op) + '\n'
res += '-' * 30
return res
try:
N = int(sys.argv[1])
except (ValueError, IndexError):
N = -1
uniq, lines, count = set(), [], 0
for line in sys.stdin:
if line == '--\n':
tlines = disassemble(lines)
if tlines not in uniq:
uniq.add(tlines)
print(tlines)
lines = []
if N == count:
sys.exit(0)
count += 1
lines.append(line[:-1])
|
import argparse
import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines, keep_logs=False):
res = []
for line in lines:
op, gline = proc.CPU_CONF['parse_line'](line), ''
if keep_logs:
gline += line + (' | DIS: ' if op is not None else '')
else:
gline += '{:04X}'.format(op['pc']) + ' - '
if op is not None:
gline += dis.disassemble(op)
res.append(gline)
res.append('-' * 20)
return '\n'.join(res)
uniq = set()
def display_lines(lines, **kwds):
tlines = disassemble(lines, **kwds)
if tlines not in uniq:
uniq.add(tlines)
print(tlines)
return []
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Little disassembly helper.')
parser.add_argument('-N', action='store', default=-1,
help='number of uniq blocks displayed')
parser.add_argument('-k', '--keep-logs', action='store_true', default=False,
help='keep log lines')
args = parser.parse_args(sys.argv[1:])
lines, count = [], 0
for line in sys.stdin:
if line == '--\n':
lines = display_lines(lines, keep_logs=args.keep_logs)
if args.N == count:
sys.exit(0)
count += 1
lines.append(line[:-1])
if lines:
display_lines(lines, keep_logs=args.keep_logs)
| 39
| 24
| 2
|
mixed
|
--- a/misc/disassemble_linear.py
+++ b/misc/disassemble_linear.py
@@ -1 +1,2 @@
+import argparse
import sys
@@ -6,28 +7,42 @@
-def disassemble(lines):
- res = ''
+def disassemble(lines, keep_logs=False):
+ res = []
for line in lines:
- op = proc.CPU_CONF['parse_line'](line)
- if op is None:
- continue
- res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassemble(op) + '\n'
- res += '-' * 30
- return res
+ op, gline = proc.CPU_CONF['parse_line'](line), ''
+ if keep_logs:
+ gline += line + (' | DIS: ' if op is not None else '')
+ else:
+ gline += '{:04X}'.format(op['pc']) + ' - '
+ if op is not None:
+ gline += dis.disassemble(op)
+ res.append(gline)
+ res.append('-' * 20)
+ return '\n'.join(res)
-try:
- N = int(sys.argv[1])
-except (ValueError, IndexError):
- N = -1
+uniq = set()
+def display_lines(lines, **kwds):
+ tlines = disassemble(lines, **kwds)
+ if tlines not in uniq:
+ uniq.add(tlines)
+ print(tlines)
+ return []
-uniq, lines, count = set(), [], 0
-for line in sys.stdin:
- if line == '--\n':
- tlines = disassemble(lines)
- if tlines not in uniq:
- uniq.add(tlines)
- print(tlines)
- lines = []
- if N == count:
- sys.exit(0)
- count += 1
- lines.append(line[:-1])
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Little disassembly helper.')
+ parser.add_argument('-N', action='store', default=-1,
+ help='number of uniq blocks displayed')
+ parser.add_argument('-k', '--keep-logs', action='store_true', default=False,
+ help='keep log lines')
+ args = parser.parse_args(sys.argv[1:])
+
+ lines, count = [], 0
+ for line in sys.stdin:
+ if line == '--\n':
+ lines = display_lines(lines, keep_logs=args.keep_logs)
+ if args.N == count:
+ sys.exit(0)
+ count += 1
+ lines.append(line[:-1])
+
+ if lines:
+ display_lines(lines, keep_logs=args.keep_logs)
|
--- a/misc/disassemble_linear.py
+++ b/misc/disassemble_linear.py
@@ ... @@
+import argparse
import sys
@@ ... @@
-def disassemble(lines):
- res = ''
+def disassemble(lines, keep_logs=False):
+ res = []
for line in lines:
- op = proc.CPU_CONF['parse_line'](line)
- if op is None:
- continue
- res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassemble(op) + '\n'
- res += '-' * 30
- return res
+ op, gline = proc.CPU_CONF['parse_line'](line), ''
+ if keep_logs:
+ gline += line + (' | DIS: ' if op is not None else '')
+ else:
+ gline += '{:04X}'.format(op['pc']) + ' - '
+ if op is not None:
+ gline += dis.disassemble(op)
+ res.append(gline)
+ res.append('-' * 20)
+ return '\n'.join(res)
-try:
- N = int(sys.argv[1])
-except (ValueError, IndexError):
- N = -1
+uniq = set()
+def display_lines(lines, **kwds):
+ tlines = disassemble(lines, **kwds)
+ if tlines not in uniq:
+ uniq.add(tlines)
+ print(tlines)
+ return []
-uniq, lines, count = set(), [], 0
-for line in sys.stdin:
- if line == '--\n':
- tlines = disassemble(lines)
- if tlines not in uniq:
- uniq.add(tlines)
- print(tlines)
- lines = []
- if N == count:
- sys.exit(0)
- count += 1
- lines.append(line[:-1])
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Little disassembly helper.')
+ parser.add_argument('-N', action='store', default=-1,
+ help='number of uniq blocks displayed')
+ parser.add_argument('-k', '--keep-logs', action='store_true', default=False,
+ help='keep log lines')
+ args = parser.parse_args(sys.argv[1:])
+
+ lines, count = [], 0
+ for line in sys.stdin:
+ if line == '--\n':
+ lines = display_lines(lines, keep_logs=args.keep_logs)
+ if args.N == count:
+ sys.exit(0)
+ count += 1
+ lines.append(line[:-1])
+
+ if lines:
+ display_lines(lines, keep_logs=args.keep_logs)
|
--- a/misc/disassemble_linear.py
+++ b/misc/disassemble_linear.py
@@ -1 +1,2 @@
ADD import argparse
CON import sys
@@ -6,28 +7,42 @@
CON
DEL def disassemble(lines):
DEL res = ''
ADD def disassemble(lines, keep_logs=False):
ADD res = []
CON for line in lines:
DEL op = proc.CPU_CONF['parse_line'](line)
DEL if op is None:
DEL continue
DEL res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassemble(op) + '\n'
DEL res += '-' * 30
DEL return res
ADD op, gline = proc.CPU_CONF['parse_line'](line), ''
ADD if keep_logs:
ADD gline += line + (' | DIS: ' if op is not None else '')
ADD else:
ADD gline += '{:04X}'.format(op['pc']) + ' - '
ADD if op is not None:
ADD gline += dis.disassemble(op)
ADD res.append(gline)
ADD res.append('-' * 20)
ADD return '\n'.join(res)
CON
DEL try:
DEL N = int(sys.argv[1])
DEL except (ValueError, IndexError):
DEL N = -1
ADD uniq = set()
ADD def display_lines(lines, **kwds):
ADD tlines = disassemble(lines, **kwds)
ADD if tlines not in uniq:
ADD uniq.add(tlines)
ADD print(tlines)
ADD return []
CON
DEL uniq, lines, count = set(), [], 0
DEL for line in sys.stdin:
DEL if line == '--\n':
DEL tlines = disassemble(lines)
DEL if tlines not in uniq:
DEL uniq.add(tlines)
DEL print(tlines)
DEL lines = []
DEL if N == count:
DEL sys.exit(0)
DEL count += 1
DEL lines.append(line[:-1])
ADD if __name__ == '__main__':
ADD parser = argparse.ArgumentParser(description='Little disassembly helper.')
ADD parser.add_argument('-N', action='store', default=-1,
ADD help='number of uniq blocks displayed')
ADD parser.add_argument('-k', '--keep-logs', action='store_true', default=False,
ADD help='keep log lines')
ADD args = parser.parse_args(sys.argv[1:])
ADD
ADD lines, count = [], 0
ADD for line in sys.stdin:
ADD if line == '--\n':
ADD lines = display_lines(lines, keep_logs=args.keep_logs)
ADD if args.N == count:
ADD sys.exit(0)
ADD count += 1
ADD lines.append(line[:-1])
ADD
ADD if lines:
ADD display_lines(lines, keep_logs=args.keep_logs)
|
<<<<<<< SEARCH
import sys
import time
=======
import argparse
import sys
import time
>>>>>>> REPLACE
<<<<<<< SEARCH
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines):
res = ''
for line in lines:
op = proc.CPU_CONF['parse_line'](line)
if op is None:
continue
res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassemble(op) + '\n'
res += '-' * 30
return res
try:
N = int(sys.argv[1])
except (ValueError, IndexError):
N = -1
uniq, lines, count = set(), [], 0
for line in sys.stdin:
if line == '--\n':
tlines = disassemble(lines)
if tlines not in uniq:
uniq.add(tlines)
print(tlines)
lines = []
if N == count:
sys.exit(0)
count += 1
lines.append(line[:-1])
=======
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines, keep_logs=False):
res = []
for line in lines:
op, gline = proc.CPU_CONF['parse_line'](line), ''
if keep_logs:
gline += line + (' | DIS: ' if op is not None else '')
else:
gline += '{:04X}'.format(op['pc']) + ' - '
if op is not None:
gline += dis.disassemble(op)
res.append(gline)
res.append('-' * 20)
return '\n'.join(res)
uniq = set()
def display_lines(lines, **kwds):
tlines = disassemble(lines, **kwds)
if tlines not in uniq:
uniq.add(tlines)
print(tlines)
return []
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Little disassembly helper.')
parser.add_argument('-N', action='store', default=-1,
help='number of uniq blocks displayed')
parser.add_argument('-k', '--keep-logs', action='store_true', default=False,
help='keep log lines')
args = parser.parse_args(sys.argv[1:])
lines, count = [], 0
for line in sys.stdin:
if line == '--\n':
lines = display_lines(lines, keep_logs=args.keep_logs)
if args.N == count:
sys.exit(0)
count += 1
lines.append(line[:-1])
if lines:
display_lines(lines, keep_logs=args.keep_logs)
>>>>>>> REPLACE
|
alexvictoor/pitest-cucumber-plugin
|
8312b23f0ba8ab42a933d34a57d6b698f74e7384
|
src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
|
java
|
apache-2.0
|
Reduce log level to avoid log polution
|
package org.pitest.cucumber;
import org.pitest.junit.CompoundTestUnitFinder;
import org.pitest.junit.JUnitCompatibleConfiguration;
import org.pitest.testapi.TestGroupConfig;
import org.pitest.testapi.TestUnitFinder;
import org.pitest.util.Log;
import java.util.List;
import static java.util.Arrays.asList;
public class CucumberJUnitCompatibleConfiguration extends JUnitCompatibleConfiguration {
public CucumberJUnitCompatibleConfiguration(TestGroupConfig config) {
super(config);
}
@Override
public TestUnitFinder testUnitFinder() {
final TestUnitFinder finder;
if (isCucumberUsed()) {
Log.getLogger().info("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
= asList(new CucumberTestUnitFinder(), super.testUnitFinder());
finder = new CompoundTestUnitFinder(finders);
} else {
Log.getLogger().info("Cucumber not used in this project");
finder = super.testUnitFinder();
}
return finder;
}
private boolean isCucumberUsed() {
boolean result = false;
try {
Class.forName("cucumber.api.junit.Cucumber");
result = true;
} catch (ClassNotFoundException e) {
}
return result;
}
}
|
package org.pitest.cucumber;
import org.pitest.junit.CompoundTestUnitFinder;
import org.pitest.junit.JUnitCompatibleConfiguration;
import org.pitest.testapi.TestGroupConfig;
import org.pitest.testapi.TestUnitFinder;
import org.pitest.util.Log;
import java.util.List;
import static java.util.Arrays.asList;
public class CucumberJUnitCompatibleConfiguration extends JUnitCompatibleConfiguration {
public CucumberJUnitCompatibleConfiguration(TestGroupConfig config) {
super(config);
}
@Override
public TestUnitFinder testUnitFinder() {
final TestUnitFinder finder;
if (isCucumberUsed()) {
Log.getLogger().fine("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
= asList(new CucumberTestUnitFinder(), super.testUnitFinder());
finder = new CompoundTestUnitFinder(finders);
} else {
Log.getLogger().fine("Cucumber not used in this project");
finder = super.testUnitFinder();
}
return finder;
}
private boolean isCucumberUsed() {
boolean result = false;
try {
Class.forName("cucumber.api.junit.Cucumber");
result = true;
} catch (ClassNotFoundException e) {
}
return result;
}
}
| 2
| 2
| 2
|
mixed
|
--- a/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
+++ b/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
@@ -23,3 +23,3 @@
if (isCucumberUsed()) {
- Log.getLogger().info("Cucumber detected, scenarios will be used");
+ Log.getLogger().fine("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
@@ -28,3 +28,3 @@
} else {
- Log.getLogger().info("Cucumber not used in this project");
+ Log.getLogger().fine("Cucumber not used in this project");
finder = super.testUnitFinder();
|
--- a/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
+++ b/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
@@ ... @@
if (isCucumberUsed()) {
- Log.getLogger().info("Cucumber detected, scenarios will be used");
+ Log.getLogger().fine("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
@@ ... @@
} else {
- Log.getLogger().info("Cucumber not used in this project");
+ Log.getLogger().fine("Cucumber not used in this project");
finder = super.testUnitFinder();
|
--- a/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
+++ b/src/main/java/org/pitest/cucumber/CucumberJUnitCompatibleConfiguration.java
@@ -23,3 +23,3 @@
CON if (isCucumberUsed()) {
DEL Log.getLogger().info("Cucumber detected, scenarios will be used");
ADD Log.getLogger().fine("Cucumber detected, scenarios will be used");
CON List<TestUnitFinder> finders
@@ -28,3 +28,3 @@
CON } else {
DEL Log.getLogger().info("Cucumber not used in this project");
ADD Log.getLogger().fine("Cucumber not used in this project");
CON finder = super.testUnitFinder();
|
<<<<<<< SEARCH
final TestUnitFinder finder;
if (isCucumberUsed()) {
Log.getLogger().info("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
= asList(new CucumberTestUnitFinder(), super.testUnitFinder());
finder = new CompoundTestUnitFinder(finders);
} else {
Log.getLogger().info("Cucumber not used in this project");
finder = super.testUnitFinder();
}
=======
final TestUnitFinder finder;
if (isCucumberUsed()) {
Log.getLogger().fine("Cucumber detected, scenarios will be used");
List<TestUnitFinder> finders
= asList(new CucumberTestUnitFinder(), super.testUnitFinder());
finder = new CompoundTestUnitFinder(finders);
} else {
Log.getLogger().fine("Cucumber not used in this project");
finder = super.testUnitFinder();
}
>>>>>>> REPLACE
|
CenterForOpenScience/scrapi
|
f1e1df825b69c33913096af1cb6e20b7d2db72ce
|
scrapi/harvesters/pubmedcentral.py
|
python
|
apache-2.0
|
Add API call to top docstring
|
"""
Harvester of pubmed for the SHARE notification service
"""
from __future__ import unicode_literals
from scrapi.base import schemas
from scrapi.base import helpers
from scrapi.base import OAIHarvester
def oai_extract_url_pubmed(identifiers):
identifiers = [identifiers] if not isinstance(identifiers, list) else identifiers
for item in identifiers:
try:
found_url = helpers.URL_REGEX.search(item).group()
if 'viewcontent' not in found_url and '/pubmed/' in found_url:
return found_url.decode('utf-8')
except AttributeError:
continue
class PubMedHarvester(OAIHarvester):
short_name = 'pubmedcentral'
long_name = 'PubMed Central'
url = 'http://www.ncbi.nlm.nih.gov/pmc/'
schema = helpers.updated_schema(
schemas.OAISCHEMA,
{
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_url_pubmed)
}
}
)
base_url = 'http://www.pubmedcentral.nih.gov/oai/oai.cgi'
property_list = [
'type', 'source', 'publisher', 'rights',
'format', 'setSpec', 'date', 'identifier'
]
|
"""
Harvester of PubMed Central for the SHARE notification service
Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
"""
from __future__ import unicode_literals
from scrapi.base import schemas
from scrapi.base import helpers
from scrapi.base import OAIHarvester
def oai_extract_url_pubmed(identifiers):
identifiers = [identifiers] if not isinstance(identifiers, list) else identifiers
for item in identifiers:
try:
found_url = helpers.URL_REGEX.search(item).group()
if 'viewcontent' not in found_url and '/pubmed/' in found_url:
return found_url.decode('utf-8')
except AttributeError:
continue
class PubMedHarvester(OAIHarvester):
short_name = 'pubmedcentral'
long_name = 'PubMed Central'
url = 'http://www.ncbi.nlm.nih.gov/pmc/'
schema = helpers.updated_schema(
schemas.OAISCHEMA,
{
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_url_pubmed)
}
}
)
base_url = 'http://www.pubmedcentral.nih.gov/oai/oai.cgi'
property_list = [
'type', 'source', 'publisher', 'rights',
'format', 'setSpec', 'date', 'identifier'
]
| 3
| 1
| 1
|
mixed
|
--- a/scrapi/harvesters/pubmedcentral.py
+++ b/scrapi/harvesters/pubmedcentral.py
@@ -1,3 +1,5 @@
"""
-Harvester of pubmed for the SHARE notification service
+Harvester of PubMed Central for the SHARE notification service
+
+Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
"""
|
--- a/scrapi/harvesters/pubmedcentral.py
+++ b/scrapi/harvesters/pubmedcentral.py
@@ ... @@
"""
-Harvester of pubmed for the SHARE notification service
+Harvester of PubMed Central for the SHARE notification service
+
+Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
"""
|
--- a/scrapi/harvesters/pubmedcentral.py
+++ b/scrapi/harvesters/pubmedcentral.py
@@ -1,3 +1,5 @@
CON """
DEL Harvester of pubmed for the SHARE notification service
ADD Harvester of PubMed Central for the SHARE notification service
ADD
ADD Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
CON """
|
<<<<<<< SEARCH
"""
Harvester of pubmed for the SHARE notification service
"""
=======
"""
Harvester of PubMed Central for the SHARE notification service
Example API call: http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=ListRecords&metadataPrefix=oai_dc&from=2015-04-13&until=2015-04-14
"""
>>>>>>> REPLACE
|
oxcable/oxcable
|
6d1c8df21cc42e0264af83af54ccd4720c24316c
|
src/wrappers.rs
|
rust
|
apache-2.0
|
Implement deref for Buffered wrapper
|
//! Tools for wrapping devices.
use types::{AudioDevice, Sample, Time};
/// Bundles an AudioDevice with allocated input and output buffers.
///
/// To use the device, input samples must first be manually dropped into the
/// `inputs` buffer, then `tick` may be called to generate outputs. The output
/// samples can be found in the `outputs` buffer.
pub struct Buffered<D> where D: AudioDevice {
/// The AudioDevice being wrapped
pub device: D,
/// The input buffer
pub inputs: Vec<Sample>,
/// The output buffer
pub outputs: Vec<Sample>,
}
impl<D> Buffered<D> where D: AudioDevice {
/// Calls the device's tick method using the wrapper's buffers.
pub fn tick(&mut self, t: Time) {
self.device.tick(t, &self.inputs, &mut self.outputs);
}
}
impl<D> From<D> for Buffered<D> where D: AudioDevice {
fn from(device: D) -> Self {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
Buffered {
device: device,
inputs: vec![0.0; inputs],
outputs: vec![0.0; outputs],
}
}
}
|
//! Tools for wrapping devices.
use std::ops::{Deref, DerefMut};
use types::{AudioDevice, Sample, Time};
/// Bundles an AudioDevice with allocated input and output buffers.
///
/// To use the device, input samples must first be manually dropped into the
/// `inputs` buffer, then `tick` may be called to generate outputs. The output
/// samples can be found in the `outputs` buffer.
pub struct Buffered<D> where D: AudioDevice {
/// The AudioDevice being wrapped
pub device: D,
/// The input buffer
pub inputs: Vec<Sample>,
/// The output buffer
pub outputs: Vec<Sample>,
}
impl<D> Buffered<D> where D: AudioDevice {
/// Calls the device's tick method using the wrapper's buffers.
pub fn tick(&mut self, t: Time) {
self.device.tick(t, &self.inputs, &mut self.outputs);
}
}
impl<D> From<D> for Buffered<D> where D: AudioDevice {
fn from(device: D) -> Self {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
Buffered {
device: device,
inputs: vec![0.0; inputs],
outputs: vec![0.0; outputs],
}
}
}
impl<D> Deref for Buffered<D> where D: AudioDevice {
type Target = D;
fn deref(&self) -> &D {
&self.device
}
}
impl<D> DerefMut for Buffered<D> where D: AudioDevice {
fn deref_mut(&mut self) -> &mut D {
&mut self.device
}
}
| 14
| 0
| 2
|
add_only
|
--- a/src/wrappers.rs
+++ b/src/wrappers.rs
@@ -1,2 +1,4 @@
//! Tools for wrapping devices.
+
+use std::ops::{Deref, DerefMut};
@@ -37 +39,13 @@
}
+
+impl<D> Deref for Buffered<D> where D: AudioDevice {
+ type Target = D;
+ fn deref(&self) -> &D {
+ &self.device
+ }
+}
+impl<D> DerefMut for Buffered<D> where D: AudioDevice {
+ fn deref_mut(&mut self) -> &mut D {
+ &mut self.device
+ }
+}
|
--- a/src/wrappers.rs
+++ b/src/wrappers.rs
@@ ... @@
//! Tools for wrapping devices.
+
+use std::ops::{Deref, DerefMut};
@@ ... @@
}
+
+impl<D> Deref for Buffered<D> where D: AudioDevice {
+ type Target = D;
+ fn deref(&self) -> &D {
+ &self.device
+ }
+}
+impl<D> DerefMut for Buffered<D> where D: AudioDevice {
+ fn deref_mut(&mut self) -> &mut D {
+ &mut self.device
+ }
+}
|
--- a/src/wrappers.rs
+++ b/src/wrappers.rs
@@ -1,2 +1,4 @@
CON //! Tools for wrapping devices.
ADD
ADD use std::ops::{Deref, DerefMut};
CON
@@ -37 +39,13 @@
CON }
ADD
ADD impl<D> Deref for Buffered<D> where D: AudioDevice {
ADD type Target = D;
ADD fn deref(&self) -> &D {
ADD &self.device
ADD }
ADD }
ADD impl<D> DerefMut for Buffered<D> where D: AudioDevice {
ADD fn deref_mut(&mut self) -> &mut D {
ADD &mut self.device
ADD }
ADD }
|
<<<<<<< SEARCH
//! Tools for wrapping devices.
use types::{AudioDevice, Sample, Time};
=======
//! Tools for wrapping devices.
use std::ops::{Deref, DerefMut};
use types::{AudioDevice, Sample, Time};
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
=======
}
}
impl<D> Deref for Buffered<D> where D: AudioDevice {
type Target = D;
fn deref(&self) -> &D {
&self.device
}
}
impl<D> DerefMut for Buffered<D> where D: AudioDevice {
fn deref_mut(&mut self) -> &mut D {
&mut self.device
}
}
>>>>>>> REPLACE
|
threerings/narya
|
a523e71302f61eacac925b10264b35ac60bbe18c
|
src/java/com/threerings/presents/net/ObjectResponse.java
|
java
|
lgpl-2.1
|
Use the DObjectFactory to move DObjects over the wire.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@7 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
//
// $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $
package com.samskivert.cocktail.cher.net;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import com.samskivert.cocktail.cher.dobj.DObject;
import com.samskivert.cocktail.cher.io.TypedObjectFactory;
public class ObjectResponse extends DownstreamMessage
{
/** The code for an event notification. */
public static final short TYPE = TYPE_BASE + 2;
/**
* Zero argument constructor used when unserializing an instance.
*/
public ObjectResponse ()
{
super();
}
/**
* Constructs an object response with supplied distributed object that
* is associated with the specified upstream message id.
*/
public ObjectResponse (short messageId, DObject dobj)
{
this.messageId = messageId;
_dobj = dobj;
}
public short getType ()
{
return TYPE;
}
public void writeTo (DataOutputStream out)
throws IOException
{
super.writeTo(out);
out.writeShort(messageId);
TypedObjectFactory.writeTo(out, _dobj);
}
public void readFrom (DataInputStream in)
throws IOException
{
super.readFrom(in);
messageId = in.readShort();
_dobj = (DObject)TypedObjectFactory.readFrom(in);
}
/** The object which is associated with this response. */
protected DObject _dobj;
}
|
//
// $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $
package com.samskivert.cocktail.cher.net;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import com.samskivert.cocktail.cher.dobj.DObject;
import com.samskivert.cocktail.cher.dobj.DObjectFactory;
public class ObjectResponse extends DownstreamMessage
{
/** The code for an event notification. */
public static final short TYPE = TYPE_BASE + 2;
/**
* Zero argument constructor used when unserializing an instance.
*/
public ObjectResponse ()
{
super();
}
/**
* Constructs an object response with supplied distributed object that
* is associated with the specified upstream message id.
*/
public ObjectResponse (short messageId, DObject dobj)
{
this.messageId = messageId;
_dobj = dobj;
}
public short getType ()
{
return TYPE;
}
public void writeTo (DataOutputStream out)
throws IOException
{
super.writeTo(out);
out.writeShort(messageId);
DObjectFactory.writeTo(out, _dobj);
}
public void readFrom (DataInputStream in)
throws IOException
{
super.readFrom(in);
messageId = in.readShort();
_dobj = (DObject)DObjectFactory.readFrom(in);
}
/** The object which is associated with this response. */
protected DObject _dobj;
}
| 4
| 4
| 4
|
mixed
|
--- a/src/java/com/threerings/presents/net/ObjectResponse.java
+++ b/src/java/com/threerings/presents/net/ObjectResponse.java
@@ -1,3 +1,3 @@
//
-// $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $
+// $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $
@@ -10,3 +10,3 @@
import com.samskivert.cocktail.cher.dobj.DObject;
-import com.samskivert.cocktail.cher.io.TypedObjectFactory;
+import com.samskivert.cocktail.cher.dobj.DObjectFactory;
@@ -45,3 +45,3 @@
out.writeShort(messageId);
- TypedObjectFactory.writeTo(out, _dobj);
+ DObjectFactory.writeTo(out, _dobj);
}
@@ -53,3 +53,3 @@
messageId = in.readShort();
- _dobj = (DObject)TypedObjectFactory.readFrom(in);
+ _dobj = (DObject)DObjectFactory.readFrom(in);
}
|
--- a/src/java/com/threerings/presents/net/ObjectResponse.java
+++ b/src/java/com/threerings/presents/net/ObjectResponse.java
@@ ... @@
//
-// $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $
+// $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $
@@ ... @@
import com.samskivert.cocktail.cher.dobj.DObject;
-import com.samskivert.cocktail.cher.io.TypedObjectFactory;
+import com.samskivert.cocktail.cher.dobj.DObjectFactory;
@@ ... @@
out.writeShort(messageId);
- TypedObjectFactory.writeTo(out, _dobj);
+ DObjectFactory.writeTo(out, _dobj);
}
@@ ... @@
messageId = in.readShort();
- _dobj = (DObject)TypedObjectFactory.readFrom(in);
+ _dobj = (DObject)DObjectFactory.readFrom(in);
}
|
--- a/src/java/com/threerings/presents/net/ObjectResponse.java
+++ b/src/java/com/threerings/presents/net/ObjectResponse.java
@@ -1,3 +1,3 @@
CON //
DEL // $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $
ADD // $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $
CON
@@ -10,3 +10,3 @@
CON import com.samskivert.cocktail.cher.dobj.DObject;
DEL import com.samskivert.cocktail.cher.io.TypedObjectFactory;
ADD import com.samskivert.cocktail.cher.dobj.DObjectFactory;
CON
@@ -45,3 +45,3 @@
CON out.writeShort(messageId);
DEL TypedObjectFactory.writeTo(out, _dobj);
ADD DObjectFactory.writeTo(out, _dobj);
CON }
@@ -53,3 +53,3 @@
CON messageId = in.readShort();
DEL _dobj = (DObject)TypedObjectFactory.readFrom(in);
ADD _dobj = (DObject)DObjectFactory.readFrom(in);
CON }
|
<<<<<<< SEARCH
//
// $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $
package com.samskivert.cocktail.cher.net;
=======
//
// $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $
package com.samskivert.cocktail.cher.net;
>>>>>>> REPLACE
<<<<<<< SEARCH
import com.samskivert.cocktail.cher.dobj.DObject;
import com.samskivert.cocktail.cher.io.TypedObjectFactory;
public class ObjectResponse extends DownstreamMessage
=======
import com.samskivert.cocktail.cher.dobj.DObject;
import com.samskivert.cocktail.cher.dobj.DObjectFactory;
public class ObjectResponse extends DownstreamMessage
>>>>>>> REPLACE
<<<<<<< SEARCH
super.writeTo(out);
out.writeShort(messageId);
TypedObjectFactory.writeTo(out, _dobj);
}
=======
super.writeTo(out);
out.writeShort(messageId);
DObjectFactory.writeTo(out, _dobj);
}
>>>>>>> REPLACE
<<<<<<< SEARCH
super.readFrom(in);
messageId = in.readShort();
_dobj = (DObject)TypedObjectFactory.readFrom(in);
}
=======
super.readFrom(in);
messageId = in.readShort();
_dobj = (DObject)DObjectFactory.readFrom(in);
}
>>>>>>> REPLACE
|
BreakOutEvent/breakout-backend
|
2ed4f3281764476a7a4ddeb44059b563ba19655b
|
src/main/java/backend/controller/EventController.kt
|
kotlin
|
agpl-3.0
|
Validate Body of API Request for creating events
|
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
|
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@Valid @RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
| 2
| 1
| 2
|
mixed
|
--- a/src/main/java/backend/controller/EventController.kt
+++ b/src/main/java/backend/controller/EventController.kt
@@ -11,2 +11,3 @@
import java.time.ZoneOffset
+import javax.validation.Valid
import kotlin.collections.map
@@ -29,3 +30,3 @@
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
- fun createEvent(@RequestBody body: EventView): EventView {
+ fun createEvent(@Valid @RequestBody body: EventView): EventView {
|
--- a/src/main/java/backend/controller/EventController.kt
+++ b/src/main/java/backend/controller/EventController.kt
@@ ... @@
import java.time.ZoneOffset
+import javax.validation.Valid
import kotlin.collections.map
@@ ... @@
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
- fun createEvent(@RequestBody body: EventView): EventView {
+ fun createEvent(@Valid @RequestBody body: EventView): EventView {
|
--- a/src/main/java/backend/controller/EventController.kt
+++ b/src/main/java/backend/controller/EventController.kt
@@ -11,2 +11,3 @@
CON import java.time.ZoneOffset
ADD import javax.validation.Valid
CON import kotlin.collections.map
@@ -29,3 +30,3 @@
CON produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
DEL fun createEvent(@RequestBody body: EventView): EventView {
ADD fun createEvent(@Valid @RequestBody body: EventView): EventView {
CON
|
<<<<<<< SEARCH
import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.collections.map
=======
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map
>>>>>>> REPLACE
<<<<<<< SEARCH
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@RequestBody body: EventView): EventView {
val event = eventService.createEvent(
=======
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@Valid @RequestBody body: EventView): EventView {
val event = eventService.createEvent(
>>>>>>> REPLACE
|
kevva/osx-wifi-password
|
eb418dc505db2107e011f28063d08d82448f3f97
|
index.js
|
javascript
|
mit
|
Use `-w` flag to display password directly
Fixes #2.
|
'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
var ret;
execFile(cmd, args, function (err, stdout, stderr) {
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
}
if (err) {
cb(err);
return;
}
ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
ret = ret && ret.length ? ret[1] : null;
if (!ret) {
cb(new Error('Could not get password'));
return;
}
cb(null, ret);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'darwin') {
throw new Error('Only OS X systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
|
'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
execFile(cmd, args, function (err, stdout) {
stdout = stdout.trim();
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
}
if (err) {
cb(err);
return;
}
if (!stdout) {
cb(new Error('Could not get password'));
return;
}
cb(null, stdout);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'darwin') {
throw new Error('Only OS X systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
| 6
| 8
| 3
|
mixed
|
--- a/index.js
+++ b/index.js
@@ -6,6 +6,7 @@
var cmd = 'security';
- var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
- var ret;
+ var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
- execFile(cmd, args, function (err, stdout, stderr) {
+ execFile(cmd, args, function (err, stdout) {
+ stdout = stdout.trim();
+
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
@@ -19,6 +20,3 @@
- ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
- ret = ret && ret.length ? ret[1] : null;
-
- if (!ret) {
+ if (!stdout) {
cb(new Error('Could not get password'));
@@ -27,3 +25,3 @@
- cb(null, ret);
+ cb(null, stdout);
});
|
--- a/index.js
+++ b/index.js
@@ ... @@
var cmd = 'security';
- var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
- var ret;
+ var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
- execFile(cmd, args, function (err, stdout, stderr) {
+ execFile(cmd, args, function (err, stdout) {
+ stdout = stdout.trim();
+
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
@@ ... @@
- ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
- ret = ret && ret.length ? ret[1] : null;
-
- if (!ret) {
+ if (!stdout) {
cb(new Error('Could not get password'));
@@ ... @@
- cb(null, ret);
+ cb(null, stdout);
});
|
--- a/index.js
+++ b/index.js
@@ -6,6 +6,7 @@
CON var cmd = 'security';
DEL var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
DEL var ret;
ADD var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
CON
DEL execFile(cmd, args, function (err, stdout, stderr) {
ADD execFile(cmd, args, function (err, stdout) {
ADD stdout = stdout.trim();
ADD
CON if (err && /The specified item could not be found in the keychain/.test(err.message)) {
@@ -19,6 +20,3 @@
CON
DEL ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
DEL ret = ret && ret.length ? ret[1] : null;
DEL
DEL if (!ret) {
ADD if (!stdout) {
CON cb(new Error('Could not get password'));
@@ -27,3 +25,3 @@
CON
DEL cb(null, ret);
ADD cb(null, stdout);
CON });
|
<<<<<<< SEARCH
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
var ret;
execFile(cmd, args, function (err, stdout, stderr) {
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
=======
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
execFile(cmd, args, function (err, stdout) {
stdout = stdout.trim();
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
>>>>>>> REPLACE
<<<<<<< SEARCH
}
ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
ret = ret && ret.length ? ret[1] : null;
if (!ret) {
cb(new Error('Could not get password'));
return;
}
cb(null, ret);
});
}
=======
}
if (!stdout) {
cb(new Error('Could not get password'));
return;
}
cb(null, stdout);
});
}
>>>>>>> REPLACE
|
anthonyvia/bowlscore-node
|
4f5628b63bf63a4c66c4b738bed42cb510739fae
|
app.js
|
javascript
|
mit
|
Remove error handlers for now.
|
require('node-jsx').install({extension:'.jsx'});
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bowlScoreApi = require('./lib/server/api');
var config = require('./lib/config');
var app = express();
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
// logs each request, response code, and response time
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', bowlScoreApi);
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
require('node-jsx').install({extension:'.jsx'});
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bowlScoreApi = require('./lib/server/api');
var config = require('./lib/config');
var app = express();
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
// logs each request, response code, and response time
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', bowlScoreApi);
module.exports = app;
| 0
| 24
| 1
|
del_only
|
--- a/app.js
+++ b/app.js
@@ -26,26 +26,2 @@
-// error handlers
-
-// development error handler
-// will print stacktrace
-if (app.get('env') === 'development') {
- app.use(function(err, req, res, next) {
- res.status(err.status || 500);
- res.render('error', {
- message: err.message,
- error: err
- });
- });
-}
-
-// production error handler
-// no stacktraces leaked to user
-app.use(function(err, req, res, next) {
- res.status(err.status || 500);
- res.render('error', {
- message: err.message,
- error: {}
- });
-});
-
module.exports = app;
|
--- a/app.js
+++ b/app.js
@@ ... @@
-// error handlers
-
-// development error handler
-// will print stacktrace
-if (app.get('env') === 'development') {
- app.use(function(err, req, res, next) {
- res.status(err.status || 500);
- res.render('error', {
- message: err.message,
- error: err
- });
- });
-}
-
-// production error handler
-// no stacktraces leaked to user
-app.use(function(err, req, res, next) {
- res.status(err.status || 500);
- res.render('error', {
- message: err.message,
- error: {}
- });
-});
-
module.exports = app;
|
--- a/app.js
+++ b/app.js
@@ -26,26 +26,2 @@
CON
DEL // error handlers
DEL
DEL // development error handler
DEL // will print stacktrace
DEL if (app.get('env') === 'development') {
DEL app.use(function(err, req, res, next) {
DEL res.status(err.status || 500);
DEL res.render('error', {
DEL message: err.message,
DEL error: err
DEL });
DEL });
DEL }
DEL
DEL // production error handler
DEL // no stacktraces leaked to user
DEL app.use(function(err, req, res, next) {
DEL res.status(err.status || 500);
DEL res.render('error', {
DEL message: err.message,
DEL error: {}
DEL });
DEL });
DEL
CON module.exports = app;
|
<<<<<<< SEARCH
app.use('/api', bowlScoreApi);
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
=======
app.use('/api', bowlScoreApi);
module.exports = app;
>>>>>>> REPLACE
|
albburtsev/talaria
|
6a46b1f1340a233a7b8ed0b748496478dabb07b9
|
src/helpers.js
|
javascript
|
mit
|
Correct implementation of joinParams() helper
|
export default {
/**
* Naive polyfill for Object.assign()
* Why I did it? Because even modular lodash adds too much code in final build
* @param {Object} target
* @return {Object}
*/
assign(target) {
for (let i = 1; i < arguments.length; i++) {
let obj = Object(arguments[i]),
keys = Object.keys(obj);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (!obj.hasOwnProperty(key)) {
continue;
}
target[key] = obj[key];
}
}
return target;
},
/**
* Returns URL with query string
* @param {String} url
* @param {Object} params
* @return {String}
*/
joinParams(url, params = null) {
if (!params) {
return url;
}
let queryString = Object.keys(params).reduce((query, key) => {
let value = params[key];
if (value) {
value = value.toString();
value = encodeURIComponent(value);
key = encodeURIComponent(key);
query.push(`${key}=${value}`);
}
return query;
}, []).join('&');
if (!queryString) {
return url;
}
// Trim trailing "?"
url = url.replace(/\?+$/, '');
return url +
(url.indexOf('?') === -1 ? '?' : '&') +
queryString;
}
};
|
export default {
/**
* Naive polyfill for Object.assign()
* Why I did it? Because even modular lodash adds too much code in final build
* @param {Object} target
* @return {Object}
*/
assign(target) {
for (let i = 1; i < arguments.length; i++) {
let obj = Object(arguments[i]),
keys = Object.keys(obj);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (!obj.hasOwnProperty(key)) {
continue;
}
target[key] = obj[key];
}
}
return target;
},
/**
* Returns URL with query string
* @param {String} url
* @param {Object} params
* @return {String}
*/
joinParams(url, params = null) {
if (!params) {
return url;
}
let queryString = Object.keys(params)
.filter((key) => key && params[key])
.map((key) => {
let value = params[key].toString();
key = encodeURIComponent(key);
value = encodeURIComponent(value);
return `${key}=${value}`;
})
.join('&');
if (!queryString) {
return url;
}
// Trim trailing "?"
url = url.replace(/\?+$/, '');
return url +
(url.indexOf('?') === -1 ? '?' : '&') +
queryString;
}
};
| 8
| 9
| 1
|
mixed
|
--- a/src/helpers.js
+++ b/src/helpers.js
@@ -37,14 +37,13 @@
- let queryString = Object.keys(params).reduce((query, key) => {
- let value = params[key];
+ let queryString = Object.keys(params)
+ .filter((key) => key && params[key])
+ .map((key) => {
+ let value = params[key].toString();
- if (value) {
- value = value.toString();
+ key = encodeURIComponent(key);
value = encodeURIComponent(value);
- key = encodeURIComponent(key);
- query.push(`${key}=${value}`);
- }
- return query;
- }, []).join('&');
+ return `${key}=${value}`;
+ })
+ .join('&');
|
--- a/src/helpers.js
+++ b/src/helpers.js
@@ ... @@
- let queryString = Object.keys(params).reduce((query, key) => {
- let value = params[key];
+ let queryString = Object.keys(params)
+ .filter((key) => key && params[key])
+ .map((key) => {
+ let value = params[key].toString();
- if (value) {
- value = value.toString();
+ key = encodeURIComponent(key);
value = encodeURIComponent(value);
- key = encodeURIComponent(key);
- query.push(`${key}=${value}`);
- }
- return query;
- }, []).join('&');
+ return `${key}=${value}`;
+ })
+ .join('&');
|
--- a/src/helpers.js
+++ b/src/helpers.js
@@ -37,14 +37,13 @@
CON
DEL let queryString = Object.keys(params).reduce((query, key) => {
DEL let value = params[key];
ADD let queryString = Object.keys(params)
ADD .filter((key) => key && params[key])
ADD .map((key) => {
ADD let value = params[key].toString();
CON
DEL if (value) {
DEL value = value.toString();
ADD key = encodeURIComponent(key);
CON value = encodeURIComponent(value);
DEL key = encodeURIComponent(key);
DEL query.push(`${key}=${value}`);
DEL }
CON
DEL return query;
DEL }, []).join('&');
ADD return `${key}=${value}`;
ADD })
ADD .join('&');
CON
|
<<<<<<< SEARCH
}
let queryString = Object.keys(params).reduce((query, key) => {
let value = params[key];
if (value) {
value = value.toString();
value = encodeURIComponent(value);
key = encodeURIComponent(key);
query.push(`${key}=${value}`);
}
return query;
}, []).join('&');
if (!queryString) {
=======
}
let queryString = Object.keys(params)
.filter((key) => key && params[key])
.map((key) => {
let value = params[key].toString();
key = encodeURIComponent(key);
value = encodeURIComponent(value);
return `${key}=${value}`;
})
.join('&');
if (!queryString) {
>>>>>>> REPLACE
|
mbogoevici/spring-cloud-connectors
|
c48f5570a8727827654f2aa951f3c217ce1f2308
|
spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
|
java
|
apache-2.0
|
Choose sensible values for pool config by default
|
package org.springframework.cloud.service.relational;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
/**
* Common implementation that assumes DBCP connection pool properties.
*
* @author Ramnivas Laddad
*
* @param <SI>
*/
public abstract class DbcpLikePooledDataSourceCreator<SI extends RelationalServiceInfo> implements PooledDataSourceCreator<SI> {
protected static Logger logger = Logger.getLogger(PooledDataSourceCreator.class.getName());
private DataSourceConfigurer configurer = new DataSourceConfigurer();
protected void setBasicDataSourceProperties(DataSource basicDataSource, RelationalServiceInfo serviceInfo,
ServiceConnectorConfig serviceConnectorConfig,
String driverClassName, String validationQuery) {
BeanWrapper target = new BeanWrapperImpl(basicDataSource);
target.setPropertyValue("driverClassName", driverClassName);
target.setPropertyValue("url", serviceInfo.getJdbcUrl());
if (validationQuery != null) {
target.setPropertyValue("validationQuery", validationQuery);
target.setPropertyValue("testOnBorrow", true);
}
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
}
}
|
package org.springframework.cloud.service.relational;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
/**
* Common implementation that assumes DBCP connection pool properties.
*
* @author Ramnivas Laddad
*
* @param <SI>
*/
public abstract class DbcpLikePooledDataSourceCreator<SI extends RelationalServiceInfo> implements PooledDataSourceCreator<SI> {
protected static Logger logger = Logger.getLogger(PooledDataSourceCreator.class.getName());
private DataSourceConfigurer configurer = new DataSourceConfigurer();
protected void setBasicDataSourceProperties(DataSource basicDataSource, RelationalServiceInfo serviceInfo,
ServiceConnectorConfig serviceConnectorConfig,
String driverClassName, String validationQuery) {
BeanWrapper target = new BeanWrapperImpl(basicDataSource);
target.setPropertyValue("driverClassName", driverClassName);
target.setPropertyValue("url", serviceInfo.getJdbcUrl());
if (validationQuery != null) {
target.setPropertyValue("validationQuery", validationQuery);
target.setPropertyValue("testOnBorrow", true);
}
if (serviceConnectorConfig == null) {
// choose sensible values so that we set max connection pool size to what
// free tier services on Cloud Foundry and Heroku allow
serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
}
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
}
}
| 7
| 0
| 2
|
add_only
|
--- a/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
+++ b/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
@@ -8,2 +8,3 @@
import org.springframework.beans.BeanWrapperImpl;
+import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
import org.springframework.cloud.service.ServiceConnectorConfig;
@@ -34,2 +35,8 @@
}
+
+ if (serviceConnectorConfig == null) {
+ // choose sensible values so that we set max connection pool size to what
+ // free tier services on Cloud Foundry and Heroku allow
+ serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
+ }
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
|
--- a/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
+++ b/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
@@ ... @@
import org.springframework.beans.BeanWrapperImpl;
+import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
import org.springframework.cloud.service.ServiceConnectorConfig;
@@ ... @@
}
+
+ if (serviceConnectorConfig == null) {
+ // choose sensible values so that we set max connection pool size to what
+ // free tier services on Cloud Foundry and Heroku allow
+ serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
+ }
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
|
--- a/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
+++ b/spring-cloud-spring-service-connector/src/main/java/org/springframework/cloud/service/relational/DbcpLikePooledDataSourceCreator.java
@@ -8,2 +8,3 @@
CON import org.springframework.beans.BeanWrapperImpl;
ADD import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
CON import org.springframework.cloud.service.ServiceConnectorConfig;
@@ -34,2 +35,8 @@
CON }
ADD
ADD if (serviceConnectorConfig == null) {
ADD // choose sensible values so that we set max connection pool size to what
ADD // free tier services on Cloud Foundry and Heroku allow
ADD serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
ADD }
CON configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
|
<<<<<<< SEARCH
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
=======
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;
>>>>>>> REPLACE
<<<<<<< SEARCH
target.setPropertyValue("testOnBorrow", true);
}
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
}
=======
target.setPropertyValue("testOnBorrow", true);
}
if (serviceConnectorConfig == null) {
// choose sensible values so that we set max connection pool size to what
// free tier services on Cloud Foundry and Heroku allow
serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
}
configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
}
>>>>>>> REPLACE
|
ternaris/marv-robotics
|
c1d889f637d6d2a931f81332a9eef3974dfa18e0
|
code/marv/marv/__init__.py
|
python
|
agpl-3.0
|
Drop unused support to add decorators via entry points
|
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
import sys
from pkg_resources import iter_entry_points
from marv_node.io import Abort
from marv_node.io import create_group
from marv_node.io import create_stream
from marv_node.io import fork
from marv_node.io import get_logger
from marv_node.io import get_requested
from marv_node.io import get_stream
from marv_node.io import make_file
from marv_node.io import pull
from marv_node.io import pull_all
from marv_node.io import push
from marv_node.io import set_header
from marv_node.node import input, node
from marv_node.tools import select
from marv_webapi.tooling import api_endpoint
from marv_webapi.tooling import api_group
__all__ = [
'Abort',
'api_endpoint',
'api_group',
'create_group',
'create_stream',
'fork',
'get_logger',
'get_requested',
'get_stream',
'input',
'make_file',
'node',
'pull',
'pull_all',
'push',
'select',
'set_header',
]
MODULE = sys.modules[__name__]
for ep in iter_entry_points(group='marv_deco'):
assert not hasattr(MODULE, ep.name)
setattr(MODULE, ep.name, ep.load())
del MODULE
|
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from marv_node.io import Abort
from marv_node.io import create_group
from marv_node.io import create_stream
from marv_node.io import fork
from marv_node.io import get_logger
from marv_node.io import get_requested
from marv_node.io import get_stream
from marv_node.io import make_file
from marv_node.io import pull
from marv_node.io import pull_all
from marv_node.io import push
from marv_node.io import set_header
from marv_node.node import input, node
from marv_node.tools import select
from marv_webapi.tooling import api_endpoint
from marv_webapi.tooling import api_group
__all__ = [
'Abort',
'api_endpoint',
'api_group',
'create_group',
'create_stream',
'fork',
'get_logger',
'get_requested',
'get_stream',
'input',
'make_file',
'node',
'pull',
'pull_all',
'push',
'select',
'set_header',
]
| 0
| 10
| 2
|
del_only
|
--- a/code/marv/marv/__init__.py
+++ b/code/marv/marv/__init__.py
@@ -2,6 +2,2 @@
# SPDX-License-Identifier: AGPL-3.0-only
-
-import sys
-
-from pkg_resources import iter_entry_points
@@ -43,7 +39 @@
]
-
-MODULE = sys.modules[__name__]
-for ep in iter_entry_points(group='marv_deco'):
- assert not hasattr(MODULE, ep.name)
- setattr(MODULE, ep.name, ep.load())
-del MODULE
|
--- a/code/marv/marv/__init__.py
+++ b/code/marv/marv/__init__.py
@@ ... @@
# SPDX-License-Identifier: AGPL-3.0-only
-
-import sys
-
-from pkg_resources import iter_entry_points
@@ ... @@
]
-
-MODULE = sys.modules[__name__]
-for ep in iter_entry_points(group='marv_deco'):
- assert not hasattr(MODULE, ep.name)
- setattr(MODULE, ep.name, ep.load())
-del MODULE
|
--- a/code/marv/marv/__init__.py
+++ b/code/marv/marv/__init__.py
@@ -2,6 +2,2 @@
CON # SPDX-License-Identifier: AGPL-3.0-only
DEL
DEL import sys
DEL
DEL from pkg_resources import iter_entry_points
CON
@@ -43,7 +39 @@
CON ]
DEL
DEL MODULE = sys.modules[__name__]
DEL for ep in iter_entry_points(group='marv_deco'):
DEL assert not hasattr(MODULE, ep.name)
DEL setattr(MODULE, ep.name, ep.load())
DEL del MODULE
|
<<<<<<< SEARCH
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
import sys
from pkg_resources import iter_entry_points
from marv_node.io import Abort
=======
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from marv_node.io import Abort
>>>>>>> REPLACE
<<<<<<< SEARCH
'set_header',
]
MODULE = sys.modules[__name__]
for ep in iter_entry_points(group='marv_deco'):
assert not hasattr(MODULE, ep.name)
setattr(MODULE, ep.name, ep.load())
del MODULE
=======
'set_header',
]
>>>>>>> REPLACE
|
ranweiler/lfsr-rs
|
76dc41fea07a91d67ab264d0ae56c04e930b1055
|
src/lfsr.rs
|
rust
|
bsd-2-clause
|
Add first pass at LFSR trait
|
use bit_vec::BitVec;
pub fn shift(state: &mut BitVec) {
let range = 1 .. state.len();
for i in range.rev() {
let pred = state[i - 1];
state.set(i, pred);
};
state.set(0, false);
}
#[cfg(test)]
mod test {
use bit_vec::BitVec;
use super::shift;
#[test]
fn shift_works() {
let ref mut bv = BitVec::from_elem(4, true);
shift(bv);
assert!(bv.eq_vec(&[false, true, true, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, true, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, false]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, false]));
}
}
|
use bit_vec::BitVec;
pub trait LFSR {
fn output(&self) -> bool;
fn step(&mut self);
}
pub fn shift(state: &mut BitVec) {
let range = 1 .. state.len();
for i in range.rev() {
let pred = state[i - 1];
state.set(i, pred);
};
state.set(0, false);
}
#[cfg(test)]
mod test {
use bit_vec::BitVec;
use super::shift;
#[test]
fn shift_works() {
let ref mut bv = BitVec::from_elem(4, true);
shift(bv);
assert!(bv.eq_vec(&[false, true, true, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, true, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, true]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, false]));
shift(bv);
assert!(bv.eq_vec(&[false, false, false, false]));
}
}
| 5
| 0
| 1
|
add_only
|
--- a/src/lfsr.rs
+++ b/src/lfsr.rs
@@ -1,2 +1,7 @@
use bit_vec::BitVec;
+
+pub trait LFSR {
+ fn output(&self) -> bool;
+ fn step(&mut self);
+}
|
--- a/src/lfsr.rs
+++ b/src/lfsr.rs
@@ ... @@
use bit_vec::BitVec;
+
+pub trait LFSR {
+ fn output(&self) -> bool;
+ fn step(&mut self);
+}
|
--- a/src/lfsr.rs
+++ b/src/lfsr.rs
@@ -1,2 +1,7 @@
CON use bit_vec::BitVec;
ADD
ADD pub trait LFSR {
ADD fn output(&self) -> bool;
ADD fn step(&mut self);
ADD }
CON
|
<<<<<<< SEARCH
use bit_vec::BitVec;
pub fn shift(state: &mut BitVec) {
=======
use bit_vec::BitVec;
pub trait LFSR {
fn output(&self) -> bool;
fn step(&mut self);
}
pub fn shift(state: &mut BitVec) {
>>>>>>> REPLACE
|
e-loue/django-oauth-plus
|
0a1358f27db3abb04032fac1b8a3da09d846d23e
|
oauth_provider/utils.py
|
python
|
bsd-3-clause
|
Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch
|
import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=request.META,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = oauth.OAuthServer(DataStore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
def send_oauth_error(err=None):
"""Shortcut for sending an error."""
# send a 401 error
response = HttpResponse(err.message.encode('utf-8'), mimetype="text/plain")
response.status_code = 401
# return the authenticate header
realm = getattr(settings, OAUTH_REALM_KEY_NAME, '')
header = oauth.build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
|
import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': request.META['Authorization']}
elif 'HTTP_AUTHORIZATION' in request.META:
auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=auth_header,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = oauth.OAuthServer(DataStore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
def send_oauth_error(err=None):
"""Shortcut for sending an error."""
# send a 401 error
response = HttpResponse(err.message.encode('utf-8'), mimetype="text/plain")
response.status_code = 401
# return the authenticate header
realm = getattr(settings, OAUTH_REALM_KEY_NAME, '')
header = oauth.build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
| 9
| 1
| 1
|
mixed
|
--- a/oauth_provider/utils.py
+++ b/oauth_provider/utils.py
@@ -11,5 +11,13 @@
"""Shortcut for initialization."""
+ # Django converts Authorization header in HTTP_AUTHORIZATION
+ # Warning: it doesn't happen in tests but it's useful, do not remove!
+ auth_header = {}
+ if 'Authorization' in request.META:
+ auth_header = {'Authorization': request.META['Authorization']}
+ elif 'HTTP_AUTHORIZATION' in request.META:
+ auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
+
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
- headers=request.META,
+ headers=auth_header,
parameters=dict(request.REQUEST.items()),
|
--- a/oauth_provider/utils.py
+++ b/oauth_provider/utils.py
@@ ... @@
"""Shortcut for initialization."""
+ # Django converts Authorization header in HTTP_AUTHORIZATION
+ # Warning: it doesn't happen in tests but it's useful, do not remove!
+ auth_header = {}
+ if 'Authorization' in request.META:
+ auth_header = {'Authorization': request.META['Authorization']}
+ elif 'HTTP_AUTHORIZATION' in request.META:
+ auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
+
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
- headers=request.META,
+ headers=auth_header,
parameters=dict(request.REQUEST.items()),
|
--- a/oauth_provider/utils.py
+++ b/oauth_provider/utils.py
@@ -11,5 +11,13 @@
CON """Shortcut for initialization."""
ADD # Django converts Authorization header in HTTP_AUTHORIZATION
ADD # Warning: it doesn't happen in tests but it's useful, do not remove!
ADD auth_header = {}
ADD if 'Authorization' in request.META:
ADD auth_header = {'Authorization': request.META['Authorization']}
ADD elif 'HTTP_AUTHORIZATION' in request.META:
ADD auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
ADD
CON oauth_request = oauth.OAuthRequest.from_request(request.method,
CON request.build_absolute_uri(),
DEL headers=request.META,
ADD headers=auth_header,
CON parameters=dict(request.REQUEST.items()),
|
<<<<<<< SEARCH
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=request.META,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
=======
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': request.META['Authorization']}
elif 'HTTP_AUTHORIZATION' in request.META:
auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=auth_header,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
>>>>>>> REPLACE
|
Hoverbear/rust-rosetta
|
cc557e16c3acb3c37b50abd93622221ca537d22d
|
tasks/animation/src/main.rs
|
rust
|
unlicense
|
Refactor to make the task look like the other gtk related tasks
|
extern crate gtk;
use gtk::prelude::*;
use std::ops::Not;
use std::sync::{Arc, RwLock};
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
|
#[cfg(feature = "gtk")]
mod graphical {
extern crate gtk;
use self::gtk::traits::*;
use self::gtk::{Inhibit, Window, WindowType};
use std::ops::Not;
use std::sync::{Arc, RwLock};
pub fn create_window() {
gtk::init().expect("Failed to initialize GTK");
let window = Window::new(WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
}
#[cfg(feature = "gtk")]
fn main() {
graphical::create_window();
}
#[cfg(not(feature = "gtk"))]
fn main() {}
| 55
| 50
| 1
|
mixed
|
--- a/tasks/animation/src/main.rs
+++ b/tasks/animation/src/main.rs
@@ -1,55 +1,60 @@
-extern crate gtk;
+#[cfg(feature = "gtk")]
+mod graphical {
+ extern crate gtk;
-use gtk::prelude::*;
-use std::ops::Not;
-use std::sync::{Arc, RwLock};
+ use self::gtk::traits::*;
+ use self::gtk::{Inhibit, Window, WindowType};
+ use std::ops::Not;
+ use std::sync::{Arc, RwLock};
+
+ pub fn create_window() {
+ gtk::init().expect("Failed to initialize GTK");
+
+ let window = Window::new(WindowType::Toplevel);
+ window.connect_delete_event(|_, _| {
+ gtk::main_quit();
+ Inhibit(false)
+ });
+ let button = gtk::Button::new_with_label("Hello World! ");
+ window.add(&button);
+
+ let lock = Arc::new(RwLock::new(false));
+
+ let lock_button = lock.clone();
+ button.connect_clicked(move |_| {
+ let mut reverse = lock_button.write().unwrap();
+ *reverse = reverse.not();
+ });
+
+ let lock_thread = lock.clone();
+ gtk::timeout_add(100, move || {
+ let reverse = lock_thread.read().unwrap();
+ let mut text = button.get_label().unwrap();
+ let len = &text.len();
+
+ if *reverse {
+ let begin = &text.split_off(1);
+ text.insert_str(0, begin);
+ } else {
+ let end = &text.split_off(len - 1);
+ text.insert_str(0, end);
+ }
+
+ button.set_label(&text);
+
+ gtk::Continue(true)
+ });
+
+ window.show_all();
+ gtk::main();
+ }
+}
+#[cfg(feature = "gtk")]
fn main() {
- if gtk::init().is_err() {
- println!("Failed to initialize GTK.");
- return;
- }
+ graphical::create_window();
+}
- let window = gtk::Window::new(gtk::WindowType::Toplevel);
-
- window.connect_delete_event(|_, _| {
- gtk::main_quit();
- Inhibit(false)
- });
-
- let button = gtk::Button::new_with_label("Hello World! ");
-
- window.add(&button);
-
- let lock = Arc::new(RwLock::new(false));
-
- let lock_button = lock.clone();
- button.connect_clicked(move |_| {
- let mut reverse = lock_button.write().unwrap();
- *reverse = reverse.not();
- });
-
- let lock_thread = lock.clone();
- gtk::timeout_add(100, move || {
- let reverse = lock_thread.read().unwrap();
- let mut text = button.get_label().unwrap();
- let len = &text.len();
-
- if *reverse {
- let begin = &text.split_off(1);
- text.insert_str(0, begin);
- } else {
- let end = &text.split_off(len - 1);
- text.insert_str(0, end);
- }
-
- button.set_label(&text);
-
- gtk::Continue(true)
- });
-
-
- window.show_all();
- gtk::main();
-}
+#[cfg(not(feature = "gtk"))]
+fn main() {}
|
--- a/tasks/animation/src/main.rs
+++ b/tasks/animation/src/main.rs
@@ ... @@
-extern crate gtk;
+#[cfg(feature = "gtk")]
+mod graphical {
+ extern crate gtk;
-use gtk::prelude::*;
-use std::ops::Not;
-use std::sync::{Arc, RwLock};
+ use self::gtk::traits::*;
+ use self::gtk::{Inhibit, Window, WindowType};
+ use std::ops::Not;
+ use std::sync::{Arc, RwLock};
+
+ pub fn create_window() {
+ gtk::init().expect("Failed to initialize GTK");
+
+ let window = Window::new(WindowType::Toplevel);
+ window.connect_delete_event(|_, _| {
+ gtk::main_quit();
+ Inhibit(false)
+ });
+ let button = gtk::Button::new_with_label("Hello World! ");
+ window.add(&button);
+
+ let lock = Arc::new(RwLock::new(false));
+
+ let lock_button = lock.clone();
+ button.connect_clicked(move |_| {
+ let mut reverse = lock_button.write().unwrap();
+ *reverse = reverse.not();
+ });
+
+ let lock_thread = lock.clone();
+ gtk::timeout_add(100, move || {
+ let reverse = lock_thread.read().unwrap();
+ let mut text = button.get_label().unwrap();
+ let len = &text.len();
+
+ if *reverse {
+ let begin = &text.split_off(1);
+ text.insert_str(0, begin);
+ } else {
+ let end = &text.split_off(len - 1);
+ text.insert_str(0, end);
+ }
+
+ button.set_label(&text);
+
+ gtk::Continue(true)
+ });
+
+ window.show_all();
+ gtk::main();
+ }
+}
+#[cfg(feature = "gtk")]
fn main() {
- if gtk::init().is_err() {
- println!("Failed to initialize GTK.");
- return;
- }
+ graphical::create_window();
+}
- let window = gtk::Window::new(gtk::WindowType::Toplevel);
-
- window.connect_delete_event(|_, _| {
- gtk::main_quit();
- Inhibit(false)
- });
-
- let button = gtk::Button::new_with_label("Hello World! ");
-
- window.add(&button);
-
- let lock = Arc::new(RwLock::new(false));
-
- let lock_button = lock.clone();
- button.connect_clicked(move |_| {
- let mut reverse = lock_button.write().unwrap();
- *reverse = reverse.not();
- });
-
- let lock_thread = lock.clone();
- gtk::timeout_add(100, move || {
- let reverse = lock_thread.read().unwrap();
- let mut text = button.get_label().unwrap();
- let len = &text.len();
-
- if *reverse {
- let begin = &text.split_off(1);
- text.insert_str(0, begin);
- } else {
- let end = &text.split_off(len - 1);
- text.insert_str(0, end);
- }
-
- button.set_label(&text);
-
- gtk::Continue(true)
- });
-
-
- window.show_all();
- gtk::main();
-}
+#[cfg(not(feature = "gtk"))]
+fn main() {}
|
--- a/tasks/animation/src/main.rs
+++ b/tasks/animation/src/main.rs
@@ -1,55 +1,60 @@
DEL extern crate gtk;
ADD #[cfg(feature = "gtk")]
ADD mod graphical {
ADD extern crate gtk;
CON
DEL use gtk::prelude::*;
DEL use std::ops::Not;
DEL use std::sync::{Arc, RwLock};
ADD use self::gtk::traits::*;
ADD use self::gtk::{Inhibit, Window, WindowType};
ADD use std::ops::Not;
ADD use std::sync::{Arc, RwLock};
ADD
ADD pub fn create_window() {
ADD gtk::init().expect("Failed to initialize GTK");
ADD
ADD let window = Window::new(WindowType::Toplevel);
ADD window.connect_delete_event(|_, _| {
ADD gtk::main_quit();
ADD Inhibit(false)
ADD });
ADD let button = gtk::Button::new_with_label("Hello World! ");
ADD window.add(&button);
ADD
ADD let lock = Arc::new(RwLock::new(false));
ADD
ADD let lock_button = lock.clone();
ADD button.connect_clicked(move |_| {
ADD let mut reverse = lock_button.write().unwrap();
ADD *reverse = reverse.not();
ADD });
ADD
ADD let lock_thread = lock.clone();
ADD gtk::timeout_add(100, move || {
ADD let reverse = lock_thread.read().unwrap();
ADD let mut text = button.get_label().unwrap();
ADD let len = &text.len();
ADD
ADD if *reverse {
ADD let begin = &text.split_off(1);
ADD text.insert_str(0, begin);
ADD } else {
ADD let end = &text.split_off(len - 1);
ADD text.insert_str(0, end);
ADD }
ADD
ADD button.set_label(&text);
ADD
ADD gtk::Continue(true)
ADD });
ADD
ADD window.show_all();
ADD gtk::main();
ADD }
ADD }
CON
CON
ADD #[cfg(feature = "gtk")]
CON fn main() {
DEL if gtk::init().is_err() {
DEL println!("Failed to initialize GTK.");
DEL return;
DEL }
ADD graphical::create_window();
ADD }
CON
DEL let window = gtk::Window::new(gtk::WindowType::Toplevel);
DEL
DEL window.connect_delete_event(|_, _| {
DEL gtk::main_quit();
DEL Inhibit(false)
DEL });
DEL
DEL let button = gtk::Button::new_with_label("Hello World! ");
DEL
DEL window.add(&button);
DEL
DEL let lock = Arc::new(RwLock::new(false));
DEL
DEL let lock_button = lock.clone();
DEL button.connect_clicked(move |_| {
DEL let mut reverse = lock_button.write().unwrap();
DEL *reverse = reverse.not();
DEL });
DEL
DEL let lock_thread = lock.clone();
DEL gtk::timeout_add(100, move || {
DEL let reverse = lock_thread.read().unwrap();
DEL let mut text = button.get_label().unwrap();
DEL let len = &text.len();
DEL
DEL if *reverse {
DEL let begin = &text.split_off(1);
DEL text.insert_str(0, begin);
DEL } else {
DEL let end = &text.split_off(len - 1);
DEL text.insert_str(0, end);
DEL }
DEL
DEL button.set_label(&text);
DEL
DEL gtk::Continue(true)
DEL });
DEL
DEL
DEL window.show_all();
DEL gtk::main();
DEL }
ADD #[cfg(not(feature = "gtk"))]
ADD fn main() {}
|
<<<<<<< SEARCH
extern crate gtk;
use gtk::prelude::*;
use std::ops::Not;
use std::sync::{Arc, RwLock};
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
=======
#[cfg(feature = "gtk")]
mod graphical {
extern crate gtk;
use self::gtk::traits::*;
use self::gtk::{Inhibit, Window, WindowType};
use std::ops::Not;
use std::sync::{Arc, RwLock};
pub fn create_window() {
gtk::init().expect("Failed to initialize GTK");
let window = Window::new(WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
}
#[cfg(feature = "gtk")]
fn main() {
graphical::create_window();
}
#[cfg(not(feature = "gtk"))]
fn main() {}
>>>>>>> REPLACE
|
rust-fuzz/cargo-fuzz
|
c514eabe5956bceb921b3f1c242726ca31969913
|
src/templates.rs
|
rust
|
apache-2.0
|
Use `libfuzzer-sys` version 0.4.0 in the new project template
|
macro_rules! toml_template {
($name: expr) => {
format_args!(
r##"
[package]
name = "{0}-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.3"
[dependencies.{0}]
path = ".."
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
"##,
$name
)
};
}
macro_rules! toml_bin_template {
($name: expr) => {
format_args!(
r#"
[[bin]]
name = "{0}"
path = "fuzz_targets/{0}.rs"
test = false
doc = false
"#,
$name
)
};
}
macro_rules! gitignore_template {
() => {
format_args!(
r##"
target
corpus
artifacts
"##
)
};
}
macro_rules! target_template {
() => {
format_args!(
r##"#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {{
// fuzzed code goes here
}});
"##
)
};
}
|
macro_rules! toml_template {
($name: expr) => {
format_args!(
r##"
[package]
name = "{0}-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
[dependencies.{0}]
path = ".."
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
"##,
$name
)
};
}
macro_rules! toml_bin_template {
($name: expr) => {
format_args!(
r#"
[[bin]]
name = "{0}"
path = "fuzz_targets/{0}.rs"
test = false
doc = false
"#,
$name
)
};
}
macro_rules! gitignore_template {
() => {
format_args!(
r##"
target
corpus
artifacts
"##
)
};
}
macro_rules! target_template {
() => {
format_args!(
r##"#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {{
// fuzzed code goes here
}});
"##
)
};
}
| 1
| 1
| 1
|
mixed
|
--- a/src/templates.rs
+++ b/src/templates.rs
@@ -15,3 +15,3 @@
[dependencies]
-libfuzzer-sys = "0.3"
+libfuzzer-sys = "0.4"
|
--- a/src/templates.rs
+++ b/src/templates.rs
@@ ... @@
[dependencies]
-libfuzzer-sys = "0.3"
+libfuzzer-sys = "0.4"
|
--- a/src/templates.rs
+++ b/src/templates.rs
@@ -15,3 +15,3 @@
CON [dependencies]
DEL libfuzzer-sys = "0.3"
ADD libfuzzer-sys = "0.4"
CON
|
<<<<<<< SEARCH
[dependencies]
libfuzzer-sys = "0.3"
[dependencies.{0}]
=======
[dependencies]
libfuzzer-sys = "0.4"
[dependencies.{0}]
>>>>>>> REPLACE
|
ucla/PushHubCore
|
bf57dc8255df91954701fc13ca08e1999b9d2d39
|
setup.py
|
python
|
bsd-3-clause
|
Add author and URL info to make mkrelease happy.
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_zodbconn',
'pyramid_tm',
'pyramid_debugtoolbar',
'ZODB3',
'waitress',
'repoze.folder',
'zope.interface',
'requests',
'feedparser',
'WebHelpers',
'zc.queue',
]
setup(name='push-hub',
version='0.5',
description='push-hub',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pylons pyramid',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires = requires,
tests_require= requires,
extras_require={'test': ['mock']},
test_suite="pushhub",
entry_points = """\
[paste.app_factory]
main = pushhub:main
[console_scripts]
process_subscriber_notices = pushhub.scripts:process_subscriber_notices
""",
)
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_zodbconn',
'pyramid_tm',
'pyramid_debugtoolbar',
'ZODB3',
'waitress',
'repoze.folder',
'zope.interface',
'requests',
'feedparser',
'WebHelpers',
'zc.queue',
]
setup(name='push-hub',
version='0.5',
description='push-hub',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Six Feet Up',
author_email='info@sixfeetup.com',
url='http://www.sixfeetup.com',
keywords='web pylons pyramid',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires = requires,
tests_require= requires,
extras_require={'test': ['mock']},
test_suite="pushhub",
entry_points = """\
[paste.app_factory]
main = pushhub:main
[console_scripts]
process_subscriber_notices = pushhub.scripts:process_subscriber_notices
""",
)
| 3
| 3
| 1
|
mixed
|
--- a/setup.py
+++ b/setup.py
@@ -33,5 +33,5 @@
],
- author='',
- author_email='',
- url='',
+ author='Six Feet Up',
+ author_email='info@sixfeetup.com',
+ url='http://www.sixfeetup.com',
keywords='web pylons pyramid',
|
--- a/setup.py
+++ b/setup.py
@@ ... @@
],
- author='',
- author_email='',
- url='',
+ author='Six Feet Up',
+ author_email='info@sixfeetup.com',
+ url='http://www.sixfeetup.com',
keywords='web pylons pyramid',
|
--- a/setup.py
+++ b/setup.py
@@ -33,5 +33,5 @@
CON ],
DEL author='',
DEL author_email='',
DEL url='',
ADD author='Six Feet Up',
ADD author_email='info@sixfeetup.com',
ADD url='http://www.sixfeetup.com',
CON keywords='web pylons pyramid',
|
<<<<<<< SEARCH
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pylons pyramid',
packages=find_packages(),
=======
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Six Feet Up',
author_email='info@sixfeetup.com',
url='http://www.sixfeetup.com',
keywords='web pylons pyramid',
packages=find_packages(),
>>>>>>> REPLACE
|
jami-i/embulk-parser-apache-custom-log
|
4b46c083c5b383339c516261c0eef7e11e2be167
|
src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
|
java
|
mit
|
Use traditional constructors of TimestampParser against Embulk core deprecation
Some constructors of them have been deprecated on the Embulk core side.
See https://github.com/embulk/embulk/issues/745 for the details.
|
package org.embulk.parser.apache.log;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
import org.embulk.spi.time.TimestampParser;
import static org.embulk.spi.type.Types.TIMESTAMP;
public class TimestampLogElement extends LogElement<Timestamp> {
private final TimestampParser parser;
public TimestampLogElement(TimestampParser.Task task, String name, String regex) {
this(task, name, regex, "%d/%b/%Y:%T %z");
}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
}
@Override
public Timestamp parse(String s) {
try{
return parser.parse(s);
}catch (Exception e){
return null;
}
}
@Override
public void setToPageBuilder(PageBuilder pageBuilder, int i, String value) {
Timestamp parse = parse(value);
if(parse != null){
pageBuilder.setTimestamp(i, parse);
}else{
pageBuilder.setNull(i);
}
}
}
|
package org.embulk.parser.apache.log;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
import org.embulk.spi.time.TimestampParser;
import static org.embulk.spi.type.Types.TIMESTAMP;
public class TimestampLogElement extends LogElement<Timestamp> {
private final TimestampParser parser;
public TimestampLogElement(TimestampParser.Task task, String name, String regex) {
this(task, name, regex, "%d/%b/%Y:%T %z");
}
private static interface ParserIntlTask extends Task, TimestampParser.Task {}
private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
// TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
// Traditional constructor is used here for compatibility.
final ConfigSource configSource = Exec.newConfigSource();
configSource.set("format", pattern);
configSource.set("timezone", task.getDefaultTimeZone());
this.parser = new TimestampParser(
Exec.newConfigSource().loadConfig(ParserIntlTask.class),
configSource.loadConfig(ParserIntlColumnOption.class));
}
@Override
public Timestamp parse(String s) {
try{
return parser.parse(s);
}catch (Exception e){
return null;
}
}
@Override
public void setToPageBuilder(PageBuilder pageBuilder, int i, String value) {
Timestamp parse = parse(value);
if(parse != null){
pageBuilder.setTimestamp(i, parse);
}else{
pageBuilder.setNull(i);
}
}
}
| 14
| 1
| 2
|
mixed
|
--- a/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
+++ b/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
@@ -2,2 +2,5 @@
+import org.embulk.config.ConfigSource;
+import org.embulk.config.Task;
+import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
@@ -18,5 +21,15 @@
+ private static interface ParserIntlTask extends Task, TimestampParser.Task {}
+ private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
+
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
- this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
+ // TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
+ // Traditional constructor is used here for compatibility.
+ final ConfigSource configSource = Exec.newConfigSource();
+ configSource.set("format", pattern);
+ configSource.set("timezone", task.getDefaultTimeZone());
+ this.parser = new TimestampParser(
+ Exec.newConfigSource().loadConfig(ParserIntlTask.class),
+ configSource.loadConfig(ParserIntlColumnOption.class));
}
|
--- a/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
+++ b/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
@@ ... @@
+import org.embulk.config.ConfigSource;
+import org.embulk.config.Task;
+import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
@@ ... @@
+ private static interface ParserIntlTask extends Task, TimestampParser.Task {}
+ private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
+
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
- this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
+ // TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
+ // Traditional constructor is used here for compatibility.
+ final ConfigSource configSource = Exec.newConfigSource();
+ configSource.set("format", pattern);
+ configSource.set("timezone", task.getDefaultTimeZone());
+ this.parser = new TimestampParser(
+ Exec.newConfigSource().loadConfig(ParserIntlTask.class),
+ configSource.loadConfig(ParserIntlColumnOption.class));
}
|
--- a/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
+++ b/src/main/java/org/embulk/parser/apache/log/TimestampLogElement.java
@@ -2,2 +2,5 @@
CON
ADD import org.embulk.config.ConfigSource;
ADD import org.embulk.config.Task;
ADD import org.embulk.spi.Exec;
CON import org.embulk.spi.PageBuilder;
@@ -18,5 +21,15 @@
CON
ADD private static interface ParserIntlTask extends Task, TimestampParser.Task {}
ADD private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
ADD
CON public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
CON super(name, regex, TIMESTAMP);
DEL this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
ADD // TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
ADD // Traditional constructor is used here for compatibility.
ADD final ConfigSource configSource = Exec.newConfigSource();
ADD configSource.set("format", pattern);
ADD configSource.set("timezone", task.getDefaultTimeZone());
ADD this.parser = new TimestampParser(
ADD Exec.newConfigSource().loadConfig(ParserIntlTask.class),
ADD configSource.loadConfig(ParserIntlColumnOption.class));
CON }
|
<<<<<<< SEARCH
package org.embulk.parser.apache.log;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
=======
package org.embulk.parser.apache.log;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
>>>>>>> REPLACE
<<<<<<< SEARCH
}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
}
=======
}
private static interface ParserIntlTask extends Task, TimestampParser.Task {}
private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
// TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
// Traditional constructor is used here for compatibility.
final ConfigSource configSource = Exec.newConfigSource();
configSource.set("format", pattern);
configSource.set("timezone", task.getDefaultTimeZone());
this.parser = new TimestampParser(
Exec.newConfigSource().loadConfig(ParserIntlTask.class),
configSource.loadConfig(ParserIntlColumnOption.class));
}
>>>>>>> REPLACE
|
viewflow/django-material
|
ebfaf30fca157e83ea9e4bf33173221fc9525caf
|
demo/examples/employees/forms.py
|
python
|
bsd-3-clause
|
Fix emplorrs demo salary db error
|
from datetime import date
from django import forms
from django.utils import timezone
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department')
super(ChangeManagerForm, self).__init__(*args, **kwargs)
def save(self):
new_manager = self.cleaned_data['manager']
DeptManager.objects.filter(
department=self.department
).set(
department=self.department,
employee=new_manager
)
class ChangeTitleForm(forms.Form):
position = forms.CharField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeTitleForm, self).__init__(*args, **kwargs)
def save(self):
new_title = self.cleaned_data['position']
Title.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
title=new_title
)
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeSalaryForm, self).__init__(*args, **kwargs)
def save(self):
new_salary = self.cleaned_data['salary']
Salary.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
salary=new_salary,
)
|
from django import forms
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department')
super(ChangeManagerForm, self).__init__(*args, **kwargs)
def save(self):
new_manager = self.cleaned_data['manager']
DeptManager.objects.filter(
department=self.department
).set(
department=self.department,
employee=new_manager
)
class ChangeTitleForm(forms.Form):
position = forms.CharField()
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeTitleForm, self).__init__(*args, **kwargs)
def save(self):
new_title = self.cleaned_data['position']
Title.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
title=new_title
)
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField(max_value=1000000)
def __init__(self, *args, **kwargs):
self.employee = kwargs.pop('employee')
super(ChangeSalaryForm, self).__init__(*args, **kwargs)
def save(self):
new_salary = self.cleaned_data['salary']
Salary.objects.filter(
employee=self.employee,
).set(
employee=self.employee,
salary=new_salary,
)
| 1
| 4
| 2
|
mixed
|
--- a/demo/examples/employees/forms.py
+++ b/demo/examples/employees/forms.py
@@ -1,5 +1,2 @@
-from datetime import date
-
from django import forms
-from django.utils import timezone
@@ -45,3 +42,3 @@
class ChangeSalaryForm(forms.Form):
- salary = forms.IntegerField()
+ salary = forms.IntegerField(max_value=1000000)
|
--- a/demo/examples/employees/forms.py
+++ b/demo/examples/employees/forms.py
@@ ... @@
-from datetime import date
-
from django import forms
-from django.utils import timezone
@@ ... @@
class ChangeSalaryForm(forms.Form):
- salary = forms.IntegerField()
+ salary = forms.IntegerField(max_value=1000000)
|
--- a/demo/examples/employees/forms.py
+++ b/demo/examples/employees/forms.py
@@ -1,5 +1,2 @@
DEL from datetime import date
DEL
CON from django import forms
DEL from django.utils import timezone
CON
@@ -45,3 +42,3 @@
CON class ChangeSalaryForm(forms.Form):
DEL salary = forms.IntegerField()
ADD salary = forms.IntegerField(max_value=1000000)
CON
|
<<<<<<< SEARCH
from datetime import date
from django import forms
from django.utils import timezone
from .models import Employee, DeptManager, Title, Salary
=======
from django import forms
from .models import Employee, DeptManager, Title, Salary
>>>>>>> REPLACE
<<<<<<< SEARCH
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField()
def __init__(self, *args, **kwargs):
=======
class ChangeSalaryForm(forms.Form):
salary = forms.IntegerField(max_value=1000000)
def __init__(self, *args, **kwargs):
>>>>>>> REPLACE
|
ezPy-co/ezpy
|
317926c18ac2e139d2018acd767d10b4f53428f3
|
installer/installer_config/views.py
|
python
|
mit
|
Remove unneeded post method from CreateEnvProfile view
|
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.views.generic import CreateView, UpdateView, DeleteView
from installer_config.models import EnvironmentProfile, UserChoice, Step
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
class CreateEnvironmentProfile(CreateView):
model = EnvironmentProfile
template_name = 'env_profile_form.html'
form_class = EnvironmentForm
success_url = '/profile'
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateEnvironmentProfile, self).form_valid(form)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = form_class(request.POST)
if form.is_valid():
config_profile = form.save(commit=False)
config_profile.user = request.user
config_profile.save()
return HttpResponseRedirect(reverse('profile:profile'))
return self.render_to_response({'form': form})
class UpdateEnvironmentProfile(UpdateView):
model = EnvironmentProfile
context_object_name = 'profile'
template_name = 'env_profile_form.html'
form_class = EnvironmentForm
success_url = '/profile'
class DeleteEnvironmentProfile(DeleteView):
model = EnvironmentProfile
success_url = '/profile'
def download_profile_view(request, **kwargs):
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
# import pdb; pdb.set_trace()
response = render_to_response('installer_template.py', {'choices': choices},
content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
return response
|
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.views.generic import CreateView, UpdateView, DeleteView
from installer_config.models import EnvironmentProfile, UserChoice, Step
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse
class CreateEnvironmentProfile(CreateView):
model = EnvironmentProfile
template_name = 'env_profile_form.html'
form_class = EnvironmentForm
success_url = '/profile'
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateEnvironmentProfile, self).form_valid(form)
class UpdateEnvironmentProfile(UpdateView):
model = EnvironmentProfile
context_object_name = 'profile'
template_name = 'env_profile_form.html'
form_class = EnvironmentForm
success_url = '/profile'
class DeleteEnvironmentProfile(DeleteView):
model = EnvironmentProfile
success_url = '/profile'
def download_profile_view(request, **kwargs):
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
response = render_to_response('installer_template.py', {'choices': choices},
content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
return response
| 2
| 13
| 3
|
mixed
|
--- a/installer/installer_config/views.py
+++ b/installer/installer_config/views.py
@@ -6,3 +6,3 @@
from django.core.urlresolvers import reverse
-from django.http import HttpResponseRedirect
+
@@ -18,12 +18,2 @@
-
- def post(self, request, *args, **kwargs):
- form_class = self.get_form_class()
- form = form_class(request.POST)
- if form.is_valid():
- config_profile = form.save(commit=False)
- config_profile.user = request.user
- config_profile.save()
- return HttpResponseRedirect(reverse('profile:profile'))
- return self.render_to_response({'form': form})
@@ -44,5 +34,4 @@
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
- # import pdb; pdb.set_trace()
response = render_to_response('installer_template.py', {'choices': choices},
- content_type='application')
+ content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
|
--- a/installer/installer_config/views.py
+++ b/installer/installer_config/views.py
@@ ... @@
from django.core.urlresolvers import reverse
-from django.http import HttpResponseRedirect
+
@@ ... @@
-
- def post(self, request, *args, **kwargs):
- form_class = self.get_form_class()
- form = form_class(request.POST)
- if form.is_valid():
- config_profile = form.save(commit=False)
- config_profile.user = request.user
- config_profile.save()
- return HttpResponseRedirect(reverse('profile:profile'))
- return self.render_to_response({'form': form})
@@ ... @@
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
- # import pdb; pdb.set_trace()
response = render_to_response('installer_template.py', {'choices': choices},
- content_type='application')
+ content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
|
--- a/installer/installer_config/views.py
+++ b/installer/installer_config/views.py
@@ -6,3 +6,3 @@
CON from django.core.urlresolvers import reverse
DEL from django.http import HttpResponseRedirect
ADD
CON
@@ -18,12 +18,2 @@
CON
DEL
DEL def post(self, request, *args, **kwargs):
DEL form_class = self.get_form_class()
DEL form = form_class(request.POST)
DEL if form.is_valid():
DEL config_profile = form.save(commit=False)
DEL config_profile.user = request.user
DEL config_profile.save()
DEL return HttpResponseRedirect(reverse('profile:profile'))
DEL return self.render_to_response({'form': form})
CON
@@ -44,5 +34,4 @@
CON choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
DEL # import pdb; pdb.set_trace()
CON response = render_to_response('installer_template.py', {'choices': choices},
DEL content_type='application')
ADD content_type='application')
CON response['Content-Disposition'] = 'attachment; filename=something.py'
|
<<<<<<< SEARCH
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
class CreateEnvironmentProfile(CreateView):
=======
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse
class CreateEnvironmentProfile(CreateView):
>>>>>>> REPLACE
<<<<<<< SEARCH
return super(CreateEnvironmentProfile, self).form_valid(form)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = form_class(request.POST)
if form.is_valid():
config_profile = form.save(commit=False)
config_profile.user = request.user
config_profile.save()
return HttpResponseRedirect(reverse('profile:profile'))
return self.render_to_response({'form': form})
class UpdateEnvironmentProfile(UpdateView):
=======
return super(CreateEnvironmentProfile, self).form_valid(form)
class UpdateEnvironmentProfile(UpdateView):
>>>>>>> REPLACE
<<<<<<< SEARCH
def download_profile_view(request, **kwargs):
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
# import pdb; pdb.set_trace()
response = render_to_response('installer_template.py', {'choices': choices},
content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
return response
=======
def download_profile_view(request, **kwargs):
choices = UserChoice.objects.filter(profiles=kwargs['pk']).all()
response = render_to_response('installer_template.py', {'choices': choices},
content_type='application')
response['Content-Disposition'] = 'attachment; filename=something.py'
return response
>>>>>>> REPLACE
|
zzz0072/Python_Exercises
|
8d9bb10d5281fe89f693068143e45ff761200abd
|
01_Built-in_Types/list.py
|
python
|
bsd-2-clause
|
Add comment for object types
|
#!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
|
#!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
# type and id are unique
# ref: https://docs.python.org/2/reference/datamodel.html
# mutable object: value can be changed
# immutable object: value can NOT be changed after created
# This means readonly
# ex: string, numbers, tuple
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
| 7
| 0
| 1
|
add_only
|
--- a/01_Built-in_Types/list.py
+++ b/01_Built-in_Types/list.py
@@ -6,2 +6,9 @@
# Object related test
+# type and id are unique
+# ref: https://docs.python.org/2/reference/datamodel.html
+# mutable object: value can be changed
+# immutable object: value can NOT be changed after created
+# This means readonly
+# ex: string, numbers, tuple
+
print(type(sys.argv))
|
--- a/01_Built-in_Types/list.py
+++ b/01_Built-in_Types/list.py
@@ ... @@
# Object related test
+# type and id are unique
+# ref: https://docs.python.org/2/reference/datamodel.html
+# mutable object: value can be changed
+# immutable object: value can NOT be changed after created
+# This means readonly
+# ex: string, numbers, tuple
+
print(type(sys.argv))
|
--- a/01_Built-in_Types/list.py
+++ b/01_Built-in_Types/list.py
@@ -6,2 +6,9 @@
CON # Object related test
ADD # type and id are unique
ADD # ref: https://docs.python.org/2/reference/datamodel.html
ADD # mutable object: value can be changed
ADD # immutable object: value can NOT be changed after created
ADD # This means readonly
ADD # ex: string, numbers, tuple
ADD
CON print(type(sys.argv))
|
<<<<<<< SEARCH
# Object related test
print(type(sys.argv))
print(id(sys.argv))
=======
# Object related test
# type and id are unique
# ref: https://docs.python.org/2/reference/datamodel.html
# mutable object: value can be changed
# immutable object: value can NOT be changed after created
# This means readonly
# ex: string, numbers, tuple
print(type(sys.argv))
print(id(sys.argv))
>>>>>>> REPLACE
|
luxons/seven-wonders
|
80029f8c9c2ebdbd187e1078cdfbfcd5010335b9
|
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
|
kotlin
|
mit
|
Add title on hand rotation direction
|
package org.luxons.sevenwonders.ui.components.game
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import org.luxons.sevenwonders.model.cards.HandRotationDirection
import react.RBuilder
import styled.css
import styled.styledDiv
import styled.styledImg
fun RBuilder.handRotationIndicator(direction: HandRotationDirection) {
styledDiv {
css {
position = Position.absolute
display = Display.flex
alignItems = Align.center
bottom = 25.vh
}
val sideDistance = 2.rem
when (direction) {
HandRotationDirection.LEFT -> {
css { left = sideDistance }
bpIcon("arrow-left", size = 25)
handCardsImg()
}
HandRotationDirection.RIGHT -> {
css { right = sideDistance }
handCardsImg()
bpIcon("arrow-right", size = 25)
}
}
}
}
private fun RBuilder.handCardsImg() {
styledImg(src = "images/hand-cards5.png") {
css {
width = 4.rem
}
}
}
|
package org.luxons.sevenwonders.ui.components.game
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import kotlinx.html.title
import org.luxons.sevenwonders.model.cards.HandRotationDirection
import react.RBuilder
import styled.css
import styled.styledDiv
import styled.styledImg
fun RBuilder.handRotationIndicator(direction: HandRotationDirection) {
styledDiv {
css {
position = Position.absolute
display = Display.flex
alignItems = Align.center
bottom = 25.vh
}
attrs {
title = "Your hand will be passed to the player on your $direction after playing this card."
}
val sideDistance = 2.rem
when (direction) {
HandRotationDirection.LEFT -> {
css { left = sideDistance }
bpIcon("arrow-left", size = 25)
handCardsImg()
}
HandRotationDirection.RIGHT -> {
css { right = sideDistance }
handCardsImg()
bpIcon("arrow-right", size = 25)
}
}
}
}
private fun RBuilder.handCardsImg() {
styledImg(src = "images/hand-cards5.png") {
css {
width = 4.rem
}
}
}
| 4
| 0
| 2
|
add_only
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
@@ -4,2 +4,3 @@
import kotlinx.css.*
+import kotlinx.html.title
import org.luxons.sevenwonders.model.cards.HandRotationDirection
@@ -17,2 +18,5 @@
bottom = 25.vh
+ }
+ attrs {
+ title = "Your hand will be passed to the player on your $direction after playing this card."
}
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
@@ ... @@
import kotlinx.css.*
+import kotlinx.html.title
import org.luxons.sevenwonders.model.cards.HandRotationDirection
@@ ... @@
bottom = 25.vh
+ }
+ attrs {
+ title = "Your hand will be passed to the player on your $direction after playing this card."
}
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/HandRotationIndicator.kt
@@ -4,2 +4,3 @@
CON import kotlinx.css.*
ADD import kotlinx.html.title
CON import org.luxons.sevenwonders.model.cards.HandRotationDirection
@@ -17,2 +18,5 @@
CON bottom = 25.vh
ADD }
ADD attrs {
ADD title = "Your hand will be passed to the player on your $direction after playing this card."
CON }
|
<<<<<<< SEARCH
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import org.luxons.sevenwonders.model.cards.HandRotationDirection
import react.RBuilder
=======
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import kotlinx.html.title
import org.luxons.sevenwonders.model.cards.HandRotationDirection
import react.RBuilder
>>>>>>> REPLACE
<<<<<<< SEARCH
alignItems = Align.center
bottom = 25.vh
}
val sideDistance = 2.rem
=======
alignItems = Align.center
bottom = 25.vh
}
attrs {
title = "Your hand will be passed to the player on your $direction after playing this card."
}
val sideDistance = 2.rem
>>>>>>> REPLACE
|
md5555/android_packages_services_Telephony
|
0ef9516106060b1506420fcf5d997fed4718ca7c
|
src/com/android/phone/TelephonyDebugService.java
|
java
|
apache-2.0
|
Revert "enforce dump permission on dump()"
Stability blocker.
java.lang.SecurityException: Requires DUMP: Neither user 1001 nor current process has android.permission.DUMP.
at android.app.ContextImpl.enforce(ContextImpl.java:1893)
at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1922)
at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:593)
at com.android.phone.TelephonyDebugService.dump(TelephonyDebugService.java:50)
at android.app.ActivityThread.handleDumpService(ActivityThread.java:2813)
at android.app.ActivityThread.access$2300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This reverts commit 8e4dae587f8a4dd20b06c16e4f7fd3723ff56774.
Bug: 18090004
Change-Id: Id9a549971dbe7a5b4baeb7067967cd791541cf4a
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import com.android.internal.telephony.DebugService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
/**
* A debug service for telephony.
*/
public class TelephonyDebugService extends Service {
private static String TAG = "TelephonyDebugService";
private DebugService mDebugService = new DebugService();
/** Constructor */
public TelephonyDebugService() {
Log.d(TAG, "TelephonyDebugService()");
}
/**
* {@inheritDoc}
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
"Requires DUMP");
mDebugService.dump(fd, pw, args);
}
}
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import com.android.internal.telephony.DebugService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
/**
* A debug service for telephony.
*/
public class TelephonyDebugService extends Service {
private static String TAG = "TelephonyDebugService";
private DebugService mDebugService = new DebugService();
/** Constructor */
public TelephonyDebugService() {
Log.d(TAG, "TelephonyDebugService()");
}
/**
* {@inheritDoc}
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
mDebugService.dump(fd, pw, args);
}
}
| 0
| 2
| 1
|
del_only
|
--- a/src/com/android/phone/TelephonyDebugService.java
+++ b/src/com/android/phone/TelephonyDebugService.java
@@ -49,4 +49,2 @@
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
- "Requires DUMP");
mDebugService.dump(fd, pw, args);
|
--- a/src/com/android/phone/TelephonyDebugService.java
+++ b/src/com/android/phone/TelephonyDebugService.java
@@ ... @@
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
- "Requires DUMP");
mDebugService.dump(fd, pw, args);
|
--- a/src/com/android/phone/TelephonyDebugService.java
+++ b/src/com/android/phone/TelephonyDebugService.java
@@ -49,4 +49,2 @@
CON protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
DEL enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
DEL "Requires DUMP");
CON mDebugService.dump(fd, pw, args);
|
<<<<<<< SEARCH
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
"Requires DUMP");
mDebugService.dump(fd, pw, args);
}
=======
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
mDebugService.dump(fd, pw, args);
}
>>>>>>> REPLACE
|
jypma/lambda-behave
|
d577a812b889911a588d754aee66d87da471f8d4
|
lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
|
java
|
mit
|
Add failure message when testing whether a string matches a regex
|
package com.insightfullogic.lambdabehave.expectations;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* .
*/
public final class StringExpectation extends BoundExpectation<String> {
public StringExpectation(final String str, final boolean positive) {
super(str, positive);
}
public StringExpectation isEmptyString() {
return matches(Matchers.isEmptyString());
}
public StringExpectation isEmptyOrNullString() {
return matches(Matchers.isEmptyOrNullString());
}
public StringExpectation equalToIgnoringCase(final String expectedString) {
return matches(Matchers.equalToIgnoringCase(expectedString));
}
public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
}
public StringExpectation containsString(final String substring) {
return matches(Matchers.containsString(substring));
}
public StringExpectation endsWith(final String suffix) {
return matches(Matchers.endsWith(suffix));
}
public StringExpectation startsWith(final String prefix) {
return matches(Matchers.startsWith(prefix));
}
private StringExpectation matches(final Matcher<String> matcher) {
assertThat(objectUnderTest, matcher);
return this;
}
public StringExpectation matches(String regex) {
assertTrue(objectUnderTest.matches(regex));
return this;
}
}
|
package com.insightfullogic.lambdabehave.expectations;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* .
*/
public final class StringExpectation extends BoundExpectation<String> {
public StringExpectation(final String str, final boolean positive) {
super(str, positive);
}
public StringExpectation isEmptyString() {
return matches(Matchers.isEmptyString());
}
public StringExpectation isEmptyOrNullString() {
return matches(Matchers.isEmptyOrNullString());
}
public StringExpectation equalToIgnoringCase(final String expectedString) {
return matches(Matchers.equalToIgnoringCase(expectedString));
}
public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
}
public StringExpectation containsString(final String substring) {
return matches(Matchers.containsString(substring));
}
public StringExpectation endsWith(final String suffix) {
return matches(Matchers.endsWith(suffix));
}
public StringExpectation startsWith(final String prefix) {
return matches(Matchers.startsWith(prefix));
}
private StringExpectation matches(final Matcher<String> matcher) {
assertThat(objectUnderTest, matcher);
return this;
}
public StringExpectation matches(String regex) {
assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
return this;
}
}
| 1
| 1
| 1
|
mixed
|
--- a/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
+++ b/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
@@ -50,3 +50,3 @@
public StringExpectation matches(String regex) {
- assertTrue(objectUnderTest.matches(regex));
+ assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
return this;
|
--- a/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
+++ b/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
@@ ... @@
public StringExpectation matches(String regex) {
- assertTrue(objectUnderTest.matches(regex));
+ assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
return this;
|
--- a/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
+++ b/lambda-behave/src/main/java/com/insightfullogic/lambdabehave/expectations/StringExpectation.java
@@ -50,3 +50,3 @@
CON public StringExpectation matches(String regex) {
DEL assertTrue(objectUnderTest.matches(regex));
ADD assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
CON return this;
|
<<<<<<< SEARCH
public StringExpectation matches(String regex) {
assertTrue(objectUnderTest.matches(regex));
return this;
}
=======
public StringExpectation matches(String regex) {
assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
return this;
}
>>>>>>> REPLACE
|
fcostaa/kotlin-rxjava-android
|
a49614ebcd41074d0dc84a2ab152781f0dd01bd4
|
library/network/build.gradle.kts
|
kotlin
|
mit
|
Add RxJava dependency to network module
The new AGP is force this kind of behavior that satisfies some version constraints.
|
plugins {
id("com.android.library")
kotlin("android")
kotlin("kapt")
}
android {
compileSdkVersion(Versions.compileSdkVersion)
buildToolsVersion(Versions.buildToolsVersion)
defaultConfig {
minSdkVersion(Versions.minSdkVersion)
targetSdkVersion(Versions.targetSdkVersion)
versionCode = Versions.versionCode
versionName = Versions.versionName
testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
getByName("debug") {
isTestCoverageEnabled = true
}
create("debugMini") {
initWith(getByName("debug"))
matchingFallbacks = listOf("debug")
}
getByName("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
sourceSets {
getByName("main").java.srcDirs("src/main/kotlin")
getByName("test").java.srcDirs("src/test/kotlin")
getByName("androidTest").java.srcDirs("src/androidTest/kotlin")
}
}
dependencies {
KotlinDependencies.values.forEach { implementation(it) }
NetworkDependencies.values.forEach { implementation(it) }
}
val add_test_dependencies: groovy.lang.Closure<Any?> by extra
add_test_dependencies(project)
|
plugins {
id("com.android.library")
kotlin("android")
kotlin("kapt")
}
android {
compileSdkVersion(Versions.compileSdkVersion)
buildToolsVersion(Versions.buildToolsVersion)
defaultConfig {
minSdkVersion(Versions.minSdkVersion)
targetSdkVersion(Versions.targetSdkVersion)
versionCode = Versions.versionCode
versionName = Versions.versionName
testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
getByName("debug") {
isTestCoverageEnabled = true
}
create("debugMini") {
initWith(getByName("debug"))
matchingFallbacks = listOf("debug")
}
getByName("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
sourceSets {
getByName("main").java.srcDirs("src/main/kotlin")
getByName("test").java.srcDirs("src/test/kotlin")
getByName("androidTest").java.srcDirs("src/androidTest/kotlin")
}
}
dependencies {
KotlinDependencies.values.forEach { implementation(it) }
NetworkDependencies.values.forEach { implementation(it) }
implementation(RxJavaDependencies.rxJava)
}
val add_test_dependencies: groovy.lang.Closure<Any?> by extra
add_test_dependencies(project)
| 1
| 1
| 1
|
mixed
|
--- a/library/network/build.gradle.kts
+++ b/library/network/build.gradle.kts
@@ -44,4 +44,4 @@
KotlinDependencies.values.forEach { implementation(it) }
-
NetworkDependencies.values.forEach { implementation(it) }
+ implementation(RxJavaDependencies.rxJava)
}
|
--- a/library/network/build.gradle.kts
+++ b/library/network/build.gradle.kts
@@ ... @@
KotlinDependencies.values.forEach { implementation(it) }
-
NetworkDependencies.values.forEach { implementation(it) }
+ implementation(RxJavaDependencies.rxJava)
}
|
--- a/library/network/build.gradle.kts
+++ b/library/network/build.gradle.kts
@@ -44,4 +44,4 @@
CON KotlinDependencies.values.forEach { implementation(it) }
DEL
CON NetworkDependencies.values.forEach { implementation(it) }
ADD implementation(RxJavaDependencies.rxJava)
CON }
|
<<<<<<< SEARCH
dependencies {
KotlinDependencies.values.forEach { implementation(it) }
NetworkDependencies.values.forEach { implementation(it) }
}
=======
dependencies {
KotlinDependencies.values.forEach { implementation(it) }
NetworkDependencies.values.forEach { implementation(it) }
implementation(RxJavaDependencies.rxJava)
}
>>>>>>> REPLACE
|
fod-dev/bsi-token-parser
|
d395151170a346eca5b1bc59195b5da58dcc3cf3
|
src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
|
kotlin
|
apache-2.0
|
Fix token parsing for Bsi Url
|
package com.fortify.fod.parser
import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
import java.io.UnsupportedEncodingException
import java.net.URI
import java.net.URISyntaxException
import java.net.URLEncoder
class BsiTokenParser {
@Throws(URISyntaxException::class, UnsupportedEncodingException::class)
fun parse(token: String): BsiToken {
val trimmedToken = token.trim()
if (trimmedToken.contains("/bsi2.aspx?")) {
val uri = URI(trimmedToken)
return parseBsiUrl(uri)
} else {
throw Exception("Not implemented")
}
}
@Throws(UnsupportedEncodingException::class)
private fun parseBsiUrl(uri: URI): BsiToken {
val params = URLEncodedUtils.parse(uri, "UTF-8")
var token = BsiToken()
for (param in params) {
when (param.name) {
"tid" -> token.tenantId = Integer.parseInt(param.value)
"tc" -> token.tenantCode = param.value
"pv" -> token.projectVersionId = Integer.parseInt(param.value)
"ts" -> token.technologyStack = URLEncoder.encode(param.value, "UTF-8")
"ll" -> token.languageLevel = param.value
"astid" -> token.assessmentTypeId = Integer.parseInt(param.value)
"payloadType" -> token.payloadType = param.value
}
}
return token;
}
}
|
package com.fortify.fod.parser
import org.apache.http.client.utils.URLEncodedUtils
import java.io.UnsupportedEncodingException
import java.net.URI
import java.net.URISyntaxException
import java.net.URLEncoder
class BsiTokenParser {
@Throws(URISyntaxException::class, UnsupportedEncodingException::class)
fun parse(token: String): BsiToken {
val trimmedToken = token.trim()
if (trimmedToken.contains("/bsi2.aspx?")) {
val uri = URI(trimmedToken)
return parseBsiUrl(uri)
} else {
throw Exception("Not implemented")
}
}
@Throws(UnsupportedEncodingException::class)
private fun parseBsiUrl(uri: URI): BsiToken {
val params = URLEncodedUtils.parse(uri, "UTF-8")
val token = BsiToken()
token.apiUri = "${uri.scheme}://${uri.host}"
for (param in params) {
when (param.name) {
"tid" -> token.tenantId = Integer.parseInt(param.value)
"tc" -> token.tenantCode = param.value
"pv" -> token.projectVersionId = Integer.parseInt(param.value)
"ts" -> token.technologyStack = URLEncoder.encode(param.value, "UTF-8")
"ll" -> token.languageLevel = param.value
"astid" -> token.assessmentTypeId = Integer.parseInt(param.value)
"payloadType" -> token.payloadType = param.value
}
}
return token
}
}
| 5
| 4
| 4
|
mixed
|
--- a/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
+++ b/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
@@ -2,3 +2,2 @@
-import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
@@ -15,3 +14,2 @@
-
if (trimmedToken.contains("/bsi2.aspx?")) {
@@ -26,5 +24,8 @@
private fun parseBsiUrl(uri: URI): BsiToken {
+
val params = URLEncodedUtils.parse(uri, "UTF-8")
+ val token = BsiToken()
- var token = BsiToken()
+ token.apiUri = "${uri.scheme}://${uri.host}"
+
for (param in params) {
@@ -41,3 +42,3 @@
- return token;
+ return token
}
|
--- a/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
+++ b/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
@@ ... @@
-import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
@@ ... @@
-
if (trimmedToken.contains("/bsi2.aspx?")) {
@@ ... @@
private fun parseBsiUrl(uri: URI): BsiToken {
+
val params = URLEncodedUtils.parse(uri, "UTF-8")
+ val token = BsiToken()
- var token = BsiToken()
+ token.apiUri = "${uri.scheme}://${uri.host}"
+
for (param in params) {
@@ ... @@
- return token;
+ return token
}
|
--- a/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
+++ b/src/main/kotlin/com/fortify/fod/parser/BsiTokenParser.kt
@@ -2,3 +2,2 @@
CON
DEL import org.apache.http.NameValuePair
CON import org.apache.http.client.utils.URLEncodedUtils
@@ -15,3 +14,2 @@
CON
DEL
CON if (trimmedToken.contains("/bsi2.aspx?")) {
@@ -26,5 +24,8 @@
CON private fun parseBsiUrl(uri: URI): BsiToken {
ADD
CON val params = URLEncodedUtils.parse(uri, "UTF-8")
ADD val token = BsiToken()
CON
DEL var token = BsiToken()
ADD token.apiUri = "${uri.scheme}://${uri.host}"
ADD
CON for (param in params) {
@@ -41,3 +42,3 @@
CON
DEL return token;
ADD return token
CON }
|
<<<<<<< SEARCH
package com.fortify.fod.parser
import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
import java.io.UnsupportedEncodingException
=======
package com.fortify.fod.parser
import org.apache.http.client.utils.URLEncodedUtils
import java.io.UnsupportedEncodingException
>>>>>>> REPLACE
<<<<<<< SEARCH
val trimmedToken = token.trim()
if (trimmedToken.contains("/bsi2.aspx?")) {
val uri = URI(trimmedToken)
=======
val trimmedToken = token.trim()
if (trimmedToken.contains("/bsi2.aspx?")) {
val uri = URI(trimmedToken)
>>>>>>> REPLACE
<<<<<<< SEARCH
@Throws(UnsupportedEncodingException::class)
private fun parseBsiUrl(uri: URI): BsiToken {
val params = URLEncodedUtils.parse(uri, "UTF-8")
var token = BsiToken()
for (param in params) {
when (param.name) {
=======
@Throws(UnsupportedEncodingException::class)
private fun parseBsiUrl(uri: URI): BsiToken {
val params = URLEncodedUtils.parse(uri, "UTF-8")
val token = BsiToken()
token.apiUri = "${uri.scheme}://${uri.host}"
for (param in params) {
when (param.name) {
>>>>>>> REPLACE
<<<<<<< SEARCH
}
return token;
}
}
=======
}
return token
}
}
>>>>>>> REPLACE
|
homeworkprod/byceps
|
7269322106911fcb1fb71160421fc3e011fbee1d
|
byceps/config_defaults.py
|
python
|
bsd-3-clause
|
Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE`
|
"""
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
"""
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
| 0
| 1
| 1
|
del_only
|
--- a/byceps/config_defaults.py
+++ b/byceps/config_defaults.py
@@ -48,3 +48,2 @@
ROOT_REDIRECT_TARGET = None
-ROOT_REDIRECT_STATUS_CODE = 307
|
--- a/byceps/config_defaults.py
+++ b/byceps/config_defaults.py
@@ ... @@
ROOT_REDIRECT_TARGET = None
-ROOT_REDIRECT_STATUS_CODE = 307
|
--- a/byceps/config_defaults.py
+++ b/byceps/config_defaults.py
@@ -48,3 +48,2 @@
CON ROOT_REDIRECT_TARGET = None
DEL ROOT_REDIRECT_STATUS_CODE = 307
CON
|
<<<<<<< SEARCH
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
=======
# home page
ROOT_REDIRECT_TARGET = None
# shop
>>>>>>> REPLACE
|
openai/universe
|
a6ed56b37bba3f5abff73c297a8a20271d73cab2
|
example/random-agent/random-agent.py
|
python
|
mit
|
Add configure call to random_agent
|
#!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
env.configure(remotes=1) # automatically creates a local docker container
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
| 2
| 0
| 1
|
add_only
|
--- a/example/random-agent/random-agent.py
+++ b/example/random-agent/random-agent.py
@@ -24,2 +24,4 @@
env = gym.make('flashgames.NeonRace-v0')
+ env.configure(remotes=1) # automatically creates a local docker container
+
# Restrict the valid random actions. (Try removing this and see
|
--- a/example/random-agent/random-agent.py
+++ b/example/random-agent/random-agent.py
@@ ... @@
env = gym.make('flashgames.NeonRace-v0')
+ env.configure(remotes=1) # automatically creates a local docker container
+
# Restrict the valid random actions. (Try removing this and see
|
--- a/example/random-agent/random-agent.py
+++ b/example/random-agent/random-agent.py
@@ -24,2 +24,4 @@
CON env = gym.make('flashgames.NeonRace-v0')
ADD env.configure(remotes=1) # automatically creates a local docker container
ADD
CON # Restrict the valid random actions. (Try removing this and see
|
<<<<<<< SEARCH
env = gym.make('flashgames.NeonRace-v0')
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
=======
env = gym.make('flashgames.NeonRace-v0')
env.configure(remotes=1) # automatically creates a local docker container
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
>>>>>>> REPLACE
|
rocha88/techtest1
|
19ea5fc52c05909f10f9d15198438fbebfb54714
|
js/app/Parser.js
|
javascript
|
mit
|
Refactor parser again to remove use of exceptions
|
define(function() {
'use strict';
/**
* @class
*/
function CurrencyParser() { }
function ParseError() { }
var penceOnlyParser = function (str) {
var found = str.match(/^(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1]);
};
var poundsOnlyParser = function (str) {
var found = str.match(/^£(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1] * 100);
};
var poundsAndPenceParser = function (str) {
var found = str.match(/^£?(\d+(\.\d*))p?$/);
if (found === null)
throw new ParseError();
else
return Math.round(parseFloat(found[1]) * 100);
};
var parsers = [
penceOnlyParser,
poundsOnlyParser,
poundsAndPenceParser
];
/**
* Parse the supplied string as a number of British pence
* @param {String} subject - The string to be parsed
* @returns {Number} The value of the string in pence
*/
CurrencyParser.prototype.parseString = function(str) {
for (var i = 0; i < parsers.length; i++) {
try {
var parser = parsers[i];
return parser(str)
} catch (e) {
continue;
}
}
// Return undefined if no parser succeeded
};
// Return constructor
return CurrencyParser;
});
|
define(function() {
'use strict';
/**
* @class
*/
function CurrencyParser() { }
/**
* Array of recognised currency formats, each with a regex pattern
* and a parser function which receives the first matched group.
*/
var formats = [
{
// Just pence, with optional 'p'
pattern: /^(\d+)p?$/,
parser: function (str) { return parseInt(str); }
},
{
// Just pounds, with '£' and optional 'p'
pattern: /^£(\d+)p?$/,
parser: function (str) { return parseInt(str) * 100; }
},
{
// Pounds and pence, with decimal point, and optional '£' and/or 'p'
pattern: /^£?(\d+(\.\d*))p?$/,
parser: function (str) { return Math.round(parseFloat(str) * 100); }
},
];
/**
* Parse the specified string and return a number of pence Sterling
* @param {String} input - The string to be parsed
* @returns {Number} Value in pence, or undefined if parsing failed
*/
CurrencyParser.prototype.parseString = function(input) {
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
var matches = input.match(format.pattern);
if (matches)
return format.parser(matches[1]);
}
// Return undefined if no format was matched
};
// Return constructor
return CurrencyParser;
});
| 30
| 42
| 2
|
mixed
|
--- a/js/app/Parser.js
+++ b/js/app/Parser.js
@@ -8,32 +8,22 @@
- function ParseError() { }
-
- var penceOnlyParser = function (str) {
- var found = str.match(/^(\d+)p?$/);
- if (found === null)
- throw new ParseError();
- else
- return parseInt(found[1]);
- };
-
- var poundsOnlyParser = function (str) {
- var found = str.match(/^£(\d+)p?$/);
- if (found === null)
- throw new ParseError();
- else
- return parseInt(found[1] * 100);
- };
-
- var poundsAndPenceParser = function (str) {
- var found = str.match(/^£?(\d+(\.\d*))p?$/);
- if (found === null)
- throw new ParseError();
- else
- return Math.round(parseFloat(found[1]) * 100);
- };
-
- var parsers = [
- penceOnlyParser,
- poundsOnlyParser,
- poundsAndPenceParser
+ /**
+ * Array of recognised currency formats, each with a regex pattern
+ * and a parser function which receives the first matched group.
+ */
+ var formats = [
+ {
+ // Just pence, with optional 'p'
+ pattern: /^(\d+)p?$/,
+ parser: function (str) { return parseInt(str); }
+ },
+ {
+ // Just pounds, with '£' and optional 'p'
+ pattern: /^£(\d+)p?$/,
+ parser: function (str) { return parseInt(str) * 100; }
+ },
+ {
+ // Pounds and pence, with decimal point, and optional '£' and/or 'p'
+ pattern: /^£?(\d+(\.\d*))p?$/,
+ parser: function (str) { return Math.round(parseFloat(str) * 100); }
+ },
];
@@ -41,17 +31,15 @@
/**
- * Parse the supplied string as a number of British pence
- * @param {String} subject - The string to be parsed
- * @returns {Number} The value of the string in pence
+ * Parse the specified string and return a number of pence Sterling
+ * @param {String} input - The string to be parsed
+ * @returns {Number} Value in pence, or undefined if parsing failed
*/
- CurrencyParser.prototype.parseString = function(str) {
- for (var i = 0; i < parsers.length; i++) {
- try {
- var parser = parsers[i];
- return parser(str)
- } catch (e) {
- continue;
- }
+ CurrencyParser.prototype.parseString = function(input) {
+ for (var i = 0; i < formats.length; i++) {
+ var format = formats[i];
+ var matches = input.match(format.pattern);
+ if (matches)
+ return format.parser(matches[1]);
}
- // Return undefined if no parser succeeded
+ // Return undefined if no format was matched
};
|
--- a/js/app/Parser.js
+++ b/js/app/Parser.js
@@ ... @@
- function ParseError() { }
-
- var penceOnlyParser = function (str) {
- var found = str.match(/^(\d+)p?$/);
- if (found === null)
- throw new ParseError();
- else
- return parseInt(found[1]);
- };
-
- var poundsOnlyParser = function (str) {
- var found = str.match(/^£(\d+)p?$/);
- if (found === null)
- throw new ParseError();
- else
- return parseInt(found[1] * 100);
- };
-
- var poundsAndPenceParser = function (str) {
- var found = str.match(/^£?(\d+(\.\d*))p?$/);
- if (found === null)
- throw new ParseError();
- else
- return Math.round(parseFloat(found[1]) * 100);
- };
-
- var parsers = [
- penceOnlyParser,
- poundsOnlyParser,
- poundsAndPenceParser
+ /**
+ * Array of recognised currency formats, each with a regex pattern
+ * and a parser function which receives the first matched group.
+ */
+ var formats = [
+ {
+ // Just pence, with optional 'p'
+ pattern: /^(\d+)p?$/,
+ parser: function (str) { return parseInt(str); }
+ },
+ {
+ // Just pounds, with '£' and optional 'p'
+ pattern: /^£(\d+)p?$/,
+ parser: function (str) { return parseInt(str) * 100; }
+ },
+ {
+ // Pounds and pence, with decimal point, and optional '£' and/or 'p'
+ pattern: /^£?(\d+(\.\d*))p?$/,
+ parser: function (str) { return Math.round(parseFloat(str) * 100); }
+ },
];
@@ ... @@
/**
- * Parse the supplied string as a number of British pence
- * @param {String} subject - The string to be parsed
- * @returns {Number} The value of the string in pence
+ * Parse the specified string and return a number of pence Sterling
+ * @param {String} input - The string to be parsed
+ * @returns {Number} Value in pence, or undefined if parsing failed
*/
- CurrencyParser.prototype.parseString = function(str) {
- for (var i = 0; i < parsers.length; i++) {
- try {
- var parser = parsers[i];
- return parser(str)
- } catch (e) {
- continue;
- }
+ CurrencyParser.prototype.parseString = function(input) {
+ for (var i = 0; i < formats.length; i++) {
+ var format = formats[i];
+ var matches = input.match(format.pattern);
+ if (matches)
+ return format.parser(matches[1]);
}
- // Return undefined if no parser succeeded
+ // Return undefined if no format was matched
};
|
--- a/js/app/Parser.js
+++ b/js/app/Parser.js
@@ -8,32 +8,22 @@
CON
DEL function ParseError() { }
DEL
DEL var penceOnlyParser = function (str) {
DEL var found = str.match(/^(\d+)p?$/);
DEL if (found === null)
DEL throw new ParseError();
DEL else
DEL return parseInt(found[1]);
DEL };
DEL
DEL var poundsOnlyParser = function (str) {
DEL var found = str.match(/^£(\d+)p?$/);
DEL if (found === null)
DEL throw new ParseError();
DEL else
DEL return parseInt(found[1] * 100);
DEL };
DEL
DEL var poundsAndPenceParser = function (str) {
DEL var found = str.match(/^£?(\d+(\.\d*))p?$/);
DEL if (found === null)
DEL throw new ParseError();
DEL else
DEL return Math.round(parseFloat(found[1]) * 100);
DEL };
DEL
DEL var parsers = [
DEL penceOnlyParser,
DEL poundsOnlyParser,
DEL poundsAndPenceParser
ADD /**
ADD * Array of recognised currency formats, each with a regex pattern
ADD * and a parser function which receives the first matched group.
ADD */
ADD var formats = [
ADD {
ADD // Just pence, with optional 'p'
ADD pattern: /^(\d+)p?$/,
ADD parser: function (str) { return parseInt(str); }
ADD },
ADD {
ADD // Just pounds, with '£' and optional 'p'
ADD pattern: /^£(\d+)p?$/,
ADD parser: function (str) { return parseInt(str) * 100; }
ADD },
ADD {
ADD // Pounds and pence, with decimal point, and optional '£' and/or 'p'
ADD pattern: /^£?(\d+(\.\d*))p?$/,
ADD parser: function (str) { return Math.round(parseFloat(str) * 100); }
ADD },
CON ];
@@ -41,17 +31,15 @@
CON /**
DEL * Parse the supplied string as a number of British pence
DEL * @param {String} subject - The string to be parsed
DEL * @returns {Number} The value of the string in pence
ADD * Parse the specified string and return a number of pence Sterling
ADD * @param {String} input - The string to be parsed
ADD * @returns {Number} Value in pence, or undefined if parsing failed
CON */
DEL CurrencyParser.prototype.parseString = function(str) {
DEL for (var i = 0; i < parsers.length; i++) {
DEL try {
DEL var parser = parsers[i];
DEL return parser(str)
DEL } catch (e) {
DEL continue;
DEL }
ADD CurrencyParser.prototype.parseString = function(input) {
ADD for (var i = 0; i < formats.length; i++) {
ADD var format = formats[i];
ADD var matches = input.match(format.pattern);
ADD if (matches)
ADD return format.parser(matches[1]);
CON }
CON
DEL // Return undefined if no parser succeeded
ADD // Return undefined if no format was matched
CON };
|
<<<<<<< SEARCH
function CurrencyParser() { }
function ParseError() { }
var penceOnlyParser = function (str) {
var found = str.match(/^(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1]);
};
var poundsOnlyParser = function (str) {
var found = str.match(/^£(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1] * 100);
};
var poundsAndPenceParser = function (str) {
var found = str.match(/^£?(\d+(\.\d*))p?$/);
if (found === null)
throw new ParseError();
else
return Math.round(parseFloat(found[1]) * 100);
};
var parsers = [
penceOnlyParser,
poundsOnlyParser,
poundsAndPenceParser
];
/**
* Parse the supplied string as a number of British pence
* @param {String} subject - The string to be parsed
* @returns {Number} The value of the string in pence
*/
CurrencyParser.prototype.parseString = function(str) {
for (var i = 0; i < parsers.length; i++) {
try {
var parser = parsers[i];
return parser(str)
} catch (e) {
continue;
}
}
// Return undefined if no parser succeeded
};
=======
function CurrencyParser() { }
/**
* Array of recognised currency formats, each with a regex pattern
* and a parser function which receives the first matched group.
*/
var formats = [
{
// Just pence, with optional 'p'
pattern: /^(\d+)p?$/,
parser: function (str) { return parseInt(str); }
},
{
// Just pounds, with '£' and optional 'p'
pattern: /^£(\d+)p?$/,
parser: function (str) { return parseInt(str) * 100; }
},
{
// Pounds and pence, with decimal point, and optional '£' and/or 'p'
pattern: /^£?(\d+(\.\d*))p?$/,
parser: function (str) { return Math.round(parseFloat(str) * 100); }
},
];
/**
* Parse the specified string and return a number of pence Sterling
* @param {String} input - The string to be parsed
* @returns {Number} Value in pence, or undefined if parsing failed
*/
CurrencyParser.prototype.parseString = function(input) {
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
var matches = input.match(format.pattern);
if (matches)
return format.parser(matches[1]);
}
// Return undefined if no format was matched
};
>>>>>>> REPLACE
|
wordpress-mobile/AztecEditor-Android
|
66206e671027fa062fd58a48c1a5cd789d024f5c
|
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
|
kotlin
|
mpl-2.0
|
Move rectangle to class variable for reuse
|
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.style.ImageSpan
class AztecCommentSpan(val context: Context, drawable: Drawable) : ImageSpan(drawable) {
companion object {
private val HTML_MORE: String = "more"
private val HTML_PAGE: String = "nextpage"
}
enum class Comment constructor(val html: String) {
MORE(HTML_MORE),
PAGE(HTML_PAGE)
}
override fun getSize(paint: Paint?, text: CharSequence?, start: Int, end: Int, metrics: Paint.FontMetricsInt?): Int {
val drawable = drawable
val bounds = getBounds(drawable)
if (metrics != null) {
metrics.ascent = -bounds.bottom
metrics.descent = 0
metrics.top = metrics.ascent
metrics.bottom = 0
}
return bounds.right
}
private fun getBounds(drawable: Drawable): Rect {
if (drawable.intrinsicWidth === 0) {
return Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
}
val width = context.resources.displayMetrics.widthPixels
val height = drawable.intrinsicHeight * width / drawable.intrinsicWidth
drawable.setBounds(0, 0, width, height)
return drawable.bounds
}
}
|
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.style.ImageSpan
class AztecCommentSpan(val context: Context, drawable: Drawable) : ImageSpan(drawable) {
companion object {
private val rect: Rect = Rect()
private val HTML_MORE: String = "more"
private val HTML_PAGE: String = "nextpage"
}
enum class Comment constructor(val html: String) {
MORE(HTML_MORE),
PAGE(HTML_PAGE)
}
override fun getSize(paint: Paint?, text: CharSequence?, start: Int, end: Int, metrics: Paint.FontMetricsInt?): Int {
val drawable = drawable
val bounds = getBounds(drawable)
if (metrics != null) {
metrics.ascent = -bounds.bottom
metrics.descent = 0
metrics.top = metrics.ascent
metrics.bottom = 0
}
return bounds.right
}
private fun getBounds(drawable: Drawable): Rect {
if (drawable.intrinsicWidth === 0) {
rect.set(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
return rect
}
val width = context.resources.displayMetrics.widthPixels
val height = drawable.intrinsicHeight * width / drawable.intrinsicWidth
drawable.setBounds(0, 0, width, height)
return drawable.bounds
}
}
| 3
| 1
| 2
|
mixed
|
--- a/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
+++ b/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
@@ -10,2 +10,3 @@
companion object {
+ private val rect: Rect = Rect()
private val HTML_MORE: String = "more"
@@ -36,3 +37,4 @@
if (drawable.intrinsicWidth === 0) {
- return Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
+ rect.set(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
+ return rect
}
|
--- a/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
+++ b/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
@@ ... @@
companion object {
+ private val rect: Rect = Rect()
private val HTML_MORE: String = "more"
@@ ... @@
if (drawable.intrinsicWidth === 0) {
- return Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
+ rect.set(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
+ return rect
}
|
--- a/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
+++ b/aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCommentSpan.kt
@@ -10,2 +10,3 @@
CON companion object {
ADD private val rect: Rect = Rect()
CON private val HTML_MORE: String = "more"
@@ -36,3 +37,4 @@
CON if (drawable.intrinsicWidth === 0) {
DEL return Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
ADD rect.set(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
ADD return rect
CON }
|
<<<<<<< SEARCH
class AztecCommentSpan(val context: Context, drawable: Drawable) : ImageSpan(drawable) {
companion object {
private val HTML_MORE: String = "more"
private val HTML_PAGE: String = "nextpage"
=======
class AztecCommentSpan(val context: Context, drawable: Drawable) : ImageSpan(drawable) {
companion object {
private val rect: Rect = Rect()
private val HTML_MORE: String = "more"
private val HTML_PAGE: String = "nextpage"
>>>>>>> REPLACE
<<<<<<< SEARCH
private fun getBounds(drawable: Drawable): Rect {
if (drawable.intrinsicWidth === 0) {
return Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
}
=======
private fun getBounds(drawable: Drawable): Rect {
if (drawable.intrinsicWidth === 0) {
rect.set(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
return rect
}
>>>>>>> REPLACE
|
lucthev/serialize-element
|
93ed00e3f05589358139c03bd4d1982aaaddc990
|
src/convert.js
|
javascript
|
mit
|
Apply markups from the outside in
|
'use strict';
module.exports = convert
var serializeInline = require('./inline').serializeInline
/**
* convert(elem, s) performs the actual work of converting an element
* into its abstract representation.
*
* @param {Element} elem
* @param {Serialize} s
*/
function convert (elem, s) {
var node = elem,
children = [],
info,
i
while (node) {
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
info = serializeInline(node)
for (i = 0; i < info.length; i += 1)
info[i].start = s.length
children.push(info)
node = node.firstChild
continue
}
if (node.nodeType === Node.TEXT_NODE)
s.text += node.data
else if (node.nodeName === 'BR')
s.text += '\n'
while (!node.nextSibling && node !== elem) {
info = children.pop()
for (i = 0; i < info.length; i += 1)
info[i].end = s.length
s.addMarkups(info)
node = node.parentNode
}
if (node === elem)
break
node = node.nextSibling
}
}
|
'use strict';
module.exports = convert
var serializeInline = require('./inline').serializeInline
/**
* convert(elem, s) performs the actual work of converting an element
* into its abstract representation.
*
* @param {Element} elem
* @param {Serialize} s
*/
function convert (elem, s) {
var allMarkups = [],
node = elem,
markups,
i
while (node) {
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
markups = serializeInline(node)
for (i = 0; i < markups.length; i += 1)
markups[i].start = s.length
allMarkups.push(markups)
node = node.firstChild
continue
}
if (node.nodeType === Node.TEXT_NODE)
s.text += node.data
else if (node.nodeName === 'BR')
s.text += '\n'
while (!node.nextSibling && node !== elem) {
markups = allMarkups.pop()
for (i = 0; i < markups.length; i += 1)
markups[i].end = s.length
allMarkups.unshift(markups)
node = node.parentNode
}
if (node === elem)
break
node = node.nextSibling
}
s.addMarkups(allMarkups.reduce(function (arr, markups) {
return arr.concat(markups)
}, []))
}
| 15
| 11
| 4
|
mixed
|
--- a/src/convert.js
+++ b/src/convert.js
@@ -14,5 +14,5 @@
function convert (elem, s) {
- var node = elem,
- children = [],
- info,
+ var allMarkups = [],
+ node = elem,
+ markups,
i
@@ -21,7 +21,7 @@
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
- info = serializeInline(node)
- for (i = 0; i < info.length; i += 1)
- info[i].start = s.length
+ markups = serializeInline(node)
+ for (i = 0; i < markups.length; i += 1)
+ markups[i].start = s.length
- children.push(info)
+ allMarkups.push(markups)
@@ -37,7 +37,7 @@
while (!node.nextSibling && node !== elem) {
- info = children.pop()
- for (i = 0; i < info.length; i += 1)
- info[i].end = s.length
+ markups = allMarkups.pop()
+ for (i = 0; i < markups.length; i += 1)
+ markups[i].end = s.length
- s.addMarkups(info)
+ allMarkups.unshift(markups)
@@ -51,2 +51,6 @@
}
+
+ s.addMarkups(allMarkups.reduce(function (arr, markups) {
+ return arr.concat(markups)
+ }, []))
}
|
--- a/src/convert.js
+++ b/src/convert.js
@@ ... @@
function convert (elem, s) {
- var node = elem,
- children = [],
- info,
+ var allMarkups = [],
+ node = elem,
+ markups,
i
@@ ... @@
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
- info = serializeInline(node)
- for (i = 0; i < info.length; i += 1)
- info[i].start = s.length
+ markups = serializeInline(node)
+ for (i = 0; i < markups.length; i += 1)
+ markups[i].start = s.length
- children.push(info)
+ allMarkups.push(markups)
@@ ... @@
while (!node.nextSibling && node !== elem) {
- info = children.pop()
- for (i = 0; i < info.length; i += 1)
- info[i].end = s.length
+ markups = allMarkups.pop()
+ for (i = 0; i < markups.length; i += 1)
+ markups[i].end = s.length
- s.addMarkups(info)
+ allMarkups.unshift(markups)
@@ ... @@
}
+
+ s.addMarkups(allMarkups.reduce(function (arr, markups) {
+ return arr.concat(markups)
+ }, []))
}
|
--- a/src/convert.js
+++ b/src/convert.js
@@ -14,5 +14,5 @@
CON function convert (elem, s) {
DEL var node = elem,
DEL children = [],
DEL info,
ADD var allMarkups = [],
ADD node = elem,
ADD markups,
CON i
@@ -21,7 +21,7 @@
CON if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
DEL info = serializeInline(node)
DEL for (i = 0; i < info.length; i += 1)
DEL info[i].start = s.length
ADD markups = serializeInline(node)
ADD for (i = 0; i < markups.length; i += 1)
ADD markups[i].start = s.length
CON
DEL children.push(info)
ADD allMarkups.push(markups)
CON
@@ -37,7 +37,7 @@
CON while (!node.nextSibling && node !== elem) {
DEL info = children.pop()
DEL for (i = 0; i < info.length; i += 1)
DEL info[i].end = s.length
ADD markups = allMarkups.pop()
ADD for (i = 0; i < markups.length; i += 1)
ADD markups[i].end = s.length
CON
DEL s.addMarkups(info)
ADD allMarkups.unshift(markups)
CON
@@ -51,2 +51,6 @@
CON }
ADD
ADD s.addMarkups(allMarkups.reduce(function (arr, markups) {
ADD return arr.concat(markups)
ADD }, []))
CON }
|
<<<<<<< SEARCH
*/
function convert (elem, s) {
var node = elem,
children = [],
info,
i
while (node) {
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
info = serializeInline(node)
for (i = 0; i < info.length; i += 1)
info[i].start = s.length
children.push(info)
node = node.firstChild
=======
*/
function convert (elem, s) {
var allMarkups = [],
node = elem,
markups,
i
while (node) {
if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) {
markups = serializeInline(node)
for (i = 0; i < markups.length; i += 1)
markups[i].start = s.length
allMarkups.push(markups)
node = node.firstChild
>>>>>>> REPLACE
<<<<<<< SEARCH
while (!node.nextSibling && node !== elem) {
info = children.pop()
for (i = 0; i < info.length; i += 1)
info[i].end = s.length
s.addMarkups(info)
node = node.parentNode
=======
while (!node.nextSibling && node !== elem) {
markups = allMarkups.pop()
for (i = 0; i < markups.length; i += 1)
markups[i].end = s.length
allMarkups.unshift(markups)
node = node.parentNode
>>>>>>> REPLACE
<<<<<<< SEARCH
node = node.nextSibling
}
}
=======
node = node.nextSibling
}
s.addMarkups(allMarkups.reduce(function (arr, markups) {
return arr.concat(markups)
}, []))
}
>>>>>>> REPLACE
|
bloder/Blorm
|
a13f95b9a5534ff27ebb5192773fab3bd8d65c45
|
blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
|
java
|
mit
|
Add is function with error message in blorm class
|
package br.com.bloder.blormlib;
import android.content.Context;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 05/06/16.
*/
public class Blorm {
public static class Builder {
private List<Validate> validations;
private View field;
public Builder() {
validations = new ArrayList<>();
}
public Builder field(View field) {
this.field = field;
return this;
}
public Builder is(Validate validation) {
this.validations.add(validation);
return this;
}
public Builder is(Validation validation) {
validation.field = this.field;
this.validations.add(validation.validate());
return this;
}
public void onSubmit(View submittedItem) {
new Blorm(this.validations).onSubmitted();
}
}
private List<Validate> validations;
public Blorm(List<Validate> validations) {
this.validations = validations;
}
private void onSubmitted() {
for(Validate validate : validations) {
if(validate.validate()) {
} else {
}
}
}
}
|
package br.com.bloder.blormlib;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 05/06/16.
*/
public class Blorm {
public static class Builder {
private List<Validate> validations;
private View field;
public Builder() {
validations = new ArrayList<>();
}
public Builder field(View field) {
this.field = field;
return this;
}
public Builder is(Validate validation) {
this.validations.add(validation);
return this;
}
public Builder is(Validation validation) {
validation.field = this.field;
this.validations.add(validation.validate());
return this;
}
public Builder is(String errorMessgae, Validation validation) {
validation.field = this.field;
validation.errorMessage = errorMessgae;
this.validations.add(validation.validate());
return this;
}
public void onSubmit(View submittedItem) {
new Blorm(this.validations).onSubmitted();
}
}
private List<Validate> validations;
public Blorm(List<Validate> validations) {
this.validations = validations;
}
private void onSubmitted() {
for(Validate validate : validations) {
if(!validate.validate()) {
validate.onError();
}
}
}
}
| 9
| 4
| 3
|
mixed
|
--- a/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
+++ b/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
@@ -2,5 +2,3 @@
-import android.content.Context;
import android.view.View;
-import android.widget.Toast;
@@ -42,2 +40,9 @@
+ public Builder is(String errorMessgae, Validation validation) {
+ validation.field = this.field;
+ validation.errorMessage = errorMessgae;
+ this.validations.add(validation.validate());
+ return this;
+ }
+
public void onSubmit(View submittedItem) {
@@ -55,4 +60,4 @@
for(Validate validate : validations) {
- if(validate.validate()) {
- } else {
+ if(!validate.validate()) {
+ validate.onError();
}
|
--- a/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
+++ b/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
@@ ... @@
-import android.content.Context;
import android.view.View;
-import android.widget.Toast;
@@ ... @@
+ public Builder is(String errorMessgae, Validation validation) {
+ validation.field = this.field;
+ validation.errorMessage = errorMessgae;
+ this.validations.add(validation.validate());
+ return this;
+ }
+
public void onSubmit(View submittedItem) {
@@ ... @@
for(Validate validate : validations) {
- if(validate.validate()) {
- } else {
+ if(!validate.validate()) {
+ validate.onError();
}
|
--- a/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
+++ b/blormlib/src/main/java/br/com/bloder/blormlib/Blorm.java
@@ -2,5 +2,3 @@
CON
DEL import android.content.Context;
CON import android.view.View;
DEL import android.widget.Toast;
CON
@@ -42,2 +40,9 @@
CON
ADD public Builder is(String errorMessgae, Validation validation) {
ADD validation.field = this.field;
ADD validation.errorMessage = errorMessgae;
ADD this.validations.add(validation.validate());
ADD return this;
ADD }
ADD
CON public void onSubmit(View submittedItem) {
@@ -55,4 +60,4 @@
CON for(Validate validate : validations) {
DEL if(validate.validate()) {
DEL } else {
ADD if(!validate.validate()) {
ADD validate.onError();
CON }
|
<<<<<<< SEARCH
package br.com.bloder.blormlib;
import android.content.Context;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
=======
package br.com.bloder.blormlib;
import android.view.View;
import java.util.ArrayList;
>>>>>>> REPLACE
<<<<<<< SEARCH
}
public void onSubmit(View submittedItem) {
new Blorm(this.validations).onSubmitted();
=======
}
public Builder is(String errorMessgae, Validation validation) {
validation.field = this.field;
validation.errorMessage = errorMessgae;
this.validations.add(validation.validate());
return this;
}
public void onSubmit(View submittedItem) {
new Blorm(this.validations).onSubmitted();
>>>>>>> REPLACE
<<<<<<< SEARCH
private void onSubmitted() {
for(Validate validate : validations) {
if(validate.validate()) {
} else {
}
}
=======
private void onSubmitted() {
for(Validate validate : validations) {
if(!validate.validate()) {
validate.onError();
}
}
>>>>>>> REPLACE
|
dimagi/commcare-hq
|
5874c5ec875c86e8fdb7fc36d130e4bd7d65ecfd
|
corehq/apps/reports/static/reports/js/base.js
|
javascript
|
bsd-3-clause
|
Remove .export-action-download now that reports.download_export.js is gone
|
hqDefine("reports/js/base", function() {
$(function() {
hqImport("reports/js/filters/main").init();
var initial_page_data = hqImport("hqwebapp/js/initial_page_data").get;
var defaultConfig = initial_page_data('default_config') || {};
if (initial_page_data('has_datespan')) {
defaultConfig.date_range = 'last7';
} else {
defaultConfig.date_range = null;
}
defaultConfig.has_ucr_datespan = false;
defaultConfig.datespan_filters = [];
defaultConfig.datespan_slug = null;
var $savedReports = $("#savedReports");
if ($savedReports.length) {
$savedReports.reportConfigEditor({
filterForm: $("#reportFilters"),
items: initial_page_data('report_configs'),
defaultItem: defaultConfig,
saveUrl: hqImport("hqwebapp/js/initial_page_data").reverse("add_report_config"),
});
}
$('#email-enabled').tooltip({
placement: 'right',
html: true,
title: gettext("You can email a saved version<br />of this report."),
});
$(document).on('click', '.export-action-download', function() {
var $modalBody = $("#export-download-status .modal-body");
$modalBody.text("Fetching...");
$("#export-download-status .modal-header h3 span").text($(this).data("formname"));
$.getJSON($(this).data('dlocation'), function(d) {
$modalBody.empty().load(d.download_url);
});
});
});
});
|
hqDefine("reports/js/base", function() {
$(function() {
hqImport("reports/js/filters/main").init();
var initial_page_data = hqImport("hqwebapp/js/initial_page_data").get;
var defaultConfig = initial_page_data('default_config') || {};
if (initial_page_data('has_datespan')) {
defaultConfig.date_range = 'last7';
} else {
defaultConfig.date_range = null;
}
defaultConfig.has_ucr_datespan = false;
defaultConfig.datespan_filters = [];
defaultConfig.datespan_slug = null;
var $savedReports = $("#savedReports");
if ($savedReports.length) {
$savedReports.reportConfigEditor({
filterForm: $("#reportFilters"),
items: initial_page_data('report_configs'),
defaultItem: defaultConfig,
saveUrl: hqImport("hqwebapp/js/initial_page_data").reverse("add_report_config"),
});
}
$('#email-enabled').tooltip({
placement: 'right',
html: true,
title: gettext("You can email a saved version<br />of this report."),
});
});
});
| 0
| 9
| 1
|
del_only
|
--- a/corehq/apps/reports/static/reports/js/base.js
+++ b/corehq/apps/reports/static/reports/js/base.js
@@ -30,11 +30,2 @@
});
-
- $(document).on('click', '.export-action-download', function() {
- var $modalBody = $("#export-download-status .modal-body");
- $modalBody.text("Fetching...");
- $("#export-download-status .modal-header h3 span").text($(this).data("formname"));
- $.getJSON($(this).data('dlocation'), function(d) {
- $modalBody.empty().load(d.download_url);
- });
- });
});
|
--- a/corehq/apps/reports/static/reports/js/base.js
+++ b/corehq/apps/reports/static/reports/js/base.js
@@ ... @@
});
-
- $(document).on('click', '.export-action-download', function() {
- var $modalBody = $("#export-download-status .modal-body");
- $modalBody.text("Fetching...");
- $("#export-download-status .modal-header h3 span").text($(this).data("formname"));
- $.getJSON($(this).data('dlocation'), function(d) {
- $modalBody.empty().load(d.download_url);
- });
- });
});
|
--- a/corehq/apps/reports/static/reports/js/base.js
+++ b/corehq/apps/reports/static/reports/js/base.js
@@ -30,11 +30,2 @@
CON });
DEL
DEL $(document).on('click', '.export-action-download', function() {
DEL var $modalBody = $("#export-download-status .modal-body");
DEL $modalBody.text("Fetching...");
DEL $("#export-download-status .modal-header h3 span").text($(this).data("formname"));
DEL $.getJSON($(this).data('dlocation'), function(d) {
DEL $modalBody.empty().load(d.download_url);
DEL });
DEL });
CON });
|
<<<<<<< SEARCH
title: gettext("You can email a saved version<br />of this report."),
});
$(document).on('click', '.export-action-download', function() {
var $modalBody = $("#export-download-status .modal-body");
$modalBody.text("Fetching...");
$("#export-download-status .modal-header h3 span").text($(this).data("formname"));
$.getJSON($(this).data('dlocation'), function(d) {
$modalBody.empty().load(d.download_url);
});
});
});
});
=======
title: gettext("You can email a saved version<br />of this report."),
});
});
});
>>>>>>> REPLACE
|
dodyg/Kotlin101
|
4650c0da62324b958162ea9ab58df41f2b8f27e5
|
src/Functions/Cascades.kt
|
kotlin
|
bsd-3-clause
|
Add sub object creation in with example
|
package Kotlin101.Functions.Cascades
fun main (Args : Array<String>){
/* This call utilizes extension function and infix call */
var superman = Superman() with {
name = "Lux Luthor"
punch()
kick()
}
}
public fun <T>T.with(operations : T.() -> Unit) : T {
this.operations()
return this
}
public class Superman() {
var name : String = "Clark Kent"
public fun punch() : Unit = println("$name punches")
public fun fly() : Unit = println("$name flies")
public fun kick() : Unit = println("$name kicks")
}
|
package Kotlin101.Functions.Cascades
fun main (Args : Array<String>){
/* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
var superman = Superman() with {
name = "Lux Luthor"
punch()
kick()
sidekick = Spiderman() with {
special()
}
}
}
public fun <T>T.with(operations : T.() -> Unit) : T {
this.operations()
return this
}
public class Superman() {
var name : String = "Clark Kent"
var sidekick : Sidekick = Robin()
public fun punch() : Unit = println("$name punches")
public fun fly() : Unit = println("$name flies")
public fun kick() : Unit = println("$name kicks")
}
trait Sidekick {
public abstract fun special()
}
public class Spiderman() : Sidekick {
var name : String = "Peter Parker"
override fun special() = println("$name webs")
}
public class Robin() : Sidekick {
var name : String = "Robin"
override fun special() = println("$name is useless")
}
| 19
| 1
| 4
|
mixed
|
--- a/src/Functions/Cascades.kt
+++ b/src/Functions/Cascades.kt
@@ -3,3 +3,3 @@
fun main (Args : Array<String>){
- /* This call utilizes extension function and infix call */
+ /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
var superman = Superman() with {
@@ -8,2 +8,5 @@
kick()
+ sidekick = Spiderman() with {
+ special()
+ }
}
@@ -18,2 +21,3 @@
var name : String = "Clark Kent"
+ var sidekick : Sidekick = Robin()
@@ -23 +27,15 @@
}
+
+trait Sidekick {
+ public abstract fun special()
+}
+
+public class Spiderman() : Sidekick {
+ var name : String = "Peter Parker"
+ override fun special() = println("$name webs")
+}
+
+public class Robin() : Sidekick {
+ var name : String = "Robin"
+ override fun special() = println("$name is useless")
+}
|
--- a/src/Functions/Cascades.kt
+++ b/src/Functions/Cascades.kt
@@ ... @@
fun main (Args : Array<String>){
- /* This call utilizes extension function and infix call */
+ /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
var superman = Superman() with {
@@ ... @@
kick()
+ sidekick = Spiderman() with {
+ special()
+ }
}
@@ ... @@
var name : String = "Clark Kent"
+ var sidekick : Sidekick = Robin()
@@ ... @@
}
+
+trait Sidekick {
+ public abstract fun special()
+}
+
+public class Spiderman() : Sidekick {
+ var name : String = "Peter Parker"
+ override fun special() = println("$name webs")
+}
+
+public class Robin() : Sidekick {
+ var name : String = "Robin"
+ override fun special() = println("$name is useless")
+}
|
--- a/src/Functions/Cascades.kt
+++ b/src/Functions/Cascades.kt
@@ -3,3 +3,3 @@
CON fun main (Args : Array<String>){
DEL /* This call utilizes extension function and infix call */
ADD /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
CON var superman = Superman() with {
@@ -8,2 +8,5 @@
CON kick()
ADD sidekick = Spiderman() with {
ADD special()
ADD }
CON }
@@ -18,2 +21,3 @@
CON var name : String = "Clark Kent"
ADD var sidekick : Sidekick = Robin()
CON
@@ -23 +27,15 @@
CON }
ADD
ADD trait Sidekick {
ADD public abstract fun special()
ADD }
ADD
ADD public class Spiderman() : Sidekick {
ADD var name : String = "Peter Parker"
ADD override fun special() = println("$name webs")
ADD }
ADD
ADD public class Robin() : Sidekick {
ADD var name : String = "Robin"
ADD override fun special() = println("$name is useless")
ADD }
|
<<<<<<< SEARCH
fun main (Args : Array<String>){
/* This call utilizes extension function and infix call */
var superman = Superman() with {
name = "Lux Luthor"
punch()
kick()
}
}
=======
fun main (Args : Array<String>){
/* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
var superman = Superman() with {
name = "Lux Luthor"
punch()
kick()
sidekick = Spiderman() with {
special()
}
}
}
>>>>>>> REPLACE
<<<<<<< SEARCH
public class Superman() {
var name : String = "Clark Kent"
public fun punch() : Unit = println("$name punches")
public fun fly() : Unit = println("$name flies")
public fun kick() : Unit = println("$name kicks")
}
=======
public class Superman() {
var name : String = "Clark Kent"
var sidekick : Sidekick = Robin()
public fun punch() : Unit = println("$name punches")
public fun fly() : Unit = println("$name flies")
public fun kick() : Unit = println("$name kicks")
}
trait Sidekick {
public abstract fun special()
}
public class Spiderman() : Sidekick {
var name : String = "Peter Parker"
override fun special() = println("$name webs")
}
public class Robin() : Sidekick {
var name : String = "Robin"
override fun special() = println("$name is useless")
}
>>>>>>> REPLACE
|
axelrindle/Broadcaster-Plugin
|
402b619aaf327932705fe8476d01af6d693a0ac9
|
src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
|
kotlin
|
mit
|
Test whether required class exists
|
package de.axelrindle.broadcaster.model
import net.md_5.bungee.api.chat.BaseComponent
import net.md_5.bungee.chat.ComponentSerializer
/**
* A `Message` describes a piece of information that will be broadcasted around the server.
*/
abstract class Message
/**
* @param input The input text used for configuration.
*/
(protected val input: String)
/**
* A `SimpleMessage` is just a container for holding a plain text message.
*/
class SimpleMessage(input: String) : Message(input) {
/**
* Returns just the input string to use as the message text.
*
* @return The [input].
*/
fun getText(): String = input
}
/**
* A `JsonMessage` is created from a json string and converted into an [Array] of [BaseComponent]s.
*
* @see ComponentSerializer.parse
* @see BaseComponent
*/
class JsonMessage(input: String) : Message(input) {
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
}
|
package de.axelrindle.broadcaster.model
import net.md_5.bungee.api.chat.BaseComponent
import net.md_5.bungee.chat.ComponentSerializer
/**
* A `Message` describes a piece of information that will be broadcasted around the server.
*/
abstract class Message
/**
* @param input The input text used for configuration.
*/
(protected val input: String)
/**
* A `SimpleMessage` is just a container for holding a plain text message.
*/
class SimpleMessage(input: String) : Message(input) {
/**
* Returns just the input string to use as the message text.
*
* @return The [input].
*/
fun getText(): String = input
}
/**
* A `JsonMessage` is created from a json string and converted into an [Array] of [BaseComponent]s.
*
* @see ComponentSerializer.parse
* @see BaseComponent
*/
class JsonMessage(input: String) : Message(input) {
// test for class dependency
init {
Class.forName("net.md_5.bungee.chat.ComponentSerializer")
}
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
}
| 6
| 0
| 1
|
add_only
|
--- a/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
+++ b/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
@@ -34,2 +34,8 @@
class JsonMessage(input: String) : Message(input) {
+
+ // test for class dependency
+ init {
+ Class.forName("net.md_5.bungee.chat.ComponentSerializer")
+ }
+
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
|
--- a/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
+++ b/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
@@ ... @@
class JsonMessage(input: String) : Message(input) {
+
+ // test for class dependency
+ init {
+ Class.forName("net.md_5.bungee.chat.ComponentSerializer")
+ }
+
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
|
--- a/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
+++ b/src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
@@ -34,2 +34,8 @@
CON class JsonMessage(input: String) : Message(input) {
ADD
ADD // test for class dependency
ADD init {
ADD Class.forName("net.md_5.bungee.chat.ComponentSerializer")
ADD }
ADD
CON val components: Array<BaseComponent> = ComponentSerializer.parse(input)
|
<<<<<<< SEARCH
*/
class JsonMessage(input: String) : Message(input) {
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
}
=======
*/
class JsonMessage(input: String) : Message(input) {
// test for class dependency
init {
Class.forName("net.md_5.bungee.chat.ComponentSerializer")
}
val components: Array<BaseComponent> = ComponentSerializer.parse(input)
}
>>>>>>> REPLACE
|
GlobalDigitalLibraryio/gdl-frontend
|
c3cff4e9d2b06ba41b31eeec50d782bb30ad5424
|
packages/gdl-frontend/components/NotFound/index.js
|
javascript
|
apache-2.0
|
Add container spacing to 404 page
|
// @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2018 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Taken from './Taken';
import { Trans } from '@lingui/react';
import Link from 'next/link';
import { Typography } from '@material-ui/core';
import Container from '../../elements/Container';
import A from '../../elements/A';
import Head from '../Head';
import Layout from '../Layout';
import { spacing } from '../../style/theme/';
const NotFound = () => (
<Layout>
<Head title="Page not found" />
<Container>
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
</Typography>
<Typography
component="h2"
align="center"
variant="subheading"
gutterBottom
>
<Trans>The page you were looking for was taken by a 404.</Trans>
</Typography>
<div
css={{
textAlign: 'center',
marginTop: spacing.medium,
marginBottom: spacing.medium
}}
>
<Taken height="100%" />
</div>
<Link href="/" passHref>
<A align="center">
<Trans>Take me home</Trans>
</A>
</Link>
</Container>
</Layout>
);
export default NotFound;
|
// @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2018 GDL
*
* See LICENSE
*/
import * as React from 'react';
import Taken from './Taken';
import { Trans } from '@lingui/react';
import Link from 'next/link';
import { Typography } from '@material-ui/core';
import Container from '../../elements/Container';
import A from '../../elements/A';
import Head from '../Head';
import Layout from '../Layout';
import { spacing } from '../../style/theme/';
const NotFound = () => (
<Layout>
<Head title="Page not found" />
<Container my="30px">
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
</Typography>
<Typography
component="h2"
align="center"
variant="subheading"
gutterBottom
>
<Trans>The page you were looking for was taken by a 404.</Trans>
</Typography>
<div
css={{
textAlign: 'center',
marginTop: spacing.medium,
marginBottom: spacing.medium
}}
>
<Taken height="100%" />
</div>
<Link href="/" passHref>
<A align="center">
<Trans>Take me home</Trans>
</A>
</Link>
</Container>
</Layout>
);
export default NotFound;
| 1
| 1
| 1
|
mixed
|
--- a/packages/gdl-frontend/components/NotFound/index.js
+++ b/packages/gdl-frontend/components/NotFound/index.js
@@ -23,3 +23,3 @@
<Head title="Page not found" />
- <Container>
+ <Container my="30px">
<Typography component="h1" align="center" variant="headline" gutterBottom>
|
--- a/packages/gdl-frontend/components/NotFound/index.js
+++ b/packages/gdl-frontend/components/NotFound/index.js
@@ ... @@
<Head title="Page not found" />
- <Container>
+ <Container my="30px">
<Typography component="h1" align="center" variant="headline" gutterBottom>
|
--- a/packages/gdl-frontend/components/NotFound/index.js
+++ b/packages/gdl-frontend/components/NotFound/index.js
@@ -23,3 +23,3 @@
CON <Head title="Page not found" />
DEL <Container>
ADD <Container my="30px">
CON <Typography component="h1" align="center" variant="headline" gutterBottom>
|
<<<<<<< SEARCH
<Layout>
<Head title="Page not found" />
<Container>
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
=======
<Layout>
<Head title="Page not found" />
<Container my="30px">
<Typography component="h1" align="center" variant="headline" gutterBottom>
<Trans>Oh no!</Trans>
>>>>>>> REPLACE
|
rust-analyzer/rust-analyzer
|
0b9cd8a468d63ebda3d7955faf92296d1abcdac0
|
crates/rust-analyzer/src/task_pool.rs
|
rust
|
apache-2.0
|
Increase worker thread stack and name them
|
//! A thin wrapper around `ThreadPool` to make sure that we join all things
//! properly.
use crossbeam_channel::Sender;
pub(crate) struct TaskPool<T> {
sender: Sender<T>,
inner: threadpool::ThreadPool,
}
impl<T> TaskPool<T> {
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
TaskPool { sender, inner: threadpool::ThreadPool::default() }
}
pub(crate) fn spawn<F>(&mut self, task: F)
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
self.inner.execute({
let sender = self.sender.clone();
move || sender.send(task()).unwrap()
})
}
pub(crate) fn spawn_with_sender<F>(&mut self, task: F)
where
F: FnOnce(Sender<T>) + Send + 'static,
T: Send + 'static,
{
self.inner.execute({
let sender = self.sender.clone();
move || task(sender)
})
}
pub(crate) fn len(&self) -> usize {
self.inner.queued_count()
}
}
impl<T> Drop for TaskPool<T> {
fn drop(&mut self) {
self.inner.join()
}
}
|
//! A thin wrapper around `ThreadPool` to make sure that we join all things
//! properly.
use crossbeam_channel::Sender;
pub(crate) struct TaskPool<T> {
sender: Sender<T>,
inner: threadpool::ThreadPool,
}
impl<T> TaskPool<T> {
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
const STACK_SIZE: usize = 8 * 1024 * 1024;
let inner = threadpool::Builder::new()
.thread_name("Worker".into())
.thread_stack_size(STACK_SIZE)
.build();
TaskPool { sender, inner }
}
pub(crate) fn spawn<F>(&mut self, task: F)
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
self.inner.execute({
let sender = self.sender.clone();
move || sender.send(task()).unwrap()
})
}
pub(crate) fn spawn_with_sender<F>(&mut self, task: F)
where
F: FnOnce(Sender<T>) + Send + 'static,
T: Send + 'static,
{
self.inner.execute({
let sender = self.sender.clone();
move || task(sender)
})
}
pub(crate) fn len(&self) -> usize {
self.inner.queued_count()
}
}
impl<T> Drop for TaskPool<T> {
fn drop(&mut self) {
self.inner.join()
}
}
| 7
| 1
| 1
|
mixed
|
--- a/crates/rust-analyzer/src/task_pool.rs
+++ b/crates/rust-analyzer/src/task_pool.rs
@@ -11,3 +11,9 @@
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
- TaskPool { sender, inner: threadpool::ThreadPool::default() }
+ const STACK_SIZE: usize = 8 * 1024 * 1024;
+
+ let inner = threadpool::Builder::new()
+ .thread_name("Worker".into())
+ .thread_stack_size(STACK_SIZE)
+ .build();
+ TaskPool { sender, inner }
}
|
--- a/crates/rust-analyzer/src/task_pool.rs
+++ b/crates/rust-analyzer/src/task_pool.rs
@@ ... @@
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
- TaskPool { sender, inner: threadpool::ThreadPool::default() }
+ const STACK_SIZE: usize = 8 * 1024 * 1024;
+
+ let inner = threadpool::Builder::new()
+ .thread_name("Worker".into())
+ .thread_stack_size(STACK_SIZE)
+ .build();
+ TaskPool { sender, inner }
}
|
--- a/crates/rust-analyzer/src/task_pool.rs
+++ b/crates/rust-analyzer/src/task_pool.rs
@@ -11,3 +11,9 @@
CON pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
DEL TaskPool { sender, inner: threadpool::ThreadPool::default() }
ADD const STACK_SIZE: usize = 8 * 1024 * 1024;
ADD
ADD let inner = threadpool::Builder::new()
ADD .thread_name("Worker".into())
ADD .thread_stack_size(STACK_SIZE)
ADD .build();
ADD TaskPool { sender, inner }
CON }
|
<<<<<<< SEARCH
impl<T> TaskPool<T> {
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
TaskPool { sender, inner: threadpool::ThreadPool::default() }
}
=======
impl<T> TaskPool<T> {
pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {
const STACK_SIZE: usize = 8 * 1024 * 1024;
let inner = threadpool::Builder::new()
.thread_name("Worker".into())
.thread_stack_size(STACK_SIZE)
.build();
TaskPool { sender, inner }
}
>>>>>>> REPLACE
|
us-ignite/us_ignite
|
cfc50cb9e70b7a5358b36a54d4b3bc27a2cfb2cb
|
us_ignite/common/sanitizer.py
|
python
|
bsd-3-clause
|
Allow ``table`` attributes during HTML sanitation.
Tables are part of the content expected to be added
in some of the resources in the site.
|
import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
'h3',
'h4',
'h5',
'h6',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym': ['title'],
}
ALLOWED_STYLES = []
def sanitize(text):
"""Cleans the HTML received."""
cleaned_text = bleach.clean(
text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=True)
return cleaned_text
|
import bleach
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
'p',
'br',
'h3',
'h4',
'h5',
'h6',
'table',
'tr',
'th',
'td',
]
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'abbr': ['title'],
'acronym': ['title'],
}
ALLOWED_STYLES = []
def sanitize(text):
"""Cleans the HTML received."""
cleaned_text = bleach.clean(
text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=True)
return cleaned_text
| 4
| 0
| 1
|
add_only
|
--- a/us_ignite/common/sanitizer.py
+++ b/us_ignite/common/sanitizer.py
@@ -21,2 +21,6 @@
'h6',
+ 'table',
+ 'tr',
+ 'th',
+ 'td',
]
|
--- a/us_ignite/common/sanitizer.py
+++ b/us_ignite/common/sanitizer.py
@@ ... @@
'h6',
+ 'table',
+ 'tr',
+ 'th',
+ 'td',
]
|
--- a/us_ignite/common/sanitizer.py
+++ b/us_ignite/common/sanitizer.py
@@ -21,2 +21,6 @@
CON 'h6',
ADD 'table',
ADD 'tr',
ADD 'th',
ADD 'td',
CON ]
|
<<<<<<< SEARCH
'h5',
'h6',
]
=======
'h5',
'h6',
'table',
'tr',
'th',
'td',
]
>>>>>>> REPLACE
|
krsnik02/rust-http
|
879bd24d4e892da317cff1fdcece9af0765b87a9
|
src/lib.rs
|
rust
|
mit
|
Use io::Error instead of custom error type
|
extern crate mio;
use std::io;
use std::result;
use std::net::{SocketAddr, ToSocketAddrs};
use mio::{EventLoop, Handler, Token};
use mio::tcp::{TcpListener, TcpStream};
#[derive(Debug)]
pub struct HttpError;
pub type Result<T> = result::Result<T, HttpError>;
pub struct HttpConnection {
tcp_stream: TcpStream,
}
impl HttpConnection {
pub fn local_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.local_addr()
.map_err(|_| HttpError)
}
pub fn peer_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.peer_addr()
.map_err(|_| HttpError)
}
}
pub struct HttpServer {
tcp_listener: TcpListener,
}
impl HttpServer {
pub fn bind<A: ToSocketAddrs>( addr: A ) -> Result<HttpServer> {
unimplemented!()
}
pub fn accept(&self) -> Result<Option<HttpConnection>> {
unimplemented!()
}
/// Registers itself on the given `EventLoop`.
pub fn register_self<H : Handler>(
&self, event_loop: &mut EventLoop<H>, token: Token)
-> io::Result<()> {
event_loop.register(&self.tcp_listener, token)
}
}
|
extern crate mio;
use std::io::Result;
use std::net::{SocketAddr, ToSocketAddrs};
use mio::{EventLoop, Handler, Token};
use mio::tcp::{TcpListener, TcpStream};
pub struct HttpConnection {
tcp_stream: TcpStream,
}
impl HttpConnection {
pub fn local_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.local_addr()
}
pub fn peer_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.peer_addr()
}
}
pub struct HttpServer {
tcp_listener: TcpListener,
}
impl HttpServer {
pub fn bind<A: ToSocketAddrs>( addr: A ) -> Result<HttpServer> {
unimplemented!()
}
pub fn accept(&self) -> Result<Option<HttpConnection>> {
unimplemented!()
}
/// Registers itself on the given `EventLoop`.
pub fn register_self<H : Handler>(
&self, event_loop: &mut EventLoop<H>, token: Token) -> Result<()> {
event_loop.register(&self.tcp_listener, token)
}
}
| 2
| 12
| 5
|
mixed
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,4 +2,3 @@
-use std::io;
-use std::result;
+use std::io::Result;
use std::net::{SocketAddr, ToSocketAddrs};
@@ -7,8 +6,2 @@
use mio::tcp::{TcpListener, TcpStream};
-
-#[derive(Debug)]
-pub struct HttpError;
-
-pub type Result<T> = result::Result<T, HttpError>;
-
@@ -21,3 +14,2 @@
self.tcp_stream.local_addr()
- .map_err(|_| HttpError)
}
@@ -26,3 +18,2 @@
self.tcp_stream.peer_addr()
- .map_err(|_| HttpError)
}
@@ -48,4 +39,3 @@
pub fn register_self<H : Handler>(
- &self, event_loop: &mut EventLoop<H>, token: Token)
- -> io::Result<()> {
+ &self, event_loop: &mut EventLoop<H>, token: Token) -> Result<()> {
event_loop.register(&self.tcp_listener, token)
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
-use std::io;
-use std::result;
+use std::io::Result;
use std::net::{SocketAddr, ToSocketAddrs};
@@ ... @@
use mio::tcp::{TcpListener, TcpStream};
-
-#[derive(Debug)]
-pub struct HttpError;
-
-pub type Result<T> = result::Result<T, HttpError>;
-
@@ ... @@
self.tcp_stream.local_addr()
- .map_err(|_| HttpError)
}
@@ ... @@
self.tcp_stream.peer_addr()
- .map_err(|_| HttpError)
}
@@ ... @@
pub fn register_self<H : Handler>(
- &self, event_loop: &mut EventLoop<H>, token: Token)
- -> io::Result<()> {
+ &self, event_loop: &mut EventLoop<H>, token: Token) -> Result<()> {
event_loop.register(&self.tcp_listener, token)
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,4 +2,3 @@
CON
DEL use std::io;
DEL use std::result;
ADD use std::io::Result;
CON use std::net::{SocketAddr, ToSocketAddrs};
@@ -7,8 +6,2 @@
CON use mio::tcp::{TcpListener, TcpStream};
DEL
DEL #[derive(Debug)]
DEL pub struct HttpError;
DEL
DEL pub type Result<T> = result::Result<T, HttpError>;
DEL
CON
@@ -21,3 +14,2 @@
CON self.tcp_stream.local_addr()
DEL .map_err(|_| HttpError)
CON }
@@ -26,3 +18,2 @@
CON self.tcp_stream.peer_addr()
DEL .map_err(|_| HttpError)
CON }
@@ -48,4 +39,3 @@
CON pub fn register_self<H : Handler>(
DEL &self, event_loop: &mut EventLoop<H>, token: Token)
DEL -> io::Result<()> {
ADD &self, event_loop: &mut EventLoop<H>, token: Token) -> Result<()> {
CON event_loop.register(&self.tcp_listener, token)
|
<<<<<<< SEARCH
extern crate mio;
use std::io;
use std::result;
use std::net::{SocketAddr, ToSocketAddrs};
use mio::{EventLoop, Handler, Token};
use mio::tcp::{TcpListener, TcpStream};
#[derive(Debug)]
pub struct HttpError;
pub type Result<T> = result::Result<T, HttpError>;
pub struct HttpConnection {
=======
extern crate mio;
use std::io::Result;
use std::net::{SocketAddr, ToSocketAddrs};
use mio::{EventLoop, Handler, Token};
use mio::tcp::{TcpListener, TcpStream};
pub struct HttpConnection {
>>>>>>> REPLACE
<<<<<<< SEARCH
pub fn local_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.local_addr()
.map_err(|_| HttpError)
}
pub fn peer_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.peer_addr()
.map_err(|_| HttpError)
}
}
=======
pub fn local_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.local_addr()
}
pub fn peer_addr(&self) -> Result<SocketAddr> {
self.tcp_stream.peer_addr()
}
}
>>>>>>> REPLACE
<<<<<<< SEARCH
/// Registers itself on the given `EventLoop`.
pub fn register_self<H : Handler>(
&self, event_loop: &mut EventLoop<H>, token: Token)
-> io::Result<()> {
event_loop.register(&self.tcp_listener, token)
}
=======
/// Registers itself on the given `EventLoop`.
pub fn register_self<H : Handler>(
&self, event_loop: &mut EventLoop<H>, token: Token) -> Result<()> {
event_loop.register(&self.tcp_listener, token)
}
>>>>>>> REPLACE
|
bradojevic/django-action-log
|
f941989ef9663ebbb3ba33709dd3c723c86bd2cc
|
action_log/views.py
|
python
|
mit
|
Make it DESC order by id.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all()
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all().order_by('-id')
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
| 1
| 1
| 1
|
mixed
|
--- a/action_log/views.py
+++ b/action_log/views.py
@@ -28,3 +28,3 @@
# filter out records
- records = ActionRecord.objects.all()
+ records = ActionRecord.objects.all().order_by('-id')
if action is not None:
|
--- a/action_log/views.py
+++ b/action_log/views.py
@@ ... @@
# filter out records
- records = ActionRecord.objects.all()
+ records = ActionRecord.objects.all().order_by('-id')
if action is not None:
|
--- a/action_log/views.py
+++ b/action_log/views.py
@@ -28,3 +28,3 @@
CON # filter out records
DEL records = ActionRecord.objects.all()
ADD records = ActionRecord.objects.all().order_by('-id')
CON if action is not None:
|
<<<<<<< SEARCH
# filter out records
records = ActionRecord.objects.all()
if action is not None:
records = records.filter(action_type__name=action)
=======
# filter out records
records = ActionRecord.objects.all().order_by('-id')
if action is not None:
records = records.filter(action_type__name=action)
>>>>>>> REPLACE
|
chirino/proton
|
9c3a714f587ff8953f017cc533ef2e55fd6c08e0
|
proton-j/src/org/apache/qpid/proton/engine/Transport.java
|
java
|
apache-2.0
|
Add constant definition for Proton end of stream
git-svn-id: 33ed6c3feaacb64944efc691d1ae8e09b17f2bf9@1343343 13f79535-47bb-0310-9956-ffa450edef68
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.proton.engine;
/**
* Transport
*
* @opt operations
* @opt types
*
*/
public interface Transport extends Endpoint
{
/**
* @param bytes input bytes for consumption
* @param offset the offset within bytes where input begins
* @param size the number of bytes available for input
*
* @return the number of bytes consumed
*/
public int input(byte[] bytes, int offset, int size);
/**
* @param bytes array for output bytes
* @param offset the offset within bytes where output begins
* @param size the number of bytes available for output
*
* @return the number of bytes written
*/
public int output(byte[] bytes, int offset, int size);
}
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.proton.engine;
/**
* Transport
*
* @opt operations
* @opt types
*
*/
public interface Transport extends Endpoint
{
public int END_OF_STREAM = -1;
/**
* @param bytes input bytes for consumption
* @param offset the offset within bytes where input begins
* @param size the number of bytes available for input
*
* @return the number of bytes consumed
*/
public int input(byte[] bytes, int offset, int size);
/**
* @param bytes array for output bytes
* @param offset the offset within bytes where output begins
* @param size the number of bytes available for output
*
* @return the number of bytes written
*/
public int output(byte[] bytes, int offset, int size);
}
| 1
| 0
| 1
|
add_only
|
--- a/proton-j/src/org/apache/qpid/proton/engine/Transport.java
+++ b/proton-j/src/org/apache/qpid/proton/engine/Transport.java
@@ -34,2 +34,3 @@
+ public int END_OF_STREAM = -1;
/**
|
--- a/proton-j/src/org/apache/qpid/proton/engine/Transport.java
+++ b/proton-j/src/org/apache/qpid/proton/engine/Transport.java
@@ ... @@
+ public int END_OF_STREAM = -1;
/**
|
--- a/proton-j/src/org/apache/qpid/proton/engine/Transport.java
+++ b/proton-j/src/org/apache/qpid/proton/engine/Transport.java
@@ -34,2 +34,3 @@
CON
ADD public int END_OF_STREAM = -1;
CON /**
|
<<<<<<< SEARCH
{
/**
* @param bytes input bytes for consumption
=======
{
public int END_OF_STREAM = -1;
/**
* @param bytes input bytes for consumption
>>>>>>> REPLACE
|
oliversalzburg/sanitizr
|
cb8d8bdf4b8431fccb7e40dcd6a0c733bc74e4e9
|
index.js
|
javascript
|
mit
|
[FEATURE] Put commonly used constants on main export
|
"use strict";
var TypeDecorator = require( "./lib/type/decorator" );
var TypeHelper = require( "./lib/type/helper" );
var TypeInfo = require( "./lib/type/info" );
module.exports = {
DecoratorError : require( "./lib/error/decorator" ),
HelperError : require( "./lib/error/helper" ),
ChangeSet : require( "./lib/history/changeset" ),
Conductor : require( "./lib/transaction/conductor" ),
WebSockets : require( "./lib/transaction/websockets" ),
TypeDecorator : TypeDecorator,
Factory : require( "./lib/type/factory" ),
TypeHelper : TypeHelper,
TypeInfo : TypeInfo,
Type : require( "./lib/type/type" ),
decorate : decorate,
info : info,
helper : helper
};
function decorate( type ) {
return new TypeDecorator( type );
}
function info( typeName, type ) {
return new TypeInfo( typeName, type );
}
function helper( typeInfo ) {
return new TypeHelper( typeInfo );
}
|
"use strict";
var TypeDecorator = require( "./lib/type/decorator" );
var TypeHelper = require( "./lib/type/helper" );
var TypeInfo = require( "./lib/type/info" );
module.exports = {
DecoratorError : require( "./lib/error/decorator" ),
HelperError : require( "./lib/error/helper" ),
ChangeSet : require( "./lib/history/changeset" ),
Conductor : require( "./lib/transaction/conductor" ),
WebSockets : require( "./lib/transaction/websockets" ),
TypeDecorator : TypeDecorator,
Factory : require( "./lib/type/factory" ),
TypeHelper : TypeHelper,
TypeInfo : TypeInfo,
Type : require( "./lib/type/type" ),
decorate : decorate,
info : info,
helper : helper
};
function decorate( type ) {
return new TypeDecorator( type );
}
function info( typeName, type ) {
return new TypeInfo( typeName, type );
}
function helper( typeInfo ) {
return new TypeHelper( typeInfo );
}
module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
module.exports.CONCEALED = TypeInfo.CONCEALED;
module.exports.HIDDEN = TypeInfo.HIDDEN;
module.exports.READ_ONLY = TypeInfo.READ_ONLY;
| 7
| 0
| 1
|
add_only
|
--- a/index.js
+++ b/index.js
@@ -37 +37,8 @@
}
+
+module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
+module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
+
+module.exports.CONCEALED = TypeInfo.CONCEALED;
+module.exports.HIDDEN = TypeInfo.HIDDEN;
+module.exports.READ_ONLY = TypeInfo.READ_ONLY;
|
--- a/index.js
+++ b/index.js
@@ ... @@
}
+
+module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
+module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
+
+module.exports.CONCEALED = TypeInfo.CONCEALED;
+module.exports.HIDDEN = TypeInfo.HIDDEN;
+module.exports.READ_ONLY = TypeInfo.READ_ONLY;
|
--- a/index.js
+++ b/index.js
@@ -37 +37,8 @@
CON }
ADD
ADD module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
ADD module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
ADD
ADD module.exports.CONCEALED = TypeInfo.CONCEALED;
ADD module.exports.HIDDEN = TypeInfo.HIDDEN;
ADD module.exports.READ_ONLY = TypeInfo.READ_ONLY;
|
<<<<<<< SEARCH
return new TypeHelper( typeInfo );
}
=======
return new TypeHelper( typeInfo );
}
module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
module.exports.CONCEALED = TypeInfo.CONCEALED;
module.exports.HIDDEN = TypeInfo.HIDDEN;
module.exports.READ_ONLY = TypeInfo.READ_ONLY;
>>>>>>> REPLACE
|
dtolnay/syn
|
48e29168861ef1770e48d59e587e9b4fb4240671
|
tests/test_parse_buffer.rs
|
rust
|
apache-2.0
|
Add speculative smuggling test between bracket contexts
|
extern crate syn;
use syn::{
parse::{Parse, ParseStream},
parse::discouraged::Speculative,
Result,
};
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor() {
struct Smuggled(ParseStream<'static>);
impl Parse for Smuggled {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Smuggled(unsafe { std::mem::transmute_copy(input) }))
}
}
struct BreakRules;
impl Parse for BreakRules {
fn parse(input: ParseStream) -> Result<Self> {
let Smuggled(fork) = syn::parse_str("").unwrap();
input.advance_to(fork);
Ok(Self)
}
}
syn::parse_str::<BreakRules>("").unwrap();
}
|
#[macro_use]
extern crate syn;
use syn::{
parse::{Parse, ParseStream},
parse::discouraged::Speculative,
Result,
};
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor_between_sources() {
// don't do this ever this is very unsafe and fails anyway
struct Smuggled(ParseStream<'static>);
impl Parse for Smuggled {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Smuggled(unsafe { std::mem::transmute_copy(input) }))
}
}
struct BreakRules;
impl Parse for BreakRules {
fn parse(input: ParseStream) -> Result<Self> {
let Smuggled(fork) = syn::parse_str("").unwrap();
input.advance_to(fork);
Ok(Self)
}
}
syn::parse_str::<BreakRules>("").unwrap();
}
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor_between_brackets() {
struct BreakRules;
impl Parse for BreakRules {
fn parse(input: ParseStream) -> Result<Self> {
let a;
let b;
parenthesized!(a in input);
parenthesized!(b in input);
a.advance_to(&b);
Ok(Self)
}
}
syn::parse_str::<BreakRules>("()()").unwrap();
}
| 21
| 1
| 3
|
mixed
|
--- a/tests/test_parse_buffer.rs
+++ b/tests/test_parse_buffer.rs
@@ -1 +1,2 @@
+#[macro_use]
extern crate syn;
@@ -10,3 +11,4 @@
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
-fn smuggled_speculative_cursor() {
+fn smuggled_speculative_cursor_between_sources() {
+ // don't do this ever this is very unsafe and fails anyway
struct Smuggled(ParseStream<'static>);
@@ -29 +31,19 @@
}
+
+#[test]
+#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
+fn smuggled_speculative_cursor_between_brackets() {
+ struct BreakRules;
+ impl Parse for BreakRules {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let a;
+ let b;
+ parenthesized!(a in input);
+ parenthesized!(b in input);
+ a.advance_to(&b);
+ Ok(Self)
+ }
+ }
+
+ syn::parse_str::<BreakRules>("()()").unwrap();
+}
|
--- a/tests/test_parse_buffer.rs
+++ b/tests/test_parse_buffer.rs
@@ ... @@
+#[macro_use]
extern crate syn;
@@ ... @@
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
-fn smuggled_speculative_cursor() {
+fn smuggled_speculative_cursor_between_sources() {
+ // don't do this ever this is very unsafe and fails anyway
struct Smuggled(ParseStream<'static>);
@@ ... @@
}
+
+#[test]
+#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
+fn smuggled_speculative_cursor_between_brackets() {
+ struct BreakRules;
+ impl Parse for BreakRules {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let a;
+ let b;
+ parenthesized!(a in input);
+ parenthesized!(b in input);
+ a.advance_to(&b);
+ Ok(Self)
+ }
+ }
+
+ syn::parse_str::<BreakRules>("()()").unwrap();
+}
|
--- a/tests/test_parse_buffer.rs
+++ b/tests/test_parse_buffer.rs
@@ -1 +1,2 @@
ADD #[macro_use]
CON extern crate syn;
@@ -10,3 +11,4 @@
CON #[should_panic(expected = "Fork was not derived from the advancing parse stream")]
DEL fn smuggled_speculative_cursor() {
ADD fn smuggled_speculative_cursor_between_sources() {
ADD // don't do this ever this is very unsafe and fails anyway
CON struct Smuggled(ParseStream<'static>);
@@ -29 +31,19 @@
CON }
ADD
ADD #[test]
ADD #[should_panic(expected = "Fork was not derived from the advancing parse stream")]
ADD fn smuggled_speculative_cursor_between_brackets() {
ADD struct BreakRules;
ADD impl Parse for BreakRules {
ADD fn parse(input: ParseStream) -> Result<Self> {
ADD let a;
ADD let b;
ADD parenthesized!(a in input);
ADD parenthesized!(b in input);
ADD a.advance_to(&b);
ADD Ok(Self)
ADD }
ADD }
ADD
ADD syn::parse_str::<BreakRules>("()()").unwrap();
ADD }
|
<<<<<<< SEARCH
extern crate syn;
=======
#[macro_use]
extern crate syn;
>>>>>>> REPLACE
<<<<<<< SEARCH
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor() {
struct Smuggled(ParseStream<'static>);
impl Parse for Smuggled {
=======
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor_between_sources() {
// don't do this ever this is very unsafe and fails anyway
struct Smuggled(ParseStream<'static>);
impl Parse for Smuggled {
>>>>>>> REPLACE
<<<<<<< SEARCH
syn::parse_str::<BreakRules>("").unwrap();
}
=======
syn::parse_str::<BreakRules>("").unwrap();
}
#[test]
#[should_panic(expected = "Fork was not derived from the advancing parse stream")]
fn smuggled_speculative_cursor_between_brackets() {
struct BreakRules;
impl Parse for BreakRules {
fn parse(input: ParseStream) -> Result<Self> {
let a;
let b;
parenthesized!(a in input);
parenthesized!(b in input);
a.advance_to(&b);
Ok(Self)
}
}
syn::parse_str::<BreakRules>("()()").unwrap();
}
>>>>>>> REPLACE
|
FireZenk/Kartographer
|
b4e22f60962a51b36155ffd15260c5be1cf4c931
|
library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
|
kotlin
|
mit
|
Add a basic Core test
|
package org.firezenk.kartographer.library.core
import org.junit.Assert.*
/**
* Created by Jorge Garrido Oval, aka firezenk on 14/01/18.
* Project: Kartographer
*/
class CoreTest {
}
|
package org.firezenk.kartographer.library.core
import org.firezenk.kartographer.library.Logger
import org.firezenk.kartographer.library.core.util.TargetRoute
import org.firezenk.kartographer.library.dsl.route
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
/**
* Created by Jorge Garrido Oval, aka firezenk on 14/01/18.
* Project: Kartographer
*/
class CoreTest {
lateinit var core: Core
lateinit var move: Move
@Before fun setup() {
core = Core(Any(), Logger())
move = Move(core)
}
@Test fun `given a history with one route on default path, the current route is correct`() {
val route = route {
target = TargetRoute::class
path = Core.ROOT_NODE
anchor = Any()
}
move.routeTo(route)
val currentRoute = core.current<Any>()
assertEquals(route, currentRoute)
}
@Test fun `given a history with one route on default path, the current route payload is correct`() {
val route = route {
target = TargetRoute::class
path = Core.ROOT_NODE
params = mapOf("param1" to 1, "param2" to "hi!")
anchor = Any()
}
move.routeTo(route)
val currentParam1 = core.payload<Int>("param1")
val currentParam2 = core.payload<String>("param2")
assertEquals(currentParam1, 1)
assertEquals(currentParam2, "hi!")
}
}
| 42
| 1
| 2
|
mixed
|
--- a/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
+++ b/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
@@ -2,3 +2,8 @@
-import org.junit.Assert.*
+import org.firezenk.kartographer.library.Logger
+import org.firezenk.kartographer.library.core.util.TargetRoute
+import org.firezenk.kartographer.library.dsl.route
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
@@ -10,2 +15,38 @@
+ lateinit var core: Core
+ lateinit var move: Move
+
+ @Before fun setup() {
+ core = Core(Any(), Logger())
+ move = Move(core)
+ }
+
+ @Test fun `given a history with one route on default path, the current route is correct`() {
+ val route = route {
+ target = TargetRoute::class
+ path = Core.ROOT_NODE
+ anchor = Any()
+ }
+ move.routeTo(route)
+
+ val currentRoute = core.current<Any>()
+
+ assertEquals(route, currentRoute)
+ }
+
+ @Test fun `given a history with one route on default path, the current route payload is correct`() {
+ val route = route {
+ target = TargetRoute::class
+ path = Core.ROOT_NODE
+ params = mapOf("param1" to 1, "param2" to "hi!")
+ anchor = Any()
+ }
+ move.routeTo(route)
+
+ val currentParam1 = core.payload<Int>("param1")
+ val currentParam2 = core.payload<String>("param2")
+
+ assertEquals(currentParam1, 1)
+ assertEquals(currentParam2, "hi!")
+ }
}
|
--- a/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
+++ b/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
@@ ... @@
-import org.junit.Assert.*
+import org.firezenk.kartographer.library.Logger
+import org.firezenk.kartographer.library.core.util.TargetRoute
+import org.firezenk.kartographer.library.dsl.route
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
@@ ... @@
+ lateinit var core: Core
+ lateinit var move: Move
+
+ @Before fun setup() {
+ core = Core(Any(), Logger())
+ move = Move(core)
+ }
+
+ @Test fun `given a history with one route on default path, the current route is correct`() {
+ val route = route {
+ target = TargetRoute::class
+ path = Core.ROOT_NODE
+ anchor = Any()
+ }
+ move.routeTo(route)
+
+ val currentRoute = core.current<Any>()
+
+ assertEquals(route, currentRoute)
+ }
+
+ @Test fun `given a history with one route on default path, the current route payload is correct`() {
+ val route = route {
+ target = TargetRoute::class
+ path = Core.ROOT_NODE
+ params = mapOf("param1" to 1, "param2" to "hi!")
+ anchor = Any()
+ }
+ move.routeTo(route)
+
+ val currentParam1 = core.payload<Int>("param1")
+ val currentParam2 = core.payload<String>("param2")
+
+ assertEquals(currentParam1, 1)
+ assertEquals(currentParam2, "hi!")
+ }
}
|
--- a/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
+++ b/library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
@@ -2,3 +2,8 @@
CON
DEL import org.junit.Assert.*
ADD import org.firezenk.kartographer.library.Logger
ADD import org.firezenk.kartographer.library.core.util.TargetRoute
ADD import org.firezenk.kartographer.library.dsl.route
ADD import org.junit.Assert.assertEquals
ADD import org.junit.Before
ADD import org.junit.Test
CON
@@ -10,2 +15,38 @@
CON
ADD lateinit var core: Core
ADD lateinit var move: Move
ADD
ADD @Before fun setup() {
ADD core = Core(Any(), Logger())
ADD move = Move(core)
ADD }
ADD
ADD @Test fun `given a history with one route on default path, the current route is correct`() {
ADD val route = route {
ADD target = TargetRoute::class
ADD path = Core.ROOT_NODE
ADD anchor = Any()
ADD }
ADD move.routeTo(route)
ADD
ADD val currentRoute = core.current<Any>()
ADD
ADD assertEquals(route, currentRoute)
ADD }
ADD
ADD @Test fun `given a history with one route on default path, the current route payload is correct`() {
ADD val route = route {
ADD target = TargetRoute::class
ADD path = Core.ROOT_NODE
ADD params = mapOf("param1" to 1, "param2" to "hi!")
ADD anchor = Any()
ADD }
ADD move.routeTo(route)
ADD
ADD val currentParam1 = core.payload<Int>("param1")
ADD val currentParam2 = core.payload<String>("param2")
ADD
ADD assertEquals(currentParam1, 1)
ADD assertEquals(currentParam2, "hi!")
ADD }
CON }
|
<<<<<<< SEARCH
package org.firezenk.kartographer.library.core
import org.junit.Assert.*
/**
=======
package org.firezenk.kartographer.library.core
import org.firezenk.kartographer.library.Logger
import org.firezenk.kartographer.library.core.util.TargetRoute
import org.firezenk.kartographer.library.dsl.route
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
class CoreTest {
}
=======
class CoreTest {
lateinit var core: Core
lateinit var move: Move
@Before fun setup() {
core = Core(Any(), Logger())
move = Move(core)
}
@Test fun `given a history with one route on default path, the current route is correct`() {
val route = route {
target = TargetRoute::class
path = Core.ROOT_NODE
anchor = Any()
}
move.routeTo(route)
val currentRoute = core.current<Any>()
assertEquals(route, currentRoute)
}
@Test fun `given a history with one route on default path, the current route payload is correct`() {
val route = route {
target = TargetRoute::class
path = Core.ROOT_NODE
params = mapOf("param1" to 1, "param2" to "hi!")
anchor = Any()
}
move.routeTo(route)
val currentParam1 = core.payload<Int>("param1")
val currentParam2 = core.payload<String>("param2")
assertEquals(currentParam1, 1)
assertEquals(currentParam2, "hi!")
}
}
>>>>>>> REPLACE
|
shyiko/ktlint
|
c00889e65e43139b5b3a35c884743b99c36ea95d
|
ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
|
kotlin
|
mit
|
Add missing rules to ruleset
|
package com.github.shyiko.ktlint.ruleset.standard
import com.github.shyiko.ktlint.core.RuleSet
import com.github.shyiko.ktlint.core.RuleSetProvider
class StandardRuleSetProvider : RuleSetProvider {
override fun get(): RuleSet = RuleSet("standard",
ChainWrappingRule(),
CommentSpacingRule(),
FilenameRule(),
FinalNewlineRule(),
PackageNameRule(),
// disabled until auto-correct is working properly
// (e.g. try formatting "if (true)\n return { _ ->\n _\n}")
// MultiLineIfElseRule(),
// disabled until it's clear how to reconcile difference in Intellij & Android Studio import layout
// ImportOrderingRule(),
IndentationRule(),
MaxLineLengthRule(),
ModifierOrderRule(),
NoBlankLineBeforeRbraceRule(),
NoConsecutiveBlankLinesRule(),
NoEmptyClassBodyRule(),
// disabled until it's clear what to do in case of `import _.it`
// NoItParamInMultilineLambdaRule(),
NoLineBreakAfterElseRule(),
NoLineBreakBeforeAssignmentRule(),
NoMultipleSpacesRule(),
NoSemicolonsRule(),
NoTrailingSpacesRule(),
NoUnitReturnRule(),
NoUnusedImportsRule(),
NoWildcardImportsRule(),
ParameterListWrappingRule(),
SpacingAroundColonRule(),
SpacingAroundCommaRule(),
SpacingAroundCurlyRule(),
SpacingAroundKeywordRule(),
SpacingAroundOperatorsRule(),
SpacingAroundParensRule(),
SpacingAroundRangeOperatorRule(),
StringTemplateRule()
)
}
|
package com.github.shyiko.ktlint.ruleset.standard
import com.github.shyiko.ktlint.core.RuleSet
import com.github.shyiko.ktlint.core.RuleSetProvider
class StandardRuleSetProvider : RuleSetProvider {
override fun get(): RuleSet = RuleSet("standard",
AnnotationRule(),
ChainWrappingRule(),
CommentSpacingRule(),
FilenameRule(),
FinalNewlineRule(),
PackageNameRule(),
// disabled until auto-correct is working properly
// (e.g. try formatting "if (true)\n return { _ ->\n _\n}")
// MultiLineIfElseRule(),
// disabled until it's clear how to reconcile difference in Intellij & Android Studio import layout
// ImportOrderingRule(),
IndentationRule(),
MaxLineLengthRule(),
ModifierOrderRule(),
NoBlankLineBeforeRbraceRule(),
NoConsecutiveBlankLinesRule(),
NoEmptyClassBodyRule(),
// disabled until it's clear what to do in case of `import _.it`
// NoItParamInMultilineLambdaRule(),
NoLineBreakAfterElseRule(),
NoLineBreakBeforeAssignmentRule(),
NoMultipleSpacesRule(),
NoSemicolonsRule(),
NoTrailingSpacesRule(),
NoUnitReturnRule(),
NoUnusedImportsRule(),
NoWildcardImportsRule(),
ParameterListWrappingRule(),
SpacingAroundColonRule(),
SpacingAroundCommaRule(),
SpacingAroundCurlyRule(),
SpacingAroundDotRule(),
SpacingAroundKeywordRule(),
SpacingAroundOperatorsRule(),
SpacingAroundParensRule(),
SpacingAroundRangeOperatorRule(),
StringTemplateRule()
)
}
| 2
| 0
| 2
|
add_only
|
--- a/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
@@ -8,2 +8,3 @@
override fun get(): RuleSet = RuleSet("standard",
+ AnnotationRule(),
ChainWrappingRule(),
@@ -38,2 +39,3 @@
SpacingAroundCurlyRule(),
+ SpacingAroundDotRule(),
SpacingAroundKeywordRule(),
|
--- a/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
@@ ... @@
override fun get(): RuleSet = RuleSet("standard",
+ AnnotationRule(),
ChainWrappingRule(),
@@ ... @@
SpacingAroundCurlyRule(),
+ SpacingAroundDotRule(),
SpacingAroundKeywordRule(),
|
--- a/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/StandardRuleSetProvider.kt
@@ -8,2 +8,3 @@
CON override fun get(): RuleSet = RuleSet("standard",
ADD AnnotationRule(),
CON ChainWrappingRule(),
@@ -38,2 +39,3 @@
CON SpacingAroundCurlyRule(),
ADD SpacingAroundDotRule(),
CON SpacingAroundKeywordRule(),
|
<<<<<<< SEARCH
override fun get(): RuleSet = RuleSet("standard",
ChainWrappingRule(),
CommentSpacingRule(),
=======
override fun get(): RuleSet = RuleSet("standard",
AnnotationRule(),
ChainWrappingRule(),
CommentSpacingRule(),
>>>>>>> REPLACE
<<<<<<< SEARCH
SpacingAroundCommaRule(),
SpacingAroundCurlyRule(),
SpacingAroundKeywordRule(),
SpacingAroundOperatorsRule(),
=======
SpacingAroundCommaRule(),
SpacingAroundCurlyRule(),
SpacingAroundDotRule(),
SpacingAroundKeywordRule(),
SpacingAroundOperatorsRule(),
>>>>>>> REPLACE
|
bibaev/stream-debugger-plugin
|
ca1d73285a97d79d5417f0315052aa708eff1066
|
src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
|
kotlin
|
apache-2.0
|
Update tree values position when tree repainted
|
package com.intellij.debugger.streams.ui.impl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.streams.ui.ValueWithPosition
import java.awt.Graphics
/**
* @author Vitaliy.Bibaev
*/
class PositionsAwareCollectionView(header: String,
evaluationContext: EvaluationContextImpl,
private val values: List<ValueWithPosition>) : CollectionView(header, evaluationContext,
values.map { it.traceElement }) {
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
val visibleRect = instancesTree.visibleRect
for (value in values) {
val rect = instancesTree.getRectByValue(value.traceElement)
if (rect == null || !visibleRect.intersects(rect)) {
value.position = -1
value.isSelected = false
}
else {
value.position = rect.y + rect.height / 2 - visibleRect.y
value.isSelected = instancesTree.isSelected(value.traceElement)
}
}
}
}
|
package com.intellij.debugger.streams.ui.impl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.streams.ui.PaintingListener
import com.intellij.debugger.streams.ui.ValueWithPosition
import com.intellij.openapi.application.ApplicationManager
/**
* @author Vitaliy.Bibaev
*/
class PositionsAwareCollectionView(header: String,
evaluationContext: EvaluationContextImpl,
private val values: List<ValueWithPosition>) : CollectionView(header, evaluationContext,
values.map { it.traceElement }) {
init {
instancesTree.addPaintingListener(object : PaintingListener {
override fun componentPainted() {
updateValues()
}
})
}
private fun updateValues(): Unit {
val visibleRect = instancesTree.visibleRect
for (value in values) {
val rect = instancesTree.getRectByValue(value.traceElement)
if (rect == null || !visibleRect.intersects(rect)) {
value.position = -1
value.isSelected = false
}
else {
value.position = rect.y + rect.height / 2 - visibleRect.y
value.isSelected = instancesTree.isSelected(value.traceElement)
}
}
ApplicationManager.getApplication().invokeLater({})
}
}
| 12
| 3
| 3
|
mixed
|
--- a/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
+++ b/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
@@ -3,4 +3,5 @@
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
+import com.intellij.debugger.streams.ui.PaintingListener
import com.intellij.debugger.streams.ui.ValueWithPosition
-import java.awt.Graphics
+import com.intellij.openapi.application.ApplicationManager
@@ -13,5 +14,11 @@
values.map { it.traceElement }) {
- override fun paintComponent(g: Graphics?) {
- super.paintComponent(g)
+ init {
+ instancesTree.addPaintingListener(object : PaintingListener {
+ override fun componentPainted() {
+ updateValues()
+ }
+ })
+ }
+ private fun updateValues(): Unit {
val visibleRect = instancesTree.visibleRect
@@ -28,2 +35,4 @@
}
+
+ ApplicationManager.getApplication().invokeLater({})
}
|
--- a/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
+++ b/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
@@ ... @@
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
+import com.intellij.debugger.streams.ui.PaintingListener
import com.intellij.debugger.streams.ui.ValueWithPosition
-import java.awt.Graphics
+import com.intellij.openapi.application.ApplicationManager
@@ ... @@
values.map { it.traceElement }) {
- override fun paintComponent(g: Graphics?) {
- super.paintComponent(g)
+ init {
+ instancesTree.addPaintingListener(object : PaintingListener {
+ override fun componentPainted() {
+ updateValues()
+ }
+ })
+ }
+ private fun updateValues(): Unit {
val visibleRect = instancesTree.visibleRect
@@ ... @@
}
+
+ ApplicationManager.getApplication().invokeLater({})
}
|
--- a/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
+++ b/src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt
@@ -3,4 +3,5 @@
CON import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
ADD import com.intellij.debugger.streams.ui.PaintingListener
CON import com.intellij.debugger.streams.ui.ValueWithPosition
DEL import java.awt.Graphics
ADD import com.intellij.openapi.application.ApplicationManager
CON
@@ -13,5 +14,11 @@
CON values.map { it.traceElement }) {
DEL override fun paintComponent(g: Graphics?) {
DEL super.paintComponent(g)
ADD init {
ADD instancesTree.addPaintingListener(object : PaintingListener {
ADD override fun componentPainted() {
ADD updateValues()
ADD }
ADD })
ADD }
CON
ADD private fun updateValues(): Unit {
CON val visibleRect = instancesTree.visibleRect
@@ -28,2 +35,4 @@
CON }
ADD
ADD ApplicationManager.getApplication().invokeLater({})
CON }
|
<<<<<<< SEARCH
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.streams.ui.ValueWithPosition
import java.awt.Graphics
/**
=======
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.streams.ui.PaintingListener
import com.intellij.debugger.streams.ui.ValueWithPosition
import com.intellij.openapi.application.ApplicationManager
/**
>>>>>>> REPLACE
<<<<<<< SEARCH
private val values: List<ValueWithPosition>) : CollectionView(header, evaluationContext,
values.map { it.traceElement }) {
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
val visibleRect = instancesTree.visibleRect
for (value in values) {
=======
private val values: List<ValueWithPosition>) : CollectionView(header, evaluationContext,
values.map { it.traceElement }) {
init {
instancesTree.addPaintingListener(object : PaintingListener {
override fun componentPainted() {
updateValues()
}
})
}
private fun updateValues(): Unit {
val visibleRect = instancesTree.visibleRect
for (value in values) {
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
}
}
=======
}
}
ApplicationManager.getApplication().invokeLater({})
}
}
>>>>>>> REPLACE
|
aquatir/remember_java_api
|
2c9a35eab88d5377c8f0d338e194146799188438
|
code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
|
kotlin
|
mit
|
Add merge sort example in kotlin
|
package codesample.kotlin.sandbox.algorithms
class Sorts {
fun recursiveMerge(list: List<Int>): List<Int> {
if (list.size <= 1)
return list
val middle = list.size / 2
val left = list.subList(0, middle)
val right = list.subList(middle, list.size)
return merge(recursiveMerge(left), recursiveMerge(right))
}
fun merge (left: List<Int>, right: List<Int>): List<Int> {
val mergedList = mutableListOf<Int>()
var leftIter = 0
var rightIter = 0
val size = left.size
while (leftIter < size && rightIter < size) {
if (left[leftIter] <= right[rightIter]) {
mergedList.add(left[leftIter])
leftIter++
} else {
mergedList.add(right[rightIter])
rightIter++
}
}
if (leftIter == size)
mergedList.addAll(right.subList(rightIter, size))
else if (rightIter == size)
mergedList.addAll(left.subList(leftIter, size))
return mergedList
}
}
fun main(args: Array<String>) {
val sorts = Sorts()
val left = listOf(3,5,9)
val right = listOf(3,5,10)
println(sorts.merge(left, right))
var superList = listOf(9,8,7,6,5,4,3,2,1)
println(sorts.recursiveMerge(superList))
}
|
package codesample.kotlin.sandbox.algorithms
class Sorts {
fun recursiveMerge(list: List<Int>): List<Int> {
if (list.size <= 1)
return list
val middle = list.size / 2
val left = list.subList(0, middle)
val right = list.subList(middle, list.size)
return merge(recursiveMerge(left), recursiveMerge(right))
}
fun merge (left: List<Int>, right: List<Int>): List<Int> {
val mergedList = mutableListOf<Int>()
var leftIter = 0
var rightIter = 0
val leftSize = left.size
val rightSize = right.size
while (leftIter < leftSize && rightIter < rightSize) {
if (left[leftIter] <= right[rightIter]) {
mergedList.add(left[leftIter])
leftIter++
} else {
mergedList.add(right[rightIter])
rightIter++
}
}
if (leftIter == leftSize)
mergedList.addAll(right.subList(rightIter, rightSize))
else if (rightIter == rightSize)
mergedList.addAll(left.subList(leftIter, leftSize))
return mergedList
}
}
fun main(args: Array<String>) {
val sorts = Sorts()
val left = listOf(3,5,9)
val right = listOf(3,5,10)
println(sorts.merge(left, right))
var superList = listOf(9,8,7,6,5,4,3,2,1)
println(sorts.recursiveMerge(superList))
}
| 7
| 6
| 2
|
mixed
|
--- a/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
+++ b/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
@@ -21,5 +21,6 @@
- val size = left.size
+ val leftSize = left.size
+ val rightSize = right.size
- while (leftIter < size && rightIter < size) {
+ while (leftIter < leftSize && rightIter < rightSize) {
if (left[leftIter] <= right[rightIter]) {
@@ -34,6 +35,6 @@
- if (leftIter == size)
- mergedList.addAll(right.subList(rightIter, size))
- else if (rightIter == size)
- mergedList.addAll(left.subList(leftIter, size))
+ if (leftIter == leftSize)
+ mergedList.addAll(right.subList(rightIter, rightSize))
+ else if (rightIter == rightSize)
+ mergedList.addAll(left.subList(leftIter, leftSize))
|
--- a/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
+++ b/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
@@ ... @@
- val size = left.size
+ val leftSize = left.size
+ val rightSize = right.size
- while (leftIter < size && rightIter < size) {
+ while (leftIter < leftSize && rightIter < rightSize) {
if (left[leftIter] <= right[rightIter]) {
@@ ... @@
- if (leftIter == size)
- mergedList.addAll(right.subList(rightIter, size))
- else if (rightIter == size)
- mergedList.addAll(left.subList(leftIter, size))
+ if (leftIter == leftSize)
+ mergedList.addAll(right.subList(rightIter, rightSize))
+ else if (rightIter == rightSize)
+ mergedList.addAll(left.subList(leftIter, leftSize))
|
--- a/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
+++ b/code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/algorithms/Sorts.kt
@@ -21,5 +21,6 @@
CON
DEL val size = left.size
ADD val leftSize = left.size
ADD val rightSize = right.size
CON
DEL while (leftIter < size && rightIter < size) {
ADD while (leftIter < leftSize && rightIter < rightSize) {
CON if (left[leftIter] <= right[rightIter]) {
@@ -34,6 +35,6 @@
CON
DEL if (leftIter == size)
DEL mergedList.addAll(right.subList(rightIter, size))
DEL else if (rightIter == size)
DEL mergedList.addAll(left.subList(leftIter, size))
ADD if (leftIter == leftSize)
ADD mergedList.addAll(right.subList(rightIter, rightSize))
ADD else if (rightIter == rightSize)
ADD mergedList.addAll(left.subList(leftIter, leftSize))
CON
|
<<<<<<< SEARCH
var rightIter = 0
val size = left.size
while (leftIter < size && rightIter < size) {
if (left[leftIter] <= right[rightIter]) {
mergedList.add(left[leftIter])
=======
var rightIter = 0
val leftSize = left.size
val rightSize = right.size
while (leftIter < leftSize && rightIter < rightSize) {
if (left[leftIter] <= right[rightIter]) {
mergedList.add(left[leftIter])
>>>>>>> REPLACE
<<<<<<< SEARCH
if (leftIter == size)
mergedList.addAll(right.subList(rightIter, size))
else if (rightIter == size)
mergedList.addAll(left.subList(leftIter, size))
return mergedList
=======
if (leftIter == leftSize)
mergedList.addAll(right.subList(rightIter, rightSize))
else if (rightIter == rightSize)
mergedList.addAll(left.subList(leftIter, leftSize))
return mergedList
>>>>>>> REPLACE
|
tsu-complete/js-ko-property-grid
|
078a4e91983ccb1a7844b845e8c7e6d4757b53d1
|
index.js
|
javascript
|
mit
|
Add model skeletons and setup ko component
Also exporting component property model for user
extension purposes
|
;(function ( factory ) {
"use strict";
if ("function" === typeof define && define.amd) {
define(["knockout"], factory);
} else if ("undefined" !== typeof module) {
factory(require("knockout"));
} else {
factory(window.ko);
}
})(function ( ko ) {
"use strict";
return ko;
});
|
;(function ( factory ) {
"use strict";
if ("function" === typeof define && define.amd) {
define(["knockout"], factory);
} else if ("undefined" !== typeof module) {
factory(require("knockout"));
} else {
factory(window.ko);
}
})(function ( ko ) {
"use strict";
var PropertyModel, PropertyGridViewModel;
PropertyModel = (function ( ) {
var proto;
function PropertyModel ( options ) {
// TODO: implement
this.options = options;
}
proto = PropertyModel.prototype;
return PropertyModel;
})();
PropertyGridViewModel = (function ( ) {
var proto;
function PropertyGridViewModel ( params ) {
// TODO: implement
this.params = params;
}
proto = PropertyGridViewModel.prototype;
return PropertyGridViewModel;
})();
ko.components.register("property-grid", {
viewModel: PropertyGridViewModel
, synchronous: true
, template: "<!-- TODO -->"
});
ko.property_grid = {
PropertyModel: PropertyModel
};
return ko;
});
| 39
| 0
| 1
|
add_only
|
--- a/index.js
+++ b/index.js
@@ -15,2 +15,41 @@
+ var PropertyModel, PropertyGridViewModel;
+
+ PropertyModel = (function ( ) {
+ var proto;
+
+ function PropertyModel ( options ) {
+ // TODO: implement
+ this.options = options;
+
+ }
+
+ proto = PropertyModel.prototype;
+
+ return PropertyModel;
+ })();
+
+ PropertyGridViewModel = (function ( ) {
+ var proto;
+
+ function PropertyGridViewModel ( params ) {
+ // TODO: implement
+ this.params = params;
+
+ }
+
+ proto = PropertyGridViewModel.prototype;
+
+ return PropertyGridViewModel;
+ })();
+
+ ko.components.register("property-grid", {
+ viewModel: PropertyGridViewModel
+ , synchronous: true
+ , template: "<!-- TODO -->"
+ });
+
+ ko.property_grid = {
+ PropertyModel: PropertyModel
+ };
|
--- a/index.js
+++ b/index.js
@@ ... @@
+ var PropertyModel, PropertyGridViewModel;
+
+ PropertyModel = (function ( ) {
+ var proto;
+
+ function PropertyModel ( options ) {
+ // TODO: implement
+ this.options = options;
+
+ }
+
+ proto = PropertyModel.prototype;
+
+ return PropertyModel;
+ })();
+
+ PropertyGridViewModel = (function ( ) {
+ var proto;
+
+ function PropertyGridViewModel ( params ) {
+ // TODO: implement
+ this.params = params;
+
+ }
+
+ proto = PropertyGridViewModel.prototype;
+
+ return PropertyGridViewModel;
+ })();
+
+ ko.components.register("property-grid", {
+ viewModel: PropertyGridViewModel
+ , synchronous: true
+ , template: "<!-- TODO -->"
+ });
+
+ ko.property_grid = {
+ PropertyModel: PropertyModel
+ };
|
--- a/index.js
+++ b/index.js
@@ -15,2 +15,41 @@
CON
ADD var PropertyModel, PropertyGridViewModel;
ADD
ADD PropertyModel = (function ( ) {
ADD var proto;
ADD
ADD function PropertyModel ( options ) {
ADD // TODO: implement
ADD this.options = options;
ADD
ADD }
ADD
ADD proto = PropertyModel.prototype;
ADD
ADD return PropertyModel;
ADD })();
ADD
ADD PropertyGridViewModel = (function ( ) {
ADD var proto;
ADD
ADD function PropertyGridViewModel ( params ) {
ADD // TODO: implement
ADD this.params = params;
ADD
ADD }
ADD
ADD proto = PropertyGridViewModel.prototype;
ADD
ADD return PropertyGridViewModel;
ADD })();
ADD
ADD ko.components.register("property-grid", {
ADD viewModel: PropertyGridViewModel
ADD , synchronous: true
ADD , template: "<!-- TODO -->"
ADD });
ADD
ADD ko.property_grid = {
ADD PropertyModel: PropertyModel
ADD };
CON
|
<<<<<<< SEARCH
"use strict";
return ko;
=======
"use strict";
var PropertyModel, PropertyGridViewModel;
PropertyModel = (function ( ) {
var proto;
function PropertyModel ( options ) {
// TODO: implement
this.options = options;
}
proto = PropertyModel.prototype;
return PropertyModel;
})();
PropertyGridViewModel = (function ( ) {
var proto;
function PropertyGridViewModel ( params ) {
// TODO: implement
this.params = params;
}
proto = PropertyGridViewModel.prototype;
return PropertyGridViewModel;
})();
ko.components.register("property-grid", {
viewModel: PropertyGridViewModel
, synchronous: true
, template: "<!-- TODO -->"
});
ko.property_grid = {
PropertyModel: PropertyModel
};
return ko;
>>>>>>> REPLACE
|
wxmaudio/ReactNativePropertyFinder
|
34a476e0273ffcae759194ae684608e92273e4c5
|
SearchPage.js
|
javascript
|
mit
|
Add search input and search button
|
'use strict';
import React from 'react';
import {
StyleSheet,
Text,
TextInput,
View,
Image,
TouchableHighlight,
ActivityIndicatorIOS
} from 'react-native';
const styles = StyleSheet.create({
description:{
marginBottom:20,
fontSize:18,
textAlign:'center',
color:'#656565'},
container:{
padding:30,
marginTop:65,
alignItems:'center'}
});
class SearchPage extends React.Component{
render(){
return (
<View
style = {styles.container}>
<Text style={styles.description}> Search for house to buy</Text>
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
</View>
);
}
}
export default SearchPage;
|
'use strict';
import React from 'react';
import {
StyleSheet,
Text,
TextInput,
View,
Image,
TouchableHighlight,
ActivityIndicatorIOS
} from 'react-native';
const styles = StyleSheet.create({
description:{
marginBottom:20,
fontSize:18,
textAlign:'center',
color:'#656565'},
container:{
padding:30,
marginTop:65,
alignItems:'center'},
flowRight:{
flexDirection:'row',
alignItems:'center',
alignSelf:'stretch'},
buttonText:{
fontSize:18,
color:'white',
alignSelf:'center'},
button:{
height:36,
flex:1,
flexDirection:'row',
backgroundColor:'#48BBEC',
borderColor:'#48BBEC',
borderWidth:1,
borderRadius:8,
marginBottom:10,
alignSelf:'stretch',
justifyContent:'center'},
searchInput:{
height:36,
padding:4,
marginRight:5,
flex:4,
fontSize:18,
borderWidth:1,
borderColor:'#48BBEC',
borderRadius:8,
color:'#48BBEC'}
});
class SearchPage extends React.Component{
render(){
return (
<View
style = {styles.container}>
<Text style={styles.description}> Search for house to buy</Text>
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
<View style={styles.flowRight}>
<TextInput style={styles.searchInput} placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
</View>
);
}
}
export default SearchPage;
| 42
| 1
| 2
|
mixed
|
--- a/SearchPage.js
+++ b/SearchPage.js
@@ -22,3 +22,33 @@
marginTop:65,
- alignItems:'center'}
+ alignItems:'center'},
+
+ flowRight:{
+ flexDirection:'row',
+ alignItems:'center',
+ alignSelf:'stretch'},
+ buttonText:{
+ fontSize:18,
+ color:'white',
+ alignSelf:'center'},
+ button:{
+ height:36,
+ flex:1,
+ flexDirection:'row',
+ backgroundColor:'#48BBEC',
+ borderColor:'#48BBEC',
+ borderWidth:1,
+ borderRadius:8,
+ marginBottom:10,
+ alignSelf:'stretch',
+ justifyContent:'center'},
+ searchInput:{
+ height:36,
+ padding:4,
+ marginRight:5,
+ flex:4,
+ fontSize:18,
+ borderWidth:1,
+ borderColor:'#48BBEC',
+ borderRadius:8,
+ color:'#48BBEC'}
});
@@ -32,2 +62,13 @@
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
+ <View style={styles.flowRight}>
+ <TextInput style={styles.searchInput} placeholder='Search via name or postcode'/>
+ <TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
+ <Text style={styles.buttonText}>Go</Text>
+ </TouchableHighlight>
+ </View>
+ <TouchableHighlight style={styles.button}
+ underlayColor='#99d9f4'>
+ <Text style={styles.buttonText}>Location</Text>
+ </TouchableHighlight>
+
</View>
|
--- a/SearchPage.js
+++ b/SearchPage.js
@@ ... @@
marginTop:65,
- alignItems:'center'}
+ alignItems:'center'},
+
+ flowRight:{
+ flexDirection:'row',
+ alignItems:'center',
+ alignSelf:'stretch'},
+ buttonText:{
+ fontSize:18,
+ color:'white',
+ alignSelf:'center'},
+ button:{
+ height:36,
+ flex:1,
+ flexDirection:'row',
+ backgroundColor:'#48BBEC',
+ borderColor:'#48BBEC',
+ borderWidth:1,
+ borderRadius:8,
+ marginBottom:10,
+ alignSelf:'stretch',
+ justifyContent:'center'},
+ searchInput:{
+ height:36,
+ padding:4,
+ marginRight:5,
+ flex:4,
+ fontSize:18,
+ borderWidth:1,
+ borderColor:'#48BBEC',
+ borderRadius:8,
+ color:'#48BBEC'}
});
@@ ... @@
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
+ <View style={styles.flowRight}>
+ <TextInput style={styles.searchInput} placeholder='Search via name or postcode'/>
+ <TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
+ <Text style={styles.buttonText}>Go</Text>
+ </TouchableHighlight>
+ </View>
+ <TouchableHighlight style={styles.button}
+ underlayColor='#99d9f4'>
+ <Text style={styles.buttonText}>Location</Text>
+ </TouchableHighlight>
+
</View>
|
--- a/SearchPage.js
+++ b/SearchPage.js
@@ -22,3 +22,33 @@
CON marginTop:65,
DEL alignItems:'center'}
ADD alignItems:'center'},
ADD
ADD flowRight:{
ADD flexDirection:'row',
ADD alignItems:'center',
ADD alignSelf:'stretch'},
ADD buttonText:{
ADD fontSize:18,
ADD color:'white',
ADD alignSelf:'center'},
ADD button:{
ADD height:36,
ADD flex:1,
ADD flexDirection:'row',
ADD backgroundColor:'#48BBEC',
ADD borderColor:'#48BBEC',
ADD borderWidth:1,
ADD borderRadius:8,
ADD marginBottom:10,
ADD alignSelf:'stretch',
ADD justifyContent:'center'},
ADD searchInput:{
ADD height:36,
ADD padding:4,
ADD marginRight:5,
ADD flex:4,
ADD fontSize:18,
ADD borderWidth:1,
ADD borderColor:'#48BBEC',
ADD borderRadius:8,
ADD color:'#48BBEC'}
CON });
@@ -32,2 +62,13 @@
CON <Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
ADD <View style={styles.flowRight}>
ADD <TextInput style={styles.searchInput} placeholder='Search via name or postcode'/>
ADD <TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
ADD <Text style={styles.buttonText}>Go</Text>
ADD </TouchableHighlight>
ADD </View>
ADD <TouchableHighlight style={styles.button}
ADD underlayColor='#99d9f4'>
ADD <Text style={styles.buttonText}>Location</Text>
ADD </TouchableHighlight>
ADD
CON </View>
|
<<<<<<< SEARCH
padding:30,
marginTop:65,
alignItems:'center'}
});
=======
padding:30,
marginTop:65,
alignItems:'center'},
flowRight:{
flexDirection:'row',
alignItems:'center',
alignSelf:'stretch'},
buttonText:{
fontSize:18,
color:'white',
alignSelf:'center'},
button:{
height:36,
flex:1,
flexDirection:'row',
backgroundColor:'#48BBEC',
borderColor:'#48BBEC',
borderWidth:1,
borderRadius:8,
marginBottom:10,
alignSelf:'stretch',
justifyContent:'center'},
searchInput:{
height:36,
padding:4,
marginRight:5,
flex:4,
fontSize:18,
borderWidth:1,
borderColor:'#48BBEC',
borderRadius:8,
color:'#48BBEC'}
});
>>>>>>> REPLACE
<<<<<<< SEARCH
<Text style={styles.description}> Search for house to buy</Text>
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
</View>
);
=======
<Text style={styles.description}> Search for house to buy</Text>
<Text style={styles.description}> Search by place-name, postcode or search near your location.</Text>
<View style={styles.flowRight}>
<TextInput style={styles.searchInput} placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
</View>
);
>>>>>>> REPLACE
|
luxons/seven-wonders
|
80fa00205cd432471318198ac68b79b956204ae0
|
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
|
kotlin
|
mit
|
Add player icon in player info
|
package org.luxons.sevenwonders.ui.components.gameBrowser
import org.luxons.sevenwonders.model.api.ConnectedPlayer
import org.luxons.sevenwonders.ui.redux.connectState
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import react.dom.*
interface PlayerInfoProps : RProps {
var connectedPlayer: ConnectedPlayer?
}
class PlayerInfoPresenter(props: PlayerInfoProps) : RComponent<PlayerInfoProps, RState>(props) {
override fun RBuilder.render() {
span {
b {
+"Username:"
}
props.connectedPlayer?.let {
+ " ${it.displayName}"
}
}
}
}
fun RBuilder.playerInfo() = playerInfo {}
private val playerInfo = connectState(
clazz = PlayerInfoPresenter::class,
mapStateToProps = { state, _ ->
connectedPlayer = state.connectedPlayer
}
)
|
package org.luxons.sevenwonders.ui.components.gameBrowser
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import org.luxons.sevenwonders.model.api.ConnectedPlayer
import org.luxons.sevenwonders.ui.redux.connectState
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import styled.css
import styled.styledDiv
import styled.styledSpan
interface PlayerInfoProps : RProps {
var connectedPlayer: ConnectedPlayer?
}
class PlayerInfoPresenter(props: PlayerInfoProps) : RComponent<PlayerInfoProps, RState>(props) {
override fun RBuilder.render() {
styledDiv {
css {
display = Display.flex
alignItems = Align.center
}
props.connectedPlayer?.let {
bpIcon(name = it.icon?.name ?: "user", size = 30)
styledDiv {
css {
display = Display.flex
flexDirection = FlexDirection.column
marginLeft = 0.3.rem
}
styledSpan {
css {
fontSize = 1.rem
}
+it.displayName
}
styledSpan {
css {
marginTop = 0.1.rem
color = Color.lightGray
fontSize = 0.8.rem
}
+"(${it.username})"
}
}
}
}
}
}
fun RBuilder.playerInfo() = playerInfo {}
private val playerInfo = connectState(
clazz = PlayerInfoPresenter::class,
mapStateToProps = { state, _ ->
connectedPlayer = state.connectedPlayer
}
)
| 31
| 5
| 3
|
mixed
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
@@ -2,2 +2,4 @@
+import com.palantir.blueprintjs.bpIcon
+import kotlinx.css.*
import org.luxons.sevenwonders.model.api.ConnectedPlayer
@@ -8,3 +10,5 @@
import react.RState
-import react.dom.*
+import styled.css
+import styled.styledDiv
+import styled.styledSpan
@@ -17,8 +21,30 @@
override fun RBuilder.render() {
- span {
- b {
- +"Username:"
+ styledDiv {
+ css {
+ display = Display.flex
+ alignItems = Align.center
}
props.connectedPlayer?.let {
- + " ${it.displayName}"
+ bpIcon(name = it.icon?.name ?: "user", size = 30)
+ styledDiv {
+ css {
+ display = Display.flex
+ flexDirection = FlexDirection.column
+ marginLeft = 0.3.rem
+ }
+ styledSpan {
+ css {
+ fontSize = 1.rem
+ }
+ +it.displayName
+ }
+ styledSpan {
+ css {
+ marginTop = 0.1.rem
+ color = Color.lightGray
+ fontSize = 0.8.rem
+ }
+ +"(${it.username})"
+ }
+ }
}
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
@@ ... @@
+import com.palantir.blueprintjs.bpIcon
+import kotlinx.css.*
import org.luxons.sevenwonders.model.api.ConnectedPlayer
@@ ... @@
import react.RState
-import react.dom.*
+import styled.css
+import styled.styledDiv
+import styled.styledSpan
@@ ... @@
override fun RBuilder.render() {
- span {
- b {
- +"Username:"
+ styledDiv {
+ css {
+ display = Display.flex
+ alignItems = Align.center
}
props.connectedPlayer?.let {
- + " ${it.displayName}"
+ bpIcon(name = it.icon?.name ?: "user", size = 30)
+ styledDiv {
+ css {
+ display = Display.flex
+ flexDirection = FlexDirection.column
+ marginLeft = 0.3.rem
+ }
+ styledSpan {
+ css {
+ fontSize = 1.rem
+ }
+ +it.displayName
+ }
+ styledSpan {
+ css {
+ marginTop = 0.1.rem
+ color = Color.lightGray
+ fontSize = 0.8.rem
+ }
+ +"(${it.username})"
+ }
+ }
}
|
--- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
+++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/PlayerInfo.kt
@@ -2,2 +2,4 @@
CON
ADD import com.palantir.blueprintjs.bpIcon
ADD import kotlinx.css.*
CON import org.luxons.sevenwonders.model.api.ConnectedPlayer
@@ -8,3 +10,5 @@
CON import react.RState
DEL import react.dom.*
ADD import styled.css
ADD import styled.styledDiv
ADD import styled.styledSpan
CON
@@ -17,8 +21,30 @@
CON override fun RBuilder.render() {
DEL span {
DEL b {
DEL +"Username:"
ADD styledDiv {
ADD css {
ADD display = Display.flex
ADD alignItems = Align.center
CON }
CON props.connectedPlayer?.let {
DEL + " ${it.displayName}"
ADD bpIcon(name = it.icon?.name ?: "user", size = 30)
ADD styledDiv {
ADD css {
ADD display = Display.flex
ADD flexDirection = FlexDirection.column
ADD marginLeft = 0.3.rem
ADD }
ADD styledSpan {
ADD css {
ADD fontSize = 1.rem
ADD }
ADD +it.displayName
ADD }
ADD styledSpan {
ADD css {
ADD marginTop = 0.1.rem
ADD color = Color.lightGray
ADD fontSize = 0.8.rem
ADD }
ADD +"(${it.username})"
ADD }
ADD }
CON }
|
<<<<<<< SEARCH
package org.luxons.sevenwonders.ui.components.gameBrowser
import org.luxons.sevenwonders.model.api.ConnectedPlayer
import org.luxons.sevenwonders.ui.redux.connectState
=======
package org.luxons.sevenwonders.ui.components.gameBrowser
import com.palantir.blueprintjs.bpIcon
import kotlinx.css.*
import org.luxons.sevenwonders.model.api.ConnectedPlayer
import org.luxons.sevenwonders.ui.redux.connectState
>>>>>>> REPLACE
<<<<<<< SEARCH
import react.RProps
import react.RState
import react.dom.*
interface PlayerInfoProps : RProps {
=======
import react.RProps
import react.RState
import styled.css
import styled.styledDiv
import styled.styledSpan
interface PlayerInfoProps : RProps {
>>>>>>> REPLACE
<<<<<<< SEARCH
override fun RBuilder.render() {
span {
b {
+"Username:"
}
props.connectedPlayer?.let {
+ " ${it.displayName}"
}
}
=======
override fun RBuilder.render() {
styledDiv {
css {
display = Display.flex
alignItems = Align.center
}
props.connectedPlayer?.let {
bpIcon(name = it.icon?.name ?: "user", size = 30)
styledDiv {
css {
display = Display.flex
flexDirection = FlexDirection.column
marginLeft = 0.3.rem
}
styledSpan {
css {
fontSize = 1.rem
}
+it.displayName
}
styledSpan {
css {
marginTop = 0.1.rem
color = Color.lightGray
fontSize = 0.8.rem
}
+"(${it.username})"
}
}
}
}
>>>>>>> REPLACE
|
rafaelstz/regenerator
|
605dc42c521d6d4faea36dde4773f5a802fae594
|
lib/util.js
|
javascript
|
bsd-2-clause
|
Use hasOwnProperty when setting defaults
|
/**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
exports.guessTabWidth = function(source) {
var counts = []; // Sparse array.
var lastIndent = 0;
source.split("\n").forEach(function(line) {
var indent = /^\s*/.exec(line)[0].length;
var diff = Math.abs(indent - lastIndent);
counts[diff] = ~~counts[diff] + 1;
lastIndent = indent;
});
var maxCount = -1;
var result = 2;
for (var tabWidth = 1;
tabWidth < counts.length;
tabWidth += 1) {
if (tabWidth in counts &&
counts[tabWidth] > maxCount) {
maxCount = counts[tabWidth];
result = tabWidth;
}
}
return result;
};
exports.defaults = function(obj) {
var len = arguments.length;
var extension;
for (var i = 1; i < len; ++i) {
if ((extension = arguments[i])) {
for (var key in extension) {
if (obj[key] === undefined) {
obj[key] = extension[key];
}
}
}
}
return obj;
};
|
/**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var hasOwn = Object.prototype.hasOwnProperty;
exports.guessTabWidth = function(source) {
var counts = []; // Sparse array.
var lastIndent = 0;
source.split("\n").forEach(function(line) {
var indent = /^\s*/.exec(line)[0].length;
var diff = Math.abs(indent - lastIndent);
counts[diff] = ~~counts[diff] + 1;
lastIndent = indent;
});
var maxCount = -1;
var result = 2;
for (var tabWidth = 1;
tabWidth < counts.length;
tabWidth += 1) {
if (tabWidth in counts &&
counts[tabWidth] > maxCount) {
maxCount = counts[tabWidth];
result = tabWidth;
}
}
return result;
};
exports.defaults = function(obj) {
var len = arguments.length;
var extension;
for (var i = 1; i < len; ++i) {
if ((extension = arguments[i])) {
for (var key in extension) {
if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
obj[key] = extension[key];
}
}
}
}
return obj;
};
| 3
| 1
| 2
|
mixed
|
--- a/lib/util.js
+++ b/lib/util.js
@@ -8,2 +8,4 @@
*/
+
+var hasOwn = Object.prototype.hasOwnProperty;
@@ -43,3 +45,3 @@
for (var key in extension) {
- if (obj[key] === undefined) {
+ if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
obj[key] = extension[key];
|
--- a/lib/util.js
+++ b/lib/util.js
@@ ... @@
*/
+
+var hasOwn = Object.prototype.hasOwnProperty;
@@ ... @@
for (var key in extension) {
- if (obj[key] === undefined) {
+ if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
obj[key] = extension[key];
|
--- a/lib/util.js
+++ b/lib/util.js
@@ -8,2 +8,4 @@
CON */
ADD
ADD var hasOwn = Object.prototype.hasOwnProperty;
CON
@@ -43,3 +45,3 @@
CON for (var key in extension) {
DEL if (obj[key] === undefined) {
ADD if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
CON obj[key] = extension[key];
|
<<<<<<< SEARCH
* of patent rights can be found in the PATENTS file in the same directory.
*/
exports.guessTabWidth = function(source) {
=======
* of patent rights can be found in the PATENTS file in the same directory.
*/
var hasOwn = Object.prototype.hasOwnProperty;
exports.guessTabWidth = function(source) {
>>>>>>> REPLACE
<<<<<<< SEARCH
if ((extension = arguments[i])) {
for (var key in extension) {
if (obj[key] === undefined) {
obj[key] = extension[key];
}
=======
if ((extension = arguments[i])) {
for (var key in extension) {
if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) {
obj[key] = extension[key];
}
>>>>>>> REPLACE
|
Drakulix/zwreec
|
fac58b7695b004af77291ef1fa87e4849bc08694
|
src/main.rs
|
rust
|
bsd-2-clause
|
Use new logger and new macros
|
use std::env;
#[macro_use]
pub mod utils;
extern crate zwreec;
fn main() {
log_info!("main started");
// handling commandline parameters
let args: Vec<String> = env::args().collect();
let mut input_file_name: &str;
let mut output_file_name: &str;
match args.len() {
1 => {
input_file_name = "a.in";
output_file_name = "a.out";
},
3 => {
input_file_name = &args[1];
output_file_name = &args[2];
},
_ => {
help();
return;
}
};
// call library
zwreec::compile(input_file_name, output_file_name);
// only for testing
log_verbose!("(1) {}", zwreec::frontend::temp_hello());
log_verbose!("(2) {}", zwreec::backend::temp_hello());
log_verbose!("(3) {}", zwreec::file::temp_hello());
log_info!("main finished");
}
fn help() {
log_error!("invalid arguments");
log_info!("usage:\n zwreec <input_file> <output_file>");
}
|
use std::env;
use std::fs::File;
mod utils;
use self::utils::logger;
extern crate zwreec;
#[macro_use] extern crate log;
extern crate time;
extern crate term;
fn main() {
//early init
//let _ = SimpleLogger::init(LogLevelFilter::Info);
let _ = logger::CombinedLogger::init(
vec![
logger::FileLogger::new(logger::LogLevelFilter::Trace, File::create("zwreec.log").unwrap()),
logger::TermLogger::new(logger::LogLevelFilter::Info),
]
);
info!("main started");
// handling commandline parameters
let args: Vec<String> = env::args().collect();
let mut input_file_name: &str;
let mut output_file_name: &str;
match args.len() {
1 => {
input_file_name = "a.in";
output_file_name = "a.out";
},
3 => {
input_file_name = &args[1];
output_file_name = &args[2];
},
_ => {
help();
return;
}
};
// call library
zwreec::compile(input_file_name, output_file_name);
// only for testing
debug!("(1) {}", zwreec::frontend::temp_hello());
debug!("(2) {}", zwreec::backend::temp_hello());
debug!("(3) {}", zwreec::file::temp_hello());
info!("main finished");
}
fn help() {
error!("invalid arguments");
info!("usage:\n zwreec <input_file> <output_file>");
}
| 23
| 10
| 3
|
mixed
|
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,24 @@
use std::env;
+use std::fs::File;
-#[macro_use]
-pub mod utils;
+mod utils;
+use self::utils::logger;
extern crate zwreec;
-
+#[macro_use] extern crate log;
+extern crate time;
+extern crate term;
fn main() {
- log_info!("main started");
+ //early init
+
+ //let _ = SimpleLogger::init(LogLevelFilter::Info);
+ let _ = logger::CombinedLogger::init(
+ vec![
+ logger::FileLogger::new(logger::LogLevelFilter::Trace, File::create("zwreec.log").unwrap()),
+ logger::TermLogger::new(logger::LogLevelFilter::Info),
+ ]
+ );
+
+ info!("main started");
@@ -36,7 +49,7 @@
// only for testing
- log_verbose!("(1) {}", zwreec::frontend::temp_hello());
- log_verbose!("(2) {}", zwreec::backend::temp_hello());
- log_verbose!("(3) {}", zwreec::file::temp_hello());
+ debug!("(1) {}", zwreec::frontend::temp_hello());
+ debug!("(2) {}", zwreec::backend::temp_hello());
+ debug!("(3) {}", zwreec::file::temp_hello());
- log_info!("main finished");
+ info!("main finished");
}
@@ -44,4 +57,4 @@
fn help() {
- log_error!("invalid arguments");
- log_info!("usage:\n zwreec <input_file> <output_file>");
+ error!("invalid arguments");
+ info!("usage:\n zwreec <input_file> <output_file>");
}
|
--- a/src/main.rs
+++ b/src/main.rs
@@ ... @@
use std::env;
+use std::fs::File;
-#[macro_use]
-pub mod utils;
+mod utils;
+use self::utils::logger;
extern crate zwreec;
-
+#[macro_use] extern crate log;
+extern crate time;
+extern crate term;
fn main() {
- log_info!("main started");
+ //early init
+
+ //let _ = SimpleLogger::init(LogLevelFilter::Info);
+ let _ = logger::CombinedLogger::init(
+ vec![
+ logger::FileLogger::new(logger::LogLevelFilter::Trace, File::create("zwreec.log").unwrap()),
+ logger::TermLogger::new(logger::LogLevelFilter::Info),
+ ]
+ );
+
+ info!("main started");
@@ ... @@
// only for testing
- log_verbose!("(1) {}", zwreec::frontend::temp_hello());
- log_verbose!("(2) {}", zwreec::backend::temp_hello());
- log_verbose!("(3) {}", zwreec::file::temp_hello());
+ debug!("(1) {}", zwreec::frontend::temp_hello());
+ debug!("(2) {}", zwreec::backend::temp_hello());
+ debug!("(3) {}", zwreec::file::temp_hello());
- log_info!("main finished");
+ info!("main finished");
}
@@ ... @@
fn help() {
- log_error!("invalid arguments");
- log_info!("usage:\n zwreec <input_file> <output_file>");
+ error!("invalid arguments");
+ info!("usage:\n zwreec <input_file> <output_file>");
}
|
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,24 @@
CON use std::env;
ADD use std::fs::File;
CON
DEL #[macro_use]
DEL pub mod utils;
ADD mod utils;
ADD use self::utils::logger;
CON
CON extern crate zwreec;
DEL
ADD #[macro_use] extern crate log;
ADD extern crate time;
ADD extern crate term;
CON
CON fn main() {
DEL log_info!("main started");
ADD //early init
ADD
ADD //let _ = SimpleLogger::init(LogLevelFilter::Info);
ADD let _ = logger::CombinedLogger::init(
ADD vec![
ADD logger::FileLogger::new(logger::LogLevelFilter::Trace, File::create("zwreec.log").unwrap()),
ADD logger::TermLogger::new(logger::LogLevelFilter::Info),
ADD ]
ADD );
ADD
ADD info!("main started");
CON
@@ -36,7 +49,7 @@
CON // only for testing
DEL log_verbose!("(1) {}", zwreec::frontend::temp_hello());
DEL log_verbose!("(2) {}", zwreec::backend::temp_hello());
DEL log_verbose!("(3) {}", zwreec::file::temp_hello());
ADD debug!("(1) {}", zwreec::frontend::temp_hello());
ADD debug!("(2) {}", zwreec::backend::temp_hello());
ADD debug!("(3) {}", zwreec::file::temp_hello());
CON
DEL log_info!("main finished");
ADD info!("main finished");
CON }
@@ -44,4 +57,4 @@
CON fn help() {
DEL log_error!("invalid arguments");
DEL log_info!("usage:\n zwreec <input_file> <output_file>");
ADD error!("invalid arguments");
ADD info!("usage:\n zwreec <input_file> <output_file>");
CON }
|
<<<<<<< SEARCH
use std::env;
#[macro_use]
pub mod utils;
extern crate zwreec;
fn main() {
log_info!("main started");
// handling commandline parameters
=======
use std::env;
use std::fs::File;
mod utils;
use self::utils::logger;
extern crate zwreec;
#[macro_use] extern crate log;
extern crate time;
extern crate term;
fn main() {
//early init
//let _ = SimpleLogger::init(LogLevelFilter::Info);
let _ = logger::CombinedLogger::init(
vec![
logger::FileLogger::new(logger::LogLevelFilter::Trace, File::create("zwreec.log").unwrap()),
logger::TermLogger::new(logger::LogLevelFilter::Info),
]
);
info!("main started");
// handling commandline parameters
>>>>>>> REPLACE
<<<<<<< SEARCH
// only for testing
log_verbose!("(1) {}", zwreec::frontend::temp_hello());
log_verbose!("(2) {}", zwreec::backend::temp_hello());
log_verbose!("(3) {}", zwreec::file::temp_hello());
log_info!("main finished");
}
fn help() {
log_error!("invalid arguments");
log_info!("usage:\n zwreec <input_file> <output_file>");
}
=======
// only for testing
debug!("(1) {}", zwreec::frontend::temp_hello());
debug!("(2) {}", zwreec::backend::temp_hello());
debug!("(3) {}", zwreec::file::temp_hello());
info!("main finished");
}
fn help() {
error!("invalid arguments");
info!("usage:\n zwreec <input_file> <output_file>");
}
>>>>>>> REPLACE
|
sdh31/tower_defense
|
59a09e502f7a7995f3a181b42e29973576f7b0f1
|
src/main/java/player/TDPlayerEngine.java
|
java
|
mit
|
Make player talk to engine
|
package main.java.player;
import jgame.platform.JGEngine;
public class TDPlayerEngine extends JGEngine {
public TDPlayerEngine() {
super();
initEngineComponent(960, 640);
}
@Override
public void initCanvas() {
setCanvasSettings(15, 10, 32, 32, null, null, null);
}
@Override
public void initGame() {
setFrameRate(35, 2);
}
public void doFrame() {
}
}
|
package main.java.player;
import jgame.JGColor;
import jgame.JGPoint;
import jgame.platform.JGEngine;
import main.java.engine.Model;
public class TDPlayerEngine extends JGEngine {
private Model model;
public TDPlayerEngine() {
super();
initEngineComponent(960, 640);
}
@Override
public void initCanvas() {
setCanvasSettings(15, 10, 32, 32, null, JGColor.black, null);
}
@Override
public void initGame() {
setFrameRate(45, 1);
this.model = new Model();
model.setEngine(this);
model.addNewPlayer();
model.loadMap("testmap.json");
defineMedia("/main/resources/media.tbl");
model.setTemporaryWaveSchema();
}
@Override
public void paintFrame() {
highlightMouseoverTile();
displayGameStats();
}
private void highlightMouseoverTile() {
JGPoint mousePos = getMousePos();
int curXTilePos = mousePos.x/tileWidth() * tileWidth();
int curYTilePos = mousePos.y/tileHeight() * tileHeight();
this.drawRect(curXTilePos, curYTilePos, tileWidth(), tileHeight(), false, false, 1.0, JGColor.yellow);
}
private void displayGameStats() {
this.drawString("Score: "+model.getScore(), 50, 25, -1);
this.drawString("Lives left: "+model.getPlayerLife(), 50, 50, -1);
this.drawString("Money: "+model.getMoney(), 50, 75, -1);
this.drawString("Game clock: "+model.getGameClock(), 50, 100, -1);
}
@Override
public void doFrame() {
super.doFrame();
model.updateGameClockByFrame();
if (getMouseButton(1)) {
model.placeTower(getMouseX(), getMouseY());
}
if (model.getGameClock() % 100 == 0)
model.spawnNextWave();
moveObjects();
// model.spawnMonster(100, 150);
}
}
| 45
| 5
| 3
|
mixed
|
--- a/src/main/java/player/TDPlayerEngine.java
+++ b/src/main/java/player/TDPlayerEngine.java
@@ -2,5 +2,9 @@
+import jgame.JGColor;
+import jgame.JGPoint;
import jgame.platform.JGEngine;
+import main.java.engine.Model;
public class TDPlayerEngine extends JGEngine {
+ private Model model;
@@ -13,3 +17,3 @@
public void initCanvas() {
- setCanvasSettings(15, 10, 32, 32, null, null, null);
+ setCanvasSettings(15, 10, 32, 32, null, JGColor.black, null);
}
@@ -18,8 +22,44 @@
public void initGame() {
- setFrameRate(35, 2);
+ setFrameRate(45, 1);
+ this.model = new Model();
+ model.setEngine(this);
+ model.addNewPlayer();
+ model.loadMap("testmap.json");
+ defineMedia("/main/resources/media.tbl");
+ model.setTemporaryWaveSchema();
}
+
+ @Override
+ public void paintFrame() {
+ highlightMouseoverTile();
+ displayGameStats();
+ }
- public void doFrame() {
-
- }
+ private void highlightMouseoverTile() {
+ JGPoint mousePos = getMousePos();
+ int curXTilePos = mousePos.x/tileWidth() * tileWidth();
+ int curYTilePos = mousePos.y/tileHeight() * tileHeight();
+
+ this.drawRect(curXTilePos, curYTilePos, tileWidth(), tileHeight(), false, false, 1.0, JGColor.yellow);
+ }
+
+ private void displayGameStats() {
+ this.drawString("Score: "+model.getScore(), 50, 25, -1);
+ this.drawString("Lives left: "+model.getPlayerLife(), 50, 50, -1);
+ this.drawString("Money: "+model.getMoney(), 50, 75, -1);
+ this.drawString("Game clock: "+model.getGameClock(), 50, 100, -1);
+ }
+
+ @Override
+ public void doFrame() {
+ super.doFrame();
+ model.updateGameClockByFrame();
+ if (getMouseButton(1)) {
+ model.placeTower(getMouseX(), getMouseY());
+ }
+ if (model.getGameClock() % 100 == 0)
+ model.spawnNextWave();
+ moveObjects();
+// model.spawnMonster(100, 150);
+ }
}
|
--- a/src/main/java/player/TDPlayerEngine.java
+++ b/src/main/java/player/TDPlayerEngine.java
@@ ... @@
+import jgame.JGColor;
+import jgame.JGPoint;
import jgame.platform.JGEngine;
+import main.java.engine.Model;
public class TDPlayerEngine extends JGEngine {
+ private Model model;
@@ ... @@
public void initCanvas() {
- setCanvasSettings(15, 10, 32, 32, null, null, null);
+ setCanvasSettings(15, 10, 32, 32, null, JGColor.black, null);
}
@@ ... @@
public void initGame() {
- setFrameRate(35, 2);
+ setFrameRate(45, 1);
+ this.model = new Model();
+ model.setEngine(this);
+ model.addNewPlayer();
+ model.loadMap("testmap.json");
+ defineMedia("/main/resources/media.tbl");
+ model.setTemporaryWaveSchema();
}
+
+ @Override
+ public void paintFrame() {
+ highlightMouseoverTile();
+ displayGameStats();
+ }
- public void doFrame() {
-
- }
+ private void highlightMouseoverTile() {
+ JGPoint mousePos = getMousePos();
+ int curXTilePos = mousePos.x/tileWidth() * tileWidth();
+ int curYTilePos = mousePos.y/tileHeight() * tileHeight();
+
+ this.drawRect(curXTilePos, curYTilePos, tileWidth(), tileHeight(), false, false, 1.0, JGColor.yellow);
+ }
+
+ private void displayGameStats() {
+ this.drawString("Score: "+model.getScore(), 50, 25, -1);
+ this.drawString("Lives left: "+model.getPlayerLife(), 50, 50, -1);
+ this.drawString("Money: "+model.getMoney(), 50, 75, -1);
+ this.drawString("Game clock: "+model.getGameClock(), 50, 100, -1);
+ }
+
+ @Override
+ public void doFrame() {
+ super.doFrame();
+ model.updateGameClockByFrame();
+ if (getMouseButton(1)) {
+ model.placeTower(getMouseX(), getMouseY());
+ }
+ if (model.getGameClock() % 100 == 0)
+ model.spawnNextWave();
+ moveObjects();
+// model.spawnMonster(100, 150);
+ }
}
|
--- a/src/main/java/player/TDPlayerEngine.java
+++ b/src/main/java/player/TDPlayerEngine.java
@@ -2,5 +2,9 @@
CON
ADD import jgame.JGColor;
ADD import jgame.JGPoint;
CON import jgame.platform.JGEngine;
ADD import main.java.engine.Model;
CON
CON public class TDPlayerEngine extends JGEngine {
ADD private Model model;
CON
@@ -13,3 +17,3 @@
CON public void initCanvas() {
DEL setCanvasSettings(15, 10, 32, 32, null, null, null);
ADD setCanvasSettings(15, 10, 32, 32, null, JGColor.black, null);
CON }
@@ -18,8 +22,44 @@
CON public void initGame() {
DEL setFrameRate(35, 2);
ADD setFrameRate(45, 1);
ADD this.model = new Model();
ADD model.setEngine(this);
ADD model.addNewPlayer();
ADD model.loadMap("testmap.json");
ADD defineMedia("/main/resources/media.tbl");
ADD model.setTemporaryWaveSchema();
CON }
ADD
ADD @Override
ADD public void paintFrame() {
ADD highlightMouseoverTile();
ADD displayGameStats();
ADD }
CON
DEL public void doFrame() {
DEL
DEL }
ADD private void highlightMouseoverTile() {
ADD JGPoint mousePos = getMousePos();
ADD int curXTilePos = mousePos.x/tileWidth() * tileWidth();
ADD int curYTilePos = mousePos.y/tileHeight() * tileHeight();
ADD
ADD this.drawRect(curXTilePos, curYTilePos, tileWidth(), tileHeight(), false, false, 1.0, JGColor.yellow);
ADD }
ADD
ADD private void displayGameStats() {
ADD this.drawString("Score: "+model.getScore(), 50, 25, -1);
ADD this.drawString("Lives left: "+model.getPlayerLife(), 50, 50, -1);
ADD this.drawString("Money: "+model.getMoney(), 50, 75, -1);
ADD this.drawString("Game clock: "+model.getGameClock(), 50, 100, -1);
ADD }
ADD
ADD @Override
ADD public void doFrame() {
ADD super.doFrame();
ADD model.updateGameClockByFrame();
ADD if (getMouseButton(1)) {
ADD model.placeTower(getMouseX(), getMouseY());
ADD }
ADD if (model.getGameClock() % 100 == 0)
ADD model.spawnNextWave();
ADD moveObjects();
ADD // model.spawnMonster(100, 150);
ADD }
CON }
|
<<<<<<< SEARCH
package main.java.player;
import jgame.platform.JGEngine;
public class TDPlayerEngine extends JGEngine {
public TDPlayerEngine() {
=======
package main.java.player;
import jgame.JGColor;
import jgame.JGPoint;
import jgame.platform.JGEngine;
import main.java.engine.Model;
public class TDPlayerEngine extends JGEngine {
private Model model;
public TDPlayerEngine() {
>>>>>>> REPLACE
<<<<<<< SEARCH
@Override
public void initCanvas() {
setCanvasSettings(15, 10, 32, 32, null, null, null);
}
@Override
public void initGame() {
setFrameRate(35, 2);
}
public void doFrame() {
}
}
=======
@Override
public void initCanvas() {
setCanvasSettings(15, 10, 32, 32, null, JGColor.black, null);
}
@Override
public void initGame() {
setFrameRate(45, 1);
this.model = new Model();
model.setEngine(this);
model.addNewPlayer();
model.loadMap("testmap.json");
defineMedia("/main/resources/media.tbl");
model.setTemporaryWaveSchema();
}
@Override
public void paintFrame() {
highlightMouseoverTile();
displayGameStats();
}
private void highlightMouseoverTile() {
JGPoint mousePos = getMousePos();
int curXTilePos = mousePos.x/tileWidth() * tileWidth();
int curYTilePos = mousePos.y/tileHeight() * tileHeight();
this.drawRect(curXTilePos, curYTilePos, tileWidth(), tileHeight(), false, false, 1.0, JGColor.yellow);
}
private void displayGameStats() {
this.drawString("Score: "+model.getScore(), 50, 25, -1);
this.drawString("Lives left: "+model.getPlayerLife(), 50, 50, -1);
this.drawString("Money: "+model.getMoney(), 50, 75, -1);
this.drawString("Game clock: "+model.getGameClock(), 50, 100, -1);
}
@Override
public void doFrame() {
super.doFrame();
model.updateGameClockByFrame();
if (getMouseButton(1)) {
model.placeTower(getMouseX(), getMouseY());
}
if (model.getGameClock() % 100 == 0)
model.spawnNextWave();
moveObjects();
// model.spawnMonster(100, 150);
}
}
>>>>>>> REPLACE
|
Laastine/zombie-shooter
|
f175e21dad3722244a862269c5c3839a45ddbadf
|
src/character/orientation.rs
|
rust
|
apache-2.0
|
Add Stance struct for character stance
|
use std::fmt::{Display, Formatter, Result};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Orientation {
Right = 0,
UpRight = 1,
Up = 2,
UpLeft = 3,
Left = 4,
DownLeft = 5,
Down = 6,
DownRight = 7,
Still = 8,
}
impl Display for Orientation {
fn fmt(&self, f: &mut Formatter) -> Result {
match *self {
Orientation::Right => write!(f, "0"),
Orientation::UpRight => write!(f, "1"),
Orientation::Up => write!(f, "2"),
Orientation::UpLeft => write!(f, "3"),
Orientation::Left => write!(f, "4"),
Orientation::DownLeft => write!(f, "5"),
Orientation::Down => write!(f, "6"),
Orientation::DownRight => write!(f, "7"),
Orientation::Still => write!(f, "8"),
}
}
}
|
use std::fmt::{Display, Formatter, Result};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Orientation {
Right = 0,
UpRight = 1,
Up = 2,
UpLeft = 3,
Left = 4,
DownLeft = 5,
Down = 6,
DownRight = 7,
Still = 8,
}
impl Display for Orientation {
fn fmt(&self, f: &mut Formatter) -> Result {
match *self {
Orientation::Right => write!(f, "0"),
Orientation::UpRight => write!(f, "1"),
Orientation::Up => write!(f, "2"),
Orientation::UpLeft => write!(f, "3"),
Orientation::Left => write!(f, "4"),
Orientation::DownLeft => write!(f, "5"),
Orientation::Down => write!(f, "6"),
Orientation::DownRight => write!(f, "7"),
Orientation::Still => write!(f, "8"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Stance {
Normal = 0,
Firing = 1,
}
impl Display for Stance {
fn fmt(&self, f: &mut Formatter) -> Result {
match *self {
Stance::Normal => write!(f, "0"),
Stance::Firing => write!(f, "1"),
}
}
}
| 16
| 0
| 1
|
add_only
|
--- a/src/character/orientation.rs
+++ b/src/character/orientation.rs
@@ -30 +30,17 @@
}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Stance {
+ Normal = 0,
+ Firing = 1,
+}
+
+impl Display for Stance {
+ fn fmt(&self, f: &mut Formatter) -> Result {
+ match *self {
+ Stance::Normal => write!(f, "0"),
+ Stance::Firing => write!(f, "1"),
+ }
+ }
+}
+
|
--- a/src/character/orientation.rs
+++ b/src/character/orientation.rs
@@ ... @@
}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Stance {
+ Normal = 0,
+ Firing = 1,
+}
+
+impl Display for Stance {
+ fn fmt(&self, f: &mut Formatter) -> Result {
+ match *self {
+ Stance::Normal => write!(f, "0"),
+ Stance::Firing => write!(f, "1"),
+ }
+ }
+}
+
|
--- a/src/character/orientation.rs
+++ b/src/character/orientation.rs
@@ -30 +30,17 @@
CON }
ADD
ADD #[derive(Clone, Copy, Debug, PartialEq)]
ADD pub enum Stance {
ADD Normal = 0,
ADD Firing = 1,
ADD }
ADD
ADD impl Display for Stance {
ADD fn fmt(&self, f: &mut Formatter) -> Result {
ADD match *self {
ADD Stance::Normal => write!(f, "0"),
ADD Stance::Firing => write!(f, "1"),
ADD }
ADD }
ADD }
ADD
|
<<<<<<< SEARCH
}
}
=======
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Stance {
Normal = 0,
Firing = 1,
}
impl Display for Stance {
fn fmt(&self, f: &mut Formatter) -> Result {
match *self {
Stance::Normal => write!(f, "0"),
Stance::Firing => write!(f, "1"),
}
}
}
>>>>>>> REPLACE
|
max3163/jmeter
|
cc2bf2cbe435b46f10d576d25c73048cd4ac9736
|
src/jorphan/org/apache/jorphan/test/UnitTestManager.java
|
java
|
apache-2.0
|
Document that this part of the unit test code must remain in src/
git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@602096 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.test;
/**
* Implement this interface to work with the AllTests class. This interface
* allows AllTests to pass a configuration file to your application before
* running the junit unit tests.
*
* @see AllTests
* @author Michael Stover (mstover at apache.org)
* @version $Revision$
*/
public interface UnitTestManager {
/**
* Your implementation will be handed the filename that was provided to
* AllTests as a configuration file. It can hold whatever properties you
* need to configure your system prior to the unit tests running.
*
* @param filename
*/
public void initializeProperties(String filename);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.test;
/**
* Implement this interface to work with the AllTests class. This interface
* allows AllTests to pass a configuration file to your application before
* running the junit unit tests.
*
* @see AllTests
*
* N.B. This must be in the main src/ tree (not test/) because it is
* implemented by JMeterUtils
*/
public interface UnitTestManager {
/**
* Your implementation will be handed the filename that was provided to
* AllTests as a configuration file. It can hold whatever properties you
* need to configure your system prior to the unit tests running.
*
* @param filename
*/
public void initializeProperties(String filename);
}
| 3
| 2
| 1
|
mixed
|
--- a/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
+++ b/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
@@ -26,4 +26,5 @@
* @see AllTests
- * @author Michael Stover (mstover at apache.org)
- * @version $Revision$
+ *
+ * N.B. This must be in the main src/ tree (not test/) because it is
+ * implemented by JMeterUtils
*/
|
--- a/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
+++ b/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
@@ ... @@
* @see AllTests
- * @author Michael Stover (mstover at apache.org)
- * @version $Revision$
+ *
+ * N.B. This must be in the main src/ tree (not test/) because it is
+ * implemented by JMeterUtils
*/
|
--- a/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
+++ b/src/jorphan/org/apache/jorphan/test/UnitTestManager.java
@@ -26,4 +26,5 @@
CON * @see AllTests
DEL * @author Michael Stover (mstover at apache.org)
DEL * @version $Revision$
ADD *
ADD * N.B. This must be in the main src/ tree (not test/) because it is
ADD * implemented by JMeterUtils
CON */
|
<<<<<<< SEARCH
*
* @see AllTests
* @author Michael Stover (mstover at apache.org)
* @version $Revision$
*/
public interface UnitTestManager {
=======
*
* @see AllTests
*
* N.B. This must be in the main src/ tree (not test/) because it is
* implemented by JMeterUtils
*/
public interface UnitTestManager {
>>>>>>> REPLACE
|
alexchandel/rustboot
|
c6c63f24568cebd6951843ca12b4c9df00c0c1f9
|
common/kernel/process.rs
|
rust
|
mit
|
Fix memory access (0xc0000014) error
Now, self.eip is loaded before self.esp. This still doesn’t restore the
old stack pointer.
|
use core::clone::Clone;
use kernel::mm::{Flags, PageDirectory};
use kernel::mm::physical;
use util::rt::breakpoint;
use platform::cpu::mmu;
pub struct Process {
pub eip: u32,
pub esp: u32,
pub paging: physical::Phys<PageDirectory>
}
impl Process {
pub fn new() -> Process {
Process {
eip: 0,
esp: 0,
// paging: unsafe { physical::zero_alloc_frames(1) as *mut PageDirectory }
paging: unsafe { mmu::clone_directory() }
}
}
pub fn mmap(&self, page_ptr: *mut u8, size: uint, flags: Flags) {
unsafe {
(*self.paging.as_ptr()).map(page_ptr, size, flags);
}
}
#[cfg(target_arch = "x86")]
pub fn enter(&self) {
unsafe {
breakpoint();
// TODO need to store physical address
mmu::switch_directory(self.paging);
asm!("xor %eax, %eax
xor %edx, %edx
jmp *$0" :: "m"(self.eip), "{esp}"(self.esp) :: "volatile")
}
}
#[cfg(target_arch = "arm")]
pub fn enter(&self) {}
}
|
use core::clone::Clone;
use kernel::mm::{Flags, PageDirectory};
use kernel::mm::physical;
use util::rt::breakpoint;
use platform::cpu::mmu;
pub struct Process {
pub eip: u32,
pub esp: u32,
pub paging: physical::Phys<PageDirectory>
}
impl Process {
pub fn new() -> Process {
Process {
eip: 0,
esp: 0,
// paging: unsafe { physical::zero_alloc_frames(1) as *mut PageDirectory }
paging: unsafe { mmu::clone_directory() }
}
}
pub fn mmap(&self, page_ptr: *mut u8, size: uint, flags: Flags) {
unsafe {
(*self.paging.as_ptr()).map(page_ptr, size, flags);
}
}
#[cfg(target_arch = "x86")]
pub fn enter(&self) {
unsafe {
breakpoint();
// TODO need to store physical address
mmu::switch_directory(self.paging);
asm!("xor edx, edx
jmp DWORD PTR $0" :: "{eax}"(self.eip), "{esp}"(self.esp) :: "volatile", "intel");
}
}
#[cfg(target_arch = "arm")]
pub fn enter(&self) {}
}
| 2
| 3
| 1
|
mixed
|
--- a/common/kernel/process.rs
+++ b/common/kernel/process.rs
@@ -37,5 +37,4 @@
mmu::switch_directory(self.paging);
- asm!("xor %eax, %eax
- xor %edx, %edx
- jmp *$0" :: "m"(self.eip), "{esp}"(self.esp) :: "volatile")
+ asm!("xor edx, edx
+ jmp DWORD PTR $0" :: "{eax}"(self.eip), "{esp}"(self.esp) :: "volatile", "intel");
}
|
--- a/common/kernel/process.rs
+++ b/common/kernel/process.rs
@@ ... @@
mmu::switch_directory(self.paging);
- asm!("xor %eax, %eax
- xor %edx, %edx
- jmp *$0" :: "m"(self.eip), "{esp}"(self.esp) :: "volatile")
+ asm!("xor edx, edx
+ jmp DWORD PTR $0" :: "{eax}"(self.eip), "{esp}"(self.esp) :: "volatile", "intel");
}
|
--- a/common/kernel/process.rs
+++ b/common/kernel/process.rs
@@ -37,5 +37,4 @@
CON mmu::switch_directory(self.paging);
DEL asm!("xor %eax, %eax
DEL xor %edx, %edx
DEL jmp *$0" :: "m"(self.eip), "{esp}"(self.esp) :: "volatile")
ADD asm!("xor edx, edx
ADD jmp DWORD PTR $0" :: "{eax}"(self.eip), "{esp}"(self.esp) :: "volatile", "intel");
CON }
|
<<<<<<< SEARCH
// TODO need to store physical address
mmu::switch_directory(self.paging);
asm!("xor %eax, %eax
xor %edx, %edx
jmp *$0" :: "m"(self.eip), "{esp}"(self.esp) :: "volatile")
}
}
=======
// TODO need to store physical address
mmu::switch_directory(self.paging);
asm!("xor edx, edx
jmp DWORD PTR $0" :: "{eax}"(self.eip), "{esp}"(self.esp) :: "volatile", "intel");
}
}
>>>>>>> REPLACE
|
dati91/servo
|
d985741701c6e78a94d0074d6073cfaef30ff4c3
|
components/gfx/platform/dummy/font_template.rs
|
rust
|
mpl-2.0
|
Make dummy font implementation conform to API changes.
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use string_cache::Atom;
use webrender_traits::NativeFontHandle;
#[derive(Deserialize, Serialize, Debug)]
pub struct FontTemplateData {
pub bytes: Vec<u8>,
pub identifier: Atom,
}
impl FontTemplateData {
pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {
let bytes = match font_data {
Some(bytes) => {
bytes
},
None => {
unimplemented!()
}
};
FontTemplateData {
bytes: bytes,
identifier: identifier,
}
}
pub fn bytes(&self) -> Vec<u8> {
self.bytes.clone()
}
pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> {
Some(self.bytes())
}
pub fn native_font(&self) -> Option<NativeFontHandle> {
None
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io::Error;
use string_cache::Atom;
use webrender_traits::NativeFontHandle;
#[derive(Deserialize, Serialize, Debug)]
pub struct FontTemplateData {
pub bytes: Vec<u8>,
pub identifier: Atom,
}
impl FontTemplateData {
pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {
let bytes = match font_data {
Some(bytes) => {
bytes
},
None => {
unimplemented!()
}
};
Ok(FontTemplateData {
bytes: bytes,
identifier: identifier,
})
}
pub fn bytes(&self) -> Vec<u8> {
self.bytes.clone()
}
pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> {
Some(self.bytes())
}
pub fn native_font(&self) -> Option<NativeFontHandle> {
None
}
}
| 4
| 3
| 3
|
mixed
|
--- a/components/gfx/platform/dummy/font_template.rs
+++ b/components/gfx/platform/dummy/font_template.rs
@@ -4,2 +4,3 @@
+use std::io::Error;
use string_cache::Atom;
@@ -14,3 +15,3 @@
impl FontTemplateData {
- pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {
+ pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {
let bytes = match font_data {
@@ -24,6 +25,6 @@
- FontTemplateData {
+ Ok(FontTemplateData {
bytes: bytes,
identifier: identifier,
- }
+ })
}
|
--- a/components/gfx/platform/dummy/font_template.rs
+++ b/components/gfx/platform/dummy/font_template.rs
@@ ... @@
+use std::io::Error;
use string_cache::Atom;
@@ ... @@
impl FontTemplateData {
- pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {
+ pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {
let bytes = match font_data {
@@ ... @@
- FontTemplateData {
+ Ok(FontTemplateData {
bytes: bytes,
identifier: identifier,
- }
+ })
}
|
--- a/components/gfx/platform/dummy/font_template.rs
+++ b/components/gfx/platform/dummy/font_template.rs
@@ -4,2 +4,3 @@
CON
ADD use std::io::Error;
CON use string_cache::Atom;
@@ -14,3 +15,3 @@
CON impl FontTemplateData {
DEL pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {
ADD pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {
CON let bytes = match font_data {
@@ -24,6 +25,6 @@
CON
DEL FontTemplateData {
ADD Ok(FontTemplateData {
CON bytes: bytes,
CON identifier: identifier,
DEL }
ADD })
CON }
|
<<<<<<< SEARCH
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use string_cache::Atom;
use webrender_traits::NativeFontHandle;
=======
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io::Error;
use string_cache::Atom;
use webrender_traits::NativeFontHandle;
>>>>>>> REPLACE
<<<<<<< SEARCH
impl FontTemplateData {
pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {
let bytes = match font_data {
Some(bytes) => {
=======
impl FontTemplateData {
pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {
let bytes = match font_data {
Some(bytes) => {
>>>>>>> REPLACE
<<<<<<< SEARCH
};
FontTemplateData {
bytes: bytes,
identifier: identifier,
}
}
pub fn bytes(&self) -> Vec<u8> {
=======
};
Ok(FontTemplateData {
bytes: bytes,
identifier: identifier,
})
}
pub fn bytes(&self) -> Vec<u8> {
>>>>>>> REPLACE
|
verhoevenv/kotlin-koans
|
c84844765897e70d8100ea7a373fbb98bf948990
|
src/iii_conventions/MyDate.kt
|
kotlin
|
mit
|
Fix warning in ch 2 ex 26
|
package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int {
return when {
year.compareTo(other.year) != 0 -> year.compareTo(other.year)
month.compareTo(other.month) != 0 -> month.compareTo(other.month)
dayOfMonth.compareTo(other.dayOfMonth) != 0 -> dayOfMonth.compareTo(other.dayOfMonth)
else -> 0
}
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override infix operator fun contains(date: MyDate): Boolean {
return start < date && date <= endInclusive
}
override operator fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var current = start
override fun next(): MyDate {
val res = current
current = current.nextDay()
return res
}
override fun hasNext(): Boolean = current <= endInclusive
}
}
}
|
package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int {
return when {
year.compareTo(other.year) != 0 -> year.compareTo(other.year)
month.compareTo(other.month) != 0 -> month.compareTo(other.month)
dayOfMonth.compareTo(other.dayOfMonth) != 0 -> dayOfMonth.compareTo(other.dayOfMonth)
else -> 0
}
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override infix operator fun contains(value: MyDate): Boolean {
return start < value && value <= endInclusive
}
override operator fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var current = start
override fun next(): MyDate {
val res = current
current = current.nextDay()
return res
}
override fun hasNext(): Boolean = current <= endInclusive
}
}
}
| 2
| 2
| 1
|
mixed
|
--- a/src/iii_conventions/MyDate.kt
+++ b/src/iii_conventions/MyDate.kt
@@ -22,4 +22,4 @@
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
- override infix operator fun contains(date: MyDate): Boolean {
- return start < date && date <= endInclusive
+ override infix operator fun contains(value: MyDate): Boolean {
+ return start < value && value <= endInclusive
}
|
--- a/src/iii_conventions/MyDate.kt
+++ b/src/iii_conventions/MyDate.kt
@@ ... @@
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
- override infix operator fun contains(date: MyDate): Boolean {
- return start < date && date <= endInclusive
+ override infix operator fun contains(value: MyDate): Boolean {
+ return start < value && value <= endInclusive
}
|
--- a/src/iii_conventions/MyDate.kt
+++ b/src/iii_conventions/MyDate.kt
@@ -22,4 +22,4 @@
CON class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
DEL override infix operator fun contains(date: MyDate): Boolean {
DEL return start < date && date <= endInclusive
ADD override infix operator fun contains(value: MyDate): Boolean {
ADD return start < value && value <= endInclusive
CON }
|
<<<<<<< SEARCH
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override infix operator fun contains(date: MyDate): Boolean {
return start < date && date <= endInclusive
}
=======
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override infix operator fun contains(value: MyDate): Boolean {
return start < value && value <= endInclusive
}
>>>>>>> REPLACE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.