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
87
3.19k
CartoDB/camshaft
159781448d15bdd249c5d672830df7eb833e1af1
lib/node/nodes/source.js
javascript
bsd-3-clause
Clarify why columns must modify node id
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS, { beforeCreate: function(node) { // Last updated time in source node means data changed so it has to modify node.id node.setAttributeToModifyId('updatedAt'); } }); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS, { beforeCreate: function(node) { // Last updated time in source node means data changed so it has to modify node.id node.setAttributeToModifyId('updatedAt'); } }); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Columns have to modify Node.id(). // When a `select * from table` might end in a different set of columns we want to have a different node. // Current table triggers don't check DDL changes. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
3
3
1
mixed
--- a/lib/node/nodes/source.js +++ b/lib/node/nodes/source.js @@ -26,5 +26,5 @@ this.columns = columns; - // Makes columns affecting Node.id(). - // When a `select * from table` might end in a different set of columns - // we want to have a different node. + // Columns have to modify Node.id(). + // When a `select * from table` might end in a different set of columns we want to have a different node. + // Current table triggers don't check DDL changes. this.setAttributeToModifyId('columns');
--- a/lib/node/nodes/source.js +++ b/lib/node/nodes/source.js @@ ... @@ this.columns = columns; - // Makes columns affecting Node.id(). - // When a `select * from table` might end in a different set of columns - // we want to have a different node. + // Columns have to modify Node.id(). + // When a `select * from table` might end in a different set of columns we want to have a different node. + // Current table triggers don't check DDL changes. this.setAttributeToModifyId('columns');
--- a/lib/node/nodes/source.js +++ b/lib/node/nodes/source.js @@ -26,5 +26,5 @@ CON this.columns = columns; DEL // Makes columns affecting Node.id(). DEL // When a `select * from table` might end in a different set of columns DEL // we want to have a different node. ADD // Columns have to modify Node.id(). ADD // When a `select * from table` might end in a different set of columns we want to have a different node. ADD // Current table triggers don't check DDL changes. CON this.setAttributeToModifyId('columns');
<<<<<<< SEARCH Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; ======= Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Columns have to modify Node.id(). // When a `select * from table` might end in a different set of columns we want to have a different node. // Current table triggers don't check DDL changes. this.setAttributeToModifyId('columns'); }; >>>>>>> REPLACE
garydonovan/google-maps-services-python
3de90ff1f33d05d30e295279e7ad4cdd0e6bbc9b
setup.py
python
apache-2.0
Change from planning to in beta
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2.0-dev', description='API Client library for Google Maps', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Internet', ] )
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2.0-dev', description='API Client library for Google Maps', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Internet', ] )
1
1
1
mixed
--- a/setup.py +++ b/setup.py @@ -29,3 +29,3 @@ install_requires=requirements, - classifiers=['Development Status :: 1 - Planning', + classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers',
--- a/setup.py +++ b/setup.py @@ ... @@ install_requires=requirements, - classifiers=['Development Status :: 1 - Planning', + classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers',
--- a/setup.py +++ b/setup.py @@ -29,3 +29,3 @@ CON install_requires=requirements, DEL classifiers=['Development Status :: 1 - Planning', ADD classifiers=['Development Status :: 4 - Beta', CON 'Intended Audience :: Developers',
<<<<<<< SEARCH setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', ======= setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', >>>>>>> REPLACE
Waboodoo/HTTP-Shortcuts
5184e2b97f6d948a7ca56225b202cb51e9e81a89
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt
kotlin
mit
Use same user agent for webviews as for HTTP requests
package ch.rmy.android.http_shortcuts.activities.response import android.content.Context import android.util.AttributeSet import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import ch.rmy.android.http_shortcuts.extensions.consume import ch.rmy.android.http_shortcuts.extensions.mapIf import ch.rmy.android.http_shortcuts.extensions.openURL class ResponseWebView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : WebView(context, attrs) { init { webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String) = consume { context.openURL(url) } } with(settings) { setAppCacheEnabled(false) cacheMode = WebSettings.LOAD_NO_CACHE javaScriptEnabled = false saveFormData = false allowContentAccess = false allowFileAccess = false allowFileAccessFromFileURLs = false allowUniversalAccessFromFileURLs = false } } fun loadFromString(data: String, baseUrl: String?) { val url = baseUrl ?.mapIf(!baseUrl.endsWith("/")) { it.plus("/") } loadDataWithBaseURL(url, data, "text/html", "UTF-8", null) } }
package ch.rmy.android.http_shortcuts.activities.response import android.content.Context import android.util.AttributeSet import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import ch.rmy.android.http_shortcuts.extensions.consume import ch.rmy.android.http_shortcuts.extensions.mapIf import ch.rmy.android.http_shortcuts.extensions.openURL import ch.rmy.android.http_shortcuts.utils.UserAgentUtil class ResponseWebView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : WebView(context, attrs) { init { webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String) = consume { context.openURL(url) } } with(settings) { setAppCacheEnabled(false) cacheMode = WebSettings.LOAD_NO_CACHE javaScriptEnabled = false saveFormData = false allowContentAccess = false allowFileAccess = false allowFileAccessFromFileURLs = false allowUniversalAccessFromFileURLs = false userAgentString = UserAgentUtil.userAgent } } fun loadFromString(data: String, baseUrl: String?) { val url = baseUrl ?.mapIf(!baseUrl.endsWith("/")) { it.plus("/") } loadDataWithBaseURL(url, data, "text/html", "UTF-8", null) } }
2
0
2
add_only
--- a/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt +++ b/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt @@ -10,2 +10,3 @@ import ch.rmy.android.http_shortcuts.extensions.openURL +import ch.rmy.android.http_shortcuts.utils.UserAgentUtil @@ -32,2 +33,3 @@ allowUniversalAccessFromFileURLs = false + userAgentString = UserAgentUtil.userAgent }
--- a/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt +++ b/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt @@ ... @@ import ch.rmy.android.http_shortcuts.extensions.openURL +import ch.rmy.android.http_shortcuts.utils.UserAgentUtil @@ ... @@ allowUniversalAccessFromFileURLs = false + userAgentString = UserAgentUtil.userAgent }
--- a/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt +++ b/HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/ResponseWebView.kt @@ -10,2 +10,3 @@ CON import ch.rmy.android.http_shortcuts.extensions.openURL ADD import ch.rmy.android.http_shortcuts.utils.UserAgentUtil CON @@ -32,2 +33,3 @@ CON allowUniversalAccessFromFileURLs = false ADD userAgentString = UserAgentUtil.userAgent CON }
<<<<<<< SEARCH import ch.rmy.android.http_shortcuts.extensions.mapIf import ch.rmy.android.http_shortcuts.extensions.openURL class ResponseWebView @JvmOverloads constructor( ======= import ch.rmy.android.http_shortcuts.extensions.mapIf import ch.rmy.android.http_shortcuts.extensions.openURL import ch.rmy.android.http_shortcuts.utils.UserAgentUtil class ResponseWebView @JvmOverloads constructor( >>>>>>> REPLACE
peerigon/dynamic-config
47058708f45d5f22df203d6b8be8909192636e40
lib/index.js
javascript
mit
Refactor dynamic config using smaller function that can be intercepted by alamid-plugin
"use strict"; var path = require("path"), argv = require('minimist')(process.argv.slice(2)); function readDynamicConfig(basePath, fileName) { var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, filePath = path.join(basePath, env, fileName), config; if (readDynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; } readDynamicConfig.options = { defaultEnv: "develop", log: false }; module.exports = readDynamicConfig;
"use strict"; var use = require("alamid-plugin/use.js"); var path = require("path"), argv = require("minimist")(process.argv.slice(2)); function dynamicConfig(basePath, fileName) { var env = dynamicConfig.getEnv(), filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } config = dynamicConfig.loadConfig(filePath); return config; } dynamicConfig.getEnv = function() { return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; }; dynamicConfig.getFilePath = function(basePath, env, fileName) { return path.join(basePath, env, fileName); }; dynamicConfig.loadConfig = function(filePath) { var config; try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; }; dynamicConfig.options = { defaultEnv: "develop", log: false }; dynamicConfig.use = use; module.exports = dynamicConfig;
29
8
3
mixed
--- a/lib/index.js +++ b/lib/index.js @@ -2,13 +2,32 @@ +var use = require("alamid-plugin/use.js"); + var path = require("path"), - argv = require('minimist')(process.argv.slice(2)); + argv = require("minimist")(process.argv.slice(2)); -function readDynamicConfig(basePath, fileName) { - var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, - filePath = path.join(basePath, env, fileName), +function dynamicConfig(basePath, fileName) { + + var env = dynamicConfig.getEnv(), + filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; - if (readDynamicConfig.options.log) { + if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } + + config = dynamicConfig.loadConfig(filePath); + + return config; +} + +dynamicConfig.getEnv = function() { + return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; +}; + +dynamicConfig.getFilePath = function(basePath, env, fileName) { + return path.join(basePath, env, fileName); +}; + +dynamicConfig.loadConfig = function(filePath) { + var config; @@ -28,5 +47,5 @@ return config; -} +}; -readDynamicConfig.options = { +dynamicConfig.options = { defaultEnv: "develop", @@ -35,2 +54,4 @@ -module.exports = readDynamicConfig; +dynamicConfig.use = use; + +module.exports = dynamicConfig;
--- a/lib/index.js +++ b/lib/index.js @@ ... @@ +var use = require("alamid-plugin/use.js"); + var path = require("path"), - argv = require('minimist')(process.argv.slice(2)); + argv = require("minimist")(process.argv.slice(2)); -function readDynamicConfig(basePath, fileName) { - var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, - filePath = path.join(basePath, env, fileName), +function dynamicConfig(basePath, fileName) { + + var env = dynamicConfig.getEnv(), + filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; - if (readDynamicConfig.options.log) { + if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } + + config = dynamicConfig.loadConfig(filePath); + + return config; +} + +dynamicConfig.getEnv = function() { + return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; +}; + +dynamicConfig.getFilePath = function(basePath, env, fileName) { + return path.join(basePath, env, fileName); +}; + +dynamicConfig.loadConfig = function(filePath) { + var config; @@ ... @@ return config; -} +}; -readDynamicConfig.options = { +dynamicConfig.options = { defaultEnv: "develop", @@ ... @@ -module.exports = readDynamicConfig; +dynamicConfig.use = use; + +module.exports = dynamicConfig;
--- a/lib/index.js +++ b/lib/index.js @@ -2,13 +2,32 @@ CON ADD var use = require("alamid-plugin/use.js"); ADD CON var path = require("path"), DEL argv = require('minimist')(process.argv.slice(2)); ADD argv = require("minimist")(process.argv.slice(2)); CON DEL function readDynamicConfig(basePath, fileName) { DEL var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, DEL filePath = path.join(basePath, env, fileName), ADD function dynamicConfig(basePath, fileName) { ADD ADD var env = dynamicConfig.getEnv(), ADD filePath = dynamicConfig.getFilePath(basePath, env, fileName), CON config; CON DEL if (readDynamicConfig.options.log) { ADD if (dynamicConfig.options.log) { CON console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); CON } ADD ADD config = dynamicConfig.loadConfig(filePath); ADD ADD return config; ADD } ADD ADD dynamicConfig.getEnv = function() { ADD return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; ADD }; ADD ADD dynamicConfig.getFilePath = function(basePath, env, fileName) { ADD return path.join(basePath, env, fileName); ADD }; ADD ADD dynamicConfig.loadConfig = function(filePath) { ADD var config; CON @@ -28,5 +47,5 @@ CON return config; DEL } ADD }; CON DEL readDynamicConfig.options = { ADD dynamicConfig.options = { CON defaultEnv: "develop", @@ -35,2 +54,4 @@ CON DEL module.exports = readDynamicConfig; ADD dynamicConfig.use = use; ADD ADD module.exports = dynamicConfig;
<<<<<<< SEARCH "use strict"; var path = require("path"), argv = require('minimist')(process.argv.slice(2)); function readDynamicConfig(basePath, fileName) { var env = process.env.env || argv.env || argv.ENV || readDynamicConfig.options.defaultEnv, filePath = path.join(basePath, env, fileName), config; if (readDynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } try { ======= "use strict"; var use = require("alamid-plugin/use.js"); var path = require("path"), argv = require("minimist")(process.argv.slice(2)); function dynamicConfig(basePath, fileName) { var env = dynamicConfig.getEnv(), filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } config = dynamicConfig.loadConfig(filePath); return config; } dynamicConfig.getEnv = function() { return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; }; dynamicConfig.getFilePath = function(basePath, env, fileName) { return path.join(basePath, env, fileName); }; dynamicConfig.loadConfig = function(filePath) { var config; try { >>>>>>> REPLACE
NCIP/psc
280ff5069386ab7dd6b105eb5658bdbd69809c66
src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java
java
bsd-3-clause
Add TODO about using an enum instead of an unconstrained string
package edu.northwestern.bioinformatics.studycalendar.domain; import javax.persistence.Entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Transient; /** * @author Nataliya Shurupova */ @Entity @DiscriminatorValue(value="2") public class DayOfTheWeek extends Holiday { private String dayOfTheWeek; @Transient public String getDisplayName() { return getDayOfTheWeek(); } @Transient public int getDayOfTheWeekInteger() { return mapDayNameToInteger(getDayOfTheWeek()); } public String getDayOfTheWeek() { return this.dayOfTheWeek; } public void setDayOfTheWeek(String dayOfTheWeek) { this.dayOfTheWeek = dayOfTheWeek; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DayOfTheWeek that = (DayOfTheWeek) o; if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null) return false; return true; } @Override public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("Id = "); sb.append(getId()); sb.append(" DayOfTheWeek = "); sb.append(getDayOfTheWeek()); sb.append(super.toString()); return sb.toString(); } }
package edu.northwestern.bioinformatics.studycalendar.domain; import javax.persistence.Entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Transient; /** * @author Nataliya Shurupova */ @Entity @DiscriminatorValue(value="2") public class DayOfTheWeek extends Holiday { // TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum private String dayOfTheWeek; @Transient public String getDisplayName() { return getDayOfTheWeek(); } @Transient public int getDayOfTheWeekInteger() { return mapDayNameToInteger(getDayOfTheWeek()); } public String getDayOfTheWeek() { return this.dayOfTheWeek; } public void setDayOfTheWeek(String dayOfTheWeek) { this.dayOfTheWeek = dayOfTheWeek; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DayOfTheWeek that = (DayOfTheWeek) o; if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null) return false; return true; } @Override public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("Id = "); sb.append(getId()); sb.append(" DayOfTheWeek = "); sb.append(getDayOfTheWeek()); sb.append(super.toString()); return sb.toString(); } }
1
0
1
add_only
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java +++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java @@ -14,2 +14,3 @@ public class DayOfTheWeek extends Holiday { + // TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum private String dayOfTheWeek;
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java +++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java @@ ... @@ public class DayOfTheWeek extends Holiday { + // TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum private String dayOfTheWeek;
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java +++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/DayOfTheWeek.java @@ -14,2 +14,3 @@ CON public class DayOfTheWeek extends Holiday { ADD // TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum CON private String dayOfTheWeek;
<<<<<<< SEARCH @DiscriminatorValue(value="2") public class DayOfTheWeek extends Holiday { private String dayOfTheWeek; ======= @DiscriminatorValue(value="2") public class DayOfTheWeek extends Holiday { // TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum private String dayOfTheWeek; >>>>>>> REPLACE
hansihe/Rustler
362b291574e42e6698b0a354736fda29e50cf4eb
src/wrapper/term.rs
rust
apache-2.0
Fix unlikely-to-hit logic bug in Debug support.
use std::fmt; use std::os::raw::c_char; use super::nif_interface::{ NIF_TERM }; pub fn fmt<'a>(term: NIF_TERM, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { const SIZE: usize = 1024; let mut bytes: Vec<u8> = Vec::with_capacity(SIZE); let mut n = 0; for _ in 0 .. 10 { let i = unsafe { enif_snprintf!(bytes.as_mut_ptr() as *mut c_char, bytes.capacity(), b"%T\x00" as *const u8 as *const c_char, term) }; if i < 0 { // Do not propagate an error, because string formatting is // supposed to be infallible. break; } n = i as usize; if n >= bytes.capacity() { // Bizarrely, enif_snprintf consistently underestimates the // amount of memory it will need to write long lists. To try to // avoid going around the loop again, double the estimate. bytes.reserve_exact(2 * n + 1); } else { break; } } unsafe { bytes.set_len(n); } f.write_str(&String::from_utf8_lossy(&bytes)) }
use std::fmt; use std::os::raw::c_char; use super::nif_interface::{ NIF_TERM }; pub fn fmt<'a>(term: NIF_TERM, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { const SIZE: usize = 1024; let mut bytes: Vec<u8> = Vec::with_capacity(SIZE); let mut n = 0; for _ in 0 .. 10 { let i = unsafe { enif_snprintf!(bytes.as_mut_ptr() as *mut c_char, bytes.capacity(), b"%T\x00" as *const u8 as *const c_char, term) }; if i < 0 { // Do not propagate an error, because string formatting is // supposed to be infallible. break; } n = i as usize; if n >= bytes.capacity() { // Bizarrely, enif_snprintf consistently underestimates the // amount of memory it will need to write long lists. To try to // avoid going around the loop again, double the estimate. bytes.reserve_exact(2 * n + 1); // Ensure that the `set_len` call below does not expose // uninitialized bytes if we give up after 10 attempts. n = 0; } else { break; } } unsafe { bytes.set_len(n); } f.write_str(&String::from_utf8_lossy(&bytes)) }
4
0
1
add_only
--- a/src/wrapper/term.rs +++ b/src/wrapper/term.rs @@ -30,2 +30,6 @@ bytes.reserve_exact(2 * n + 1); + + // Ensure that the `set_len` call below does not expose + // uninitialized bytes if we give up after 10 attempts. + n = 0; } else {
--- a/src/wrapper/term.rs +++ b/src/wrapper/term.rs @@ ... @@ bytes.reserve_exact(2 * n + 1); + + // Ensure that the `set_len` call below does not expose + // uninitialized bytes if we give up after 10 attempts. + n = 0; } else {
--- a/src/wrapper/term.rs +++ b/src/wrapper/term.rs @@ -30,2 +30,6 @@ CON bytes.reserve_exact(2 * n + 1); ADD ADD // Ensure that the `set_len` call below does not expose ADD // uninitialized bytes if we give up after 10 attempts. ADD n = 0; CON } else {
<<<<<<< SEARCH // avoid going around the loop again, double the estimate. bytes.reserve_exact(2 * n + 1); } else { break; ======= // avoid going around the loop again, double the estimate. bytes.reserve_exact(2 * n + 1); // Ensure that the `set_len` call below does not expose // uninitialized bytes if we give up after 10 attempts. n = 0; } else { break; >>>>>>> REPLACE
athy/fape
b3888e27b899b540b95a16757647d9eee446b82c
src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java
java
bsd-2-clause
Add tie breaker for plan comparators. First choose the one with shortest makespan. If it still a tie, use the id of the state to make sure the output is deterministic.
package fape.core.planning.search.strategies.plans; import fape.core.planning.states.State; import java.util.LinkedList; import java.util.List; /** * Used to use a sequence of PartialPlanComparator as one. * * The basic algorithm for comparing two partial plans is to apply the comparators in sequence until it results in an ordering * between the two plans. If no comparator is found, the plans are left unordered. */ public class SeqPlanComparator implements PartialPlanComparator { List<PartialPlanComparator> comparators; public SeqPlanComparator(List<PartialPlanComparator> comparators) { this.comparators = new LinkedList<>(comparators); } @Override public String shortName() { String ret = ""; for(PartialPlanComparator comp : comparators) { ret += comp.shortName() + ","; } return ret.substring(0, ret.length()-1); } @Override public int compare(State state, State state2) { for(PartialPlanComparator comp : comparators) { int res = comp.compare(state, state2); if(res != 0) { return res; } } // no resolver could rank those flaws. return 0; } }
package fape.core.planning.search.strategies.plans; import fape.core.planning.states.State; import java.util.LinkedList; import java.util.List; /** * Used to use a sequence of PartialPlanComparator as one. * * The basic algorithm for comparing two partial plans is to apply the comparators in sequence until it results in an ordering * between the two plans. If no comparator is found, the plans are left unordered. */ public class SeqPlanComparator implements PartialPlanComparator { List<PartialPlanComparator> comparators; public SeqPlanComparator(List<PartialPlanComparator> comparators) { this.comparators = new LinkedList<>(comparators); } @Override public String shortName() { String ret = ""; for(PartialPlanComparator comp : comparators) { ret += comp.shortName() + ","; } return ret.substring(0, ret.length()-1); } @Override public int compare(State state, State state2) { for(PartialPlanComparator comp : comparators) { int res = comp.compare(state, state2); if(res != 0) { return res; } } // tie breaker: makespan int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end()); if(diffMakespan != 0) return diffMakespan; // no ranking done, use mID to make deterministic return state.mID - state2.mID; } }
8
2
1
mixed
--- a/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java +++ b/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java @@ -38,4 +38,10 @@ } - // no resolver could rank those flaws. - return 0; + + // tie breaker: makespan + int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end()); + if(diffMakespan != 0) + return diffMakespan; + + // no ranking done, use mID to make deterministic + return state.mID - state2.mID; }
--- a/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java +++ b/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java @@ ... @@ } - // no resolver could rank those flaws. - return 0; + + // tie breaker: makespan + int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end()); + if(diffMakespan != 0) + return diffMakespan; + + // no ranking done, use mID to make deterministic + return state.mID - state2.mID; }
--- a/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java +++ b/src/main/java/fape/core/planning/search/strategies/plans/SeqPlanComparator.java @@ -38,4 +38,10 @@ CON } DEL // no resolver could rank those flaws. DEL return 0; ADD ADD // tie breaker: makespan ADD int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end()); ADD if(diffMakespan != 0) ADD return diffMakespan; ADD ADD // no ranking done, use mID to make deterministic ADD return state.mID - state2.mID; CON }
<<<<<<< SEARCH } } // no resolver could rank those flaws. return 0; } } ======= } } // tie breaker: makespan int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end()); if(diffMakespan != 0) return diffMakespan; // no ranking done, use mID to make deterministic return state.mID - state2.mID; } } >>>>>>> REPLACE
axelrindle/SimpleCoins
fcced317586bf23cab4226f796da28b531e8684a
src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt
kotlin
mit
Use reloadAll() to reload all config files
package de.axelrindle.simplecoins.command import de.axelrindle.pocketknife.PocketCommand import de.axelrindle.simplecoins.CoinManager import de.axelrindle.simplecoins.SimpleCoins import org.bukkit.command.Command import org.bukkit.command.CommandSender internal class ReloadCommand : PocketCommand() { override fun getName(): String { return "reload" } override fun getDescription(): String { return "Reloads the configuration from disk." } override fun getPermission(): String { return "simplecoins.reload" } override fun getUsage(): String { return "/simplecoins reload" } override fun handle(sender: CommandSender, command: Command, args: Array<out String>): Boolean { sender.sendMessage("${SimpleCoins.prefix} §bReloading...") try { // unload the CoinManager CoinManager.close() // reload the config files and re-init the CoinManager SimpleCoins.instance!!.pocketConfig.apply { reload("config") reload("database") } CoinManager.init(SimpleCoins.instance!!.pocketConfig) sender.sendMessage("${SimpleCoins.prefix} §aDone.") } catch (e: Exception) { sender.sendMessage("${SimpleCoins.prefix} §cSomething went wrong! Check the console for more information.") e.printStackTrace() } return true } override fun sendHelp(sender: CommandSender) { sender.sendMessage(getUsage()) } }
package de.axelrindle.simplecoins.command import de.axelrindle.pocketknife.PocketCommand import de.axelrindle.simplecoins.CoinManager import de.axelrindle.simplecoins.SimpleCoins import org.bukkit.command.Command import org.bukkit.command.CommandSender internal class ReloadCommand : PocketCommand() { override fun getName(): String { return "reload" } override fun getDescription(): String { return "Reloads the configuration from disk." } override fun getPermission(): String { return "simplecoins.reload" } override fun getUsage(): String { return "/simplecoins reload" } override fun handle(sender: CommandSender, command: Command, args: Array<out String>): Boolean { sender.sendMessage("${SimpleCoins.prefix} §bReloading...") try { // unload the CoinManager CoinManager.close() // reload the config files and re-init the CoinManager SimpleCoins.instance!!.apply { pocketConfig.reloadAll() CoinManager.init(pocketConfig) } sender.sendMessage("${SimpleCoins.prefix} §aDone.") } catch (e: Exception) { sender.sendMessage("${SimpleCoins.prefix} §cSomething went wrong! Check the console for more information.") e.printStackTrace() } return true } override fun sendHelp(sender: CommandSender) { sender.sendMessage(getUsage()) } }
3
4
1
mixed
--- a/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt +++ b/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt @@ -34,7 +34,6 @@ // reload the config files and re-init the CoinManager - SimpleCoins.instance!!.pocketConfig.apply { - reload("config") - reload("database") + SimpleCoins.instance!!.apply { + pocketConfig.reloadAll() + CoinManager.init(pocketConfig) } - CoinManager.init(SimpleCoins.instance!!.pocketConfig)
--- a/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt +++ b/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt @@ ... @@ // reload the config files and re-init the CoinManager - SimpleCoins.instance!!.pocketConfig.apply { - reload("config") - reload("database") + SimpleCoins.instance!!.apply { + pocketConfig.reloadAll() + CoinManager.init(pocketConfig) } - CoinManager.init(SimpleCoins.instance!!.pocketConfig)
--- a/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt +++ b/src/main/kotlin/de/axelrindle/simplecoins/command/ReloadCommand.kt @@ -34,7 +34,6 @@ CON // reload the config files and re-init the CoinManager DEL SimpleCoins.instance!!.pocketConfig.apply { DEL reload("config") DEL reload("database") ADD SimpleCoins.instance!!.apply { ADD pocketConfig.reloadAll() ADD CoinManager.init(pocketConfig) CON } DEL CoinManager.init(SimpleCoins.instance!!.pocketConfig) CON
<<<<<<< SEARCH // reload the config files and re-init the CoinManager SimpleCoins.instance!!.pocketConfig.apply { reload("config") reload("database") } CoinManager.init(SimpleCoins.instance!!.pocketConfig) sender.sendMessage("${SimpleCoins.prefix} §aDone.") ======= // reload the config files and re-init the CoinManager SimpleCoins.instance!!.apply { pocketConfig.reloadAll() CoinManager.init(pocketConfig) } sender.sendMessage("${SimpleCoins.prefix} §aDone.") >>>>>>> REPLACE
blackbeam/mysql_async
129fa2e0c5a8d0d5117b64741034afd8a42c163a
src/conn/futures/prep_exec.rs
rust
apache-2.0
Use steps! for PrepExec future
use conn::Conn; use conn::futures::query_result::BinQueryResult; use conn::futures::Prepare; use conn::stmt::futures::Execute; use conn::stmt::Stmt; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use value::Params; enum Step { Prepare(Prepare), Execute(Execute), } enum Out { Prepare(Stmt), Execute(BinQueryResult), } pub struct PrepExec { step: Step, params: Option<Params>, } pub fn new<Q, P>(conn: Conn, query: Q, params: P) -> PrepExec where Q: AsRef<str>, P: Into<Params>, { PrepExec { step: Step::Prepare(conn.prepare(query)), params: Some(params.into()), } } impl PrepExec { fn either_poll(&mut self) -> Result<Async<Out>> { match self.step { Step::Prepare(ref mut fut) => Ok(Ready(Out::Prepare(try_ready!(fut.poll())))), Step::Execute(ref mut fut) => Ok(Ready(Out::Execute(try_ready!(fut.poll())))), } } } impl Future for PrepExec { type Item = BinQueryResult; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match try_ready!(self.either_poll()) { Out::Prepare(stmt) => { let params = self.params.take().unwrap(); self.step = Step::Execute(stmt.execute(params)); self.poll() }, Out::Execute(query_result) => Ok(Ready(query_result)), } } }
use conn::Conn; use conn::futures::query_result::BinQueryResult; use conn::futures::Prepare; use conn::stmt::futures::Execute; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use std::mem; use value::Params; steps! { PrepExec { Prepare(Prepare), Execute(Execute), } } pub struct PrepExec { step: Step, params: Params, } pub fn new<Q, P>(conn: Conn, query: Q, params: P) -> PrepExec where Q: AsRef<str>, P: Into<Params>, { PrepExec { step: Step::Prepare(conn.prepare(query)), params: params.into(), } } impl Future for PrepExec { type Item = BinQueryResult; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match try_ready!(self.either_poll()) { Out::Prepare(stmt) => { let params = mem::replace(&mut self.params, Params::Empty); self.step = Step::Execute(stmt.execute(params)); self.poll() }, Out::Execute(query_result) => Ok(Ready(query_result)), } } }
9
21
6
mixed
--- a/src/conn/futures/prep_exec.rs +++ b/src/conn/futures/prep_exec.rs @@ -4,3 +4,2 @@ use conn::stmt::futures::Execute; -use conn::stmt::Stmt; use errors::*; @@ -10,2 +9,3 @@ use lib_futures::Poll; +use std::mem; use value::Params; @@ -13,10 +13,7 @@ -enum Step { - Prepare(Prepare), - Execute(Execute), -} - -enum Out { - Prepare(Stmt), - Execute(BinQueryResult), +steps! { + PrepExec { + Prepare(Prepare), + Execute(Execute), + } } @@ -25,3 +22,3 @@ step: Step, - params: Option<Params>, + params: Params, } @@ -34,12 +31,3 @@ step: Step::Prepare(conn.prepare(query)), - params: Some(params.into()), - } -} - -impl PrepExec { - fn either_poll(&mut self) -> Result<Async<Out>> { - match self.step { - Step::Prepare(ref mut fut) => Ok(Ready(Out::Prepare(try_ready!(fut.poll())))), - Step::Execute(ref mut fut) => Ok(Ready(Out::Execute(try_ready!(fut.poll())))), - } + params: params.into(), } @@ -54,3 +42,3 @@ Out::Prepare(stmt) => { - let params = self.params.take().unwrap(); + let params = mem::replace(&mut self.params, Params::Empty); self.step = Step::Execute(stmt.execute(params));
--- a/src/conn/futures/prep_exec.rs +++ b/src/conn/futures/prep_exec.rs @@ ... @@ use conn::stmt::futures::Execute; -use conn::stmt::Stmt; use errors::*; @@ ... @@ use lib_futures::Poll; +use std::mem; use value::Params; @@ ... @@ -enum Step { - Prepare(Prepare), - Execute(Execute), -} - -enum Out { - Prepare(Stmt), - Execute(BinQueryResult), +steps! { + PrepExec { + Prepare(Prepare), + Execute(Execute), + } } @@ ... @@ step: Step, - params: Option<Params>, + params: Params, } @@ ... @@ step: Step::Prepare(conn.prepare(query)), - params: Some(params.into()), - } -} - -impl PrepExec { - fn either_poll(&mut self) -> Result<Async<Out>> { - match self.step { - Step::Prepare(ref mut fut) => Ok(Ready(Out::Prepare(try_ready!(fut.poll())))), - Step::Execute(ref mut fut) => Ok(Ready(Out::Execute(try_ready!(fut.poll())))), - } + params: params.into(), } @@ ... @@ Out::Prepare(stmt) => { - let params = self.params.take().unwrap(); + let params = mem::replace(&mut self.params, Params::Empty); self.step = Step::Execute(stmt.execute(params));
--- a/src/conn/futures/prep_exec.rs +++ b/src/conn/futures/prep_exec.rs @@ -4,3 +4,2 @@ CON use conn::stmt::futures::Execute; DEL use conn::stmt::Stmt; CON use errors::*; @@ -10,2 +9,3 @@ CON use lib_futures::Poll; ADD use std::mem; CON use value::Params; @@ -13,10 +13,7 @@ CON DEL enum Step { DEL Prepare(Prepare), DEL Execute(Execute), DEL } DEL DEL enum Out { DEL Prepare(Stmt), DEL Execute(BinQueryResult), ADD steps! { ADD PrepExec { ADD Prepare(Prepare), ADD Execute(Execute), ADD } CON } @@ -25,3 +22,3 @@ CON step: Step, DEL params: Option<Params>, ADD params: Params, CON } @@ -34,12 +31,3 @@ CON step: Step::Prepare(conn.prepare(query)), DEL params: Some(params.into()), DEL } DEL } DEL DEL impl PrepExec { DEL fn either_poll(&mut self) -> Result<Async<Out>> { DEL match self.step { DEL Step::Prepare(ref mut fut) => Ok(Ready(Out::Prepare(try_ready!(fut.poll())))), DEL Step::Execute(ref mut fut) => Ok(Ready(Out::Execute(try_ready!(fut.poll())))), DEL } ADD params: params.into(), CON } @@ -54,3 +42,3 @@ CON Out::Prepare(stmt) => { DEL let params = self.params.take().unwrap(); ADD let params = mem::replace(&mut self.params, Params::Empty); CON self.step = Step::Execute(stmt.execute(params));
<<<<<<< SEARCH use conn::futures::Prepare; use conn::stmt::futures::Execute; use conn::stmt::Stmt; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use value::Params; enum Step { Prepare(Prepare), Execute(Execute), } enum Out { Prepare(Stmt), Execute(BinQueryResult), } pub struct PrepExec { step: Step, params: Option<Params>, } ======= use conn::futures::Prepare; use conn::stmt::futures::Execute; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use std::mem; use value::Params; steps! { PrepExec { Prepare(Prepare), Execute(Execute), } } pub struct PrepExec { step: Step, params: Params, } >>>>>>> REPLACE
zsiciarz/variablestars.net
1f98e497136ce3d9da7e63a6dc7c3f67fedf50b5
observations/views.py
python
mit
Save the observation if the form was valid.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from .forms import ObservationForm, BatchUploadForm class AddObservationView(FormView): """ Add a single observation. """ form_class = ObservationForm template_name = "observations/add_observation.html" success_url = reverse_lazy('observations:add_observation') def form_valid(self, form): observation = form.save(commit=False) observation.observer = self.request.observer observation.save() return super(AddObservationView, self).form_valid(form) class UploadObservationsView(LoginRequiredMixin, FormView): """ Upload a file of observations. """ form_class = BatchUploadForm template_name = "observations/upload_observations.html" success_url = reverse_lazy('observations:upload_observations') def form_valid(self, form): form.process_file() messages.success(self.request, _("File uploaded successfully!")) return super(UploadObservationsView, self).form_valid(form)
6
0
1
add_only
--- a/observations/views.py +++ b/observations/views.py @@ -21,2 +21,8 @@ + def form_valid(self, form): + observation = form.save(commit=False) + observation.observer = self.request.observer + observation.save() + return super(AddObservationView, self).form_valid(form) +
--- a/observations/views.py +++ b/observations/views.py @@ ... @@ + def form_valid(self, form): + observation = form.save(commit=False) + observation.observer = self.request.observer + observation.save() + return super(AddObservationView, self).form_valid(form) +
--- a/observations/views.py +++ b/observations/views.py @@ -21,2 +21,8 @@ CON ADD def form_valid(self, form): ADD observation = form.save(commit=False) ADD observation.observer = self.request.observer ADD observation.save() ADD return super(AddObservationView, self).form_valid(form) ADD CON
<<<<<<< SEARCH success_url = reverse_lazy('observations:add_observation') class UploadObservationsView(LoginRequiredMixin, FormView): ======= success_url = reverse_lazy('observations:add_observation') def form_valid(self, form): observation = form.save(commit=False) observation.observer = self.request.observer observation.save() return super(AddObservationView, self).form_valid(form) class UploadObservationsView(LoginRequiredMixin, FormView): >>>>>>> REPLACE
Mause/autobit
6fd7f3cb01f621d2ea79e15188f8000c7b6fa361
tools/add_feed.py
python
mit
Remove code specific to my system
import os from urllib.parse import urlencode, quote from autobit import Client def add_rarbg_feed(client, name, directory, filter_kwargs): url = 'http://localhost:5555/{}?{}'.format( quote(name), urlencode(filter_kwargs) ) return client.add_feed(name, url, directory) def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) if input('rarbg[yn]> ') == 'n': client.add_feed( name, input('url> '), directory ) else: add_rarbg_feed( client, name, directory, eval(input('filter dict> ')) ) if __name__ == '__main__': main()
import os from autobit import Client def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) client.get_torrents() name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) client.add_feed( name, input('url> '), directory ) if __name__ == '__main__': main()
6
23
3
mixed
--- a/tools/add_feed.py +++ b/tools/add_feed.py @@ -1,3 +1,2 @@ import os -from urllib.parse import urlencode, quote @@ -6,13 +5,5 @@ -def add_rarbg_feed(client, name, directory, filter_kwargs): - url = 'http://localhost:5555/{}?{}'.format( - quote(name), - urlencode(filter_kwargs) - ) - - return client.add_feed(name, url, directory) - - def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) + client.get_torrents() @@ -23,15 +14,7 @@ - if input('rarbg[yn]> ') == 'n': - client.add_feed( - name, - input('url> '), - directory - ) - else: - add_rarbg_feed( - client, - name, - directory, - eval(input('filter dict> ')) - ) + client.add_feed( + name, + input('url> '), + directory + )
--- a/tools/add_feed.py +++ b/tools/add_feed.py @@ ... @@ import os -from urllib.parse import urlencode, quote @@ ... @@ -def add_rarbg_feed(client, name, directory, filter_kwargs): - url = 'http://localhost:5555/{}?{}'.format( - quote(name), - urlencode(filter_kwargs) - ) - - return client.add_feed(name, url, directory) - - def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) + client.get_torrents() @@ ... @@ - if input('rarbg[yn]> ') == 'n': - client.add_feed( - name, - input('url> '), - directory - ) - else: - add_rarbg_feed( - client, - name, - directory, - eval(input('filter dict> ')) - ) + client.add_feed( + name, + input('url> '), + directory + )
--- a/tools/add_feed.py +++ b/tools/add_feed.py @@ -1,3 +1,2 @@ CON import os DEL from urllib.parse import urlencode, quote CON @@ -6,13 +5,5 @@ CON DEL def add_rarbg_feed(client, name, directory, filter_kwargs): DEL url = 'http://localhost:5555/{}?{}'.format( DEL quote(name), DEL urlencode(filter_kwargs) DEL ) DEL DEL return client.add_feed(name, url, directory) DEL DEL CON def main(): CON client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) ADD client.get_torrents() CON @@ -23,15 +14,7 @@ CON DEL if input('rarbg[yn]> ') == 'n': DEL client.add_feed( DEL name, DEL input('url> '), DEL directory DEL ) DEL else: DEL add_rarbg_feed( DEL client, DEL name, DEL directory, DEL eval(input('filter dict> ')) DEL ) ADD client.add_feed( ADD name, ADD input('url> '), ADD directory ADD ) CON
<<<<<<< SEARCH import os from urllib.parse import urlencode, quote from autobit import Client def add_rarbg_feed(client, name, directory, filter_kwargs): url = 'http://localhost:5555/{}?{}'.format( quote(name), urlencode(filter_kwargs) ) return client.add_feed(name, url, directory) def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) name = input('name> ') ======= import os from autobit import Client def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) client.get_torrents() name = input('name> ') >>>>>>> REPLACE
mateusmedeiros/rust_of_life
ea586633392a5755147578b0f8e0221865c7bb99
src/main.rs
rust
mit
Add the piston tutorials initial code as a base
fn main() { println!("Hello, world!"); }
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } }
76
1
1
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,78 @@ +extern crate piston; +extern crate graphics; +extern crate glutin_window; +extern crate opengl_graphics; + +use piston::window::WindowSettings; +use piston::event_loop::*; +use piston::input::*; +use glutin_window::GlutinWindow as Window; +use opengl_graphics::{ GlGraphics, OpenGL }; + +pub struct App { + gl: GlGraphics, // OpenGL drawing backend. + rotation: f64 // Rotation for the square. +} + +impl App { + fn render(&mut self, args: &RenderArgs) { + use graphics::*; + + const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + + let square = rectangle::square(0.0, 0.0, 50.0); + let rotation = self.rotation; + let (x, y) = ((args.width / 2) as f64, + (args.height / 2) as f64); + + self.gl.draw(args.viewport(), |c, gl| { + // Clear the screen. + clear(GREEN, gl); + + let transform = c.transform.trans(x, y) + .rot_rad(rotation) + .trans(-25.0, -25.0); + + // Draw a box rotating around the middle of the screen. + rectangle(RED, square, transform, gl); + }); + } + + fn update(&mut self, args: &UpdateArgs) { + // Rotate 2 radians per second. + self.rotation += 2.0 * args.dt; + } +} + fn main() { - println!("Hello, world!"); + // Change this to OpenGL::V2_1 if not working. + let opengl = OpenGL::V3_2; + + // Create an Glutin window. + let mut window: Window = WindowSettings::new( + "spinning-square", + [200, 200] + ) + .opengl(opengl) + .exit_on_esc(true) + .build() + .unwrap(); + + // Create a new game and run it. + let mut app = App { + gl: GlGraphics::new(opengl), + rotation: 0.0 + }; + + let mut events = Events::new(EventSettings::new()); + while let Some(e) = events.next(&mut window) { + if let Some(r) = e.render_args() { + app.render(&r); + } + + if let Some(u) = e.update_args() { + app.update(&u); + } + } }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ +extern crate piston; +extern crate graphics; +extern crate glutin_window; +extern crate opengl_graphics; + +use piston::window::WindowSettings; +use piston::event_loop::*; +use piston::input::*; +use glutin_window::GlutinWindow as Window; +use opengl_graphics::{ GlGraphics, OpenGL }; + +pub struct App { + gl: GlGraphics, // OpenGL drawing backend. + rotation: f64 // Rotation for the square. +} + +impl App { + fn render(&mut self, args: &RenderArgs) { + use graphics::*; + + const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + + let square = rectangle::square(0.0, 0.0, 50.0); + let rotation = self.rotation; + let (x, y) = ((args.width / 2) as f64, + (args.height / 2) as f64); + + self.gl.draw(args.viewport(), |c, gl| { + // Clear the screen. + clear(GREEN, gl); + + let transform = c.transform.trans(x, y) + .rot_rad(rotation) + .trans(-25.0, -25.0); + + // Draw a box rotating around the middle of the screen. + rectangle(RED, square, transform, gl); + }); + } + + fn update(&mut self, args: &UpdateArgs) { + // Rotate 2 radians per second. + self.rotation += 2.0 * args.dt; + } +} + fn main() { - println!("Hello, world!"); + // Change this to OpenGL::V2_1 if not working. + let opengl = OpenGL::V3_2; + + // Create an Glutin window. + let mut window: Window = WindowSettings::new( + "spinning-square", + [200, 200] + ) + .opengl(opengl) + .exit_on_esc(true) + .build() + .unwrap(); + + // Create a new game and run it. + let mut app = App { + gl: GlGraphics::new(opengl), + rotation: 0.0 + }; + + let mut events = Events::new(EventSettings::new()); + while let Some(e) = events.next(&mut window) { + if let Some(r) = e.render_args() { + app.render(&r); + } + + if let Some(u) = e.update_args() { + app.update(&u); + } + } }
--- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,78 @@ ADD extern crate piston; ADD extern crate graphics; ADD extern crate glutin_window; ADD extern crate opengl_graphics; ADD ADD use piston::window::WindowSettings; ADD use piston::event_loop::*; ADD use piston::input::*; ADD use glutin_window::GlutinWindow as Window; ADD use opengl_graphics::{ GlGraphics, OpenGL }; ADD ADD pub struct App { ADD gl: GlGraphics, // OpenGL drawing backend. ADD rotation: f64 // Rotation for the square. ADD } ADD ADD impl App { ADD fn render(&mut self, args: &RenderArgs) { ADD use graphics::*; ADD ADD const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; ADD const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; ADD ADD let square = rectangle::square(0.0, 0.0, 50.0); ADD let rotation = self.rotation; ADD let (x, y) = ((args.width / 2) as f64, ADD (args.height / 2) as f64); ADD ADD self.gl.draw(args.viewport(), |c, gl| { ADD // Clear the screen. ADD clear(GREEN, gl); ADD ADD let transform = c.transform.trans(x, y) ADD .rot_rad(rotation) ADD .trans(-25.0, -25.0); ADD ADD // Draw a box rotating around the middle of the screen. ADD rectangle(RED, square, transform, gl); ADD }); ADD } ADD ADD fn update(&mut self, args: &UpdateArgs) { ADD // Rotate 2 radians per second. ADD self.rotation += 2.0 * args.dt; ADD } ADD } ADD CON fn main() { DEL println!("Hello, world!"); ADD // Change this to OpenGL::V2_1 if not working. ADD let opengl = OpenGL::V3_2; ADD ADD // Create an Glutin window. ADD let mut window: Window = WindowSettings::new( ADD "spinning-square", ADD [200, 200] ADD ) ADD .opengl(opengl) ADD .exit_on_esc(true) ADD .build() ADD .unwrap(); ADD ADD // Create a new game and run it. ADD let mut app = App { ADD gl: GlGraphics::new(opengl), ADD rotation: 0.0 ADD }; ADD ADD let mut events = Events::new(EventSettings::new()); ADD while let Some(e) = events.next(&mut window) { ADD if let Some(r) = e.render_args() { ADD app.render(&r); ADD } ADD ADD if let Some(u) = e.update_args() { ADD app.update(&u); ADD } ADD } CON }
<<<<<<< SEARCH fn main() { println!("Hello, world!"); } ======= extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } } >>>>>>> REPLACE
cloudtools/troposphere
b5006a2820051e00c9fe4f5efe43e90129c12b4d
troposphere/cloudtrail.py
python
bsd-2-clause
Update Cloudtrail per 2021-09-10 changes
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), } class Trail(AWSObject): resource_type = "AWS::CloudTrail::Trail" props = { "CloudWatchLogsLogGroupArn": (str, False), "CloudWatchLogsRoleArn": (str, False), "EnableLogFileValidation": (boolean, False), "EventSelectors": ([EventSelector], False), "IncludeGlobalServiceEvents": (boolean, False), "IsLogging": (boolean, True), "IsMultiRegionTrail": (boolean, False), "KMSKeyId": (str, False), "S3BucketName": (str, True), "S3KeyPrefix": (str, False), "SnsTopicName": (str, False), "Tags": (Tags, False), "TrailName": (str, False), }
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "ExcludeManagementEventSources": ([str], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), } class InsightSelector(AWSProperty): props = { "InsightType": (str, False), } class Trail(AWSObject): resource_type = "AWS::CloudTrail::Trail" props = { "CloudWatchLogsLogGroupArn": (str, False), "CloudWatchLogsRoleArn": (str, False), "EnableLogFileValidation": (boolean, False), "EventSelectors": ([EventSelector], False), "IncludeGlobalServiceEvents": (boolean, False), "InsightSelectors": ([InsightSelector], False), "IsLogging": (boolean, True), "IsMultiRegionTrail": (boolean, False), "IsOrganizationTrail": (boolean, False), "KMSKeyId": (str, False), "S3BucketName": (str, True), "S3KeyPrefix": (str, False), "SnsTopicName": (str, False), "Tags": (Tags, False), "TrailName": (str, False), }
9
0
2
add_only
--- a/troposphere/cloudtrail.py +++ b/troposphere/cloudtrail.py @@ -14,4 +14,11 @@ "DataResources": ([DataResource], False), + "ExcludeManagementEventSources": ([str], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), + } + + +class InsightSelector(AWSProperty): + props = { + "InsightType": (str, False), } @@ -28,4 +35,6 @@ "IncludeGlobalServiceEvents": (boolean, False), + "InsightSelectors": ([InsightSelector], False), "IsLogging": (boolean, True), "IsMultiRegionTrail": (boolean, False), + "IsOrganizationTrail": (boolean, False), "KMSKeyId": (str, False),
--- a/troposphere/cloudtrail.py +++ b/troposphere/cloudtrail.py @@ ... @@ "DataResources": ([DataResource], False), + "ExcludeManagementEventSources": ([str], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), + } + + +class InsightSelector(AWSProperty): + props = { + "InsightType": (str, False), } @@ ... @@ "IncludeGlobalServiceEvents": (boolean, False), + "InsightSelectors": ([InsightSelector], False), "IsLogging": (boolean, True), "IsMultiRegionTrail": (boolean, False), + "IsOrganizationTrail": (boolean, False), "KMSKeyId": (str, False),
--- a/troposphere/cloudtrail.py +++ b/troposphere/cloudtrail.py @@ -14,4 +14,11 @@ CON "DataResources": ([DataResource], False), ADD "ExcludeManagementEventSources": ([str], False), CON "IncludeManagementEvents": (boolean, False), CON "ReadWriteType": (str, False), ADD } ADD ADD ADD class InsightSelector(AWSProperty): ADD props = { ADD "InsightType": (str, False), CON } @@ -28,4 +35,6 @@ CON "IncludeGlobalServiceEvents": (boolean, False), ADD "InsightSelectors": ([InsightSelector], False), CON "IsLogging": (boolean, True), CON "IsMultiRegionTrail": (boolean, False), ADD "IsOrganizationTrail": (boolean, False), CON "KMSKeyId": (str, False),
<<<<<<< SEARCH props = { "DataResources": ([DataResource], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), } ======= props = { "DataResources": ([DataResource], False), "ExcludeManagementEventSources": ([str], False), "IncludeManagementEvents": (boolean, False), "ReadWriteType": (str, False), } class InsightSelector(AWSProperty): props = { "InsightType": (str, False), } >>>>>>> REPLACE
datamade/semabot
60e92f0a085bf7f4cb9f326085e3d4aba11f3594
bot.py
python
mit
Add actual things that do real stuff
from flask import Flask from flow import Flow from config import ORG_ID, CHANNEL_ID flow = Flow('botbotbot') app = Flask(__name__) @app.route('/') def index(): flow.send_message(ORG_ID, CHANNEL_ID, 'botbotbot') return 'foo' if __name__ == "__main__": app.run()
import json import requests from flask import Flask, request from flow import Flow from config import ORG_ID, CHANNEL_ID flow = Flow('botbotbot') app = Flask(__name__) @app.route('/') def index(): flow.send_message(ORG_ID, CHANNEL_ID, 'botbotbot') return 'foo' @app.route('/deployments/', methods=['POST']) def failures(): data = json.loads(request.data.decode('utf-8')) message_type = data['Type'] if message_type == 'SubscriptionConfirmation': confirmation = requests.get(data['SubscribeURL']) elif message_type == 'Notification': message_data = json.loads(data['Message']) message = '{applicationName} ({deploymentGroupName}) deployment has the status {status}'.format(**message_data) flow.send_message(ORG_ID, CHANNEL_ID, message) return 'foop' if __name__ == "__main__": import sys port = int(sys.argv[1]) app.run(port=port, debug=True)
28
2
2
mixed
--- a/bot.py +++ b/bot.py @@ -1,2 +1,6 @@ -from flask import Flask +import json + +import requests + +from flask import Flask, request from flow import Flow @@ -15,3 +19,25 @@ [email protected]('/deployments/', methods=['POST']) +def failures(): + + data = json.loads(request.data.decode('utf-8')) + message_type = data['Type'] + + if message_type == 'SubscriptionConfirmation': + confirmation = requests.get(data['SubscribeURL']) + + elif message_type == 'Notification': + + message_data = json.loads(data['Message']) + + message = '{applicationName} ({deploymentGroupName}) deployment has the status {status}'.format(**message_data) + + flow.send_message(ORG_ID, CHANNEL_ID, message) + + return 'foop' + + if __name__ == "__main__": - app.run() + import sys + port = int(sys.argv[1]) + app.run(port=port, debug=True)
--- a/bot.py +++ b/bot.py @@ ... @@ -from flask import Flask +import json + +import requests + +from flask import Flask, request from flow import Flow @@ ... @@ [email protected]('/deployments/', methods=['POST']) +def failures(): + + data = json.loads(request.data.decode('utf-8')) + message_type = data['Type'] + + if message_type == 'SubscriptionConfirmation': + confirmation = requests.get(data['SubscribeURL']) + + elif message_type == 'Notification': + + message_data = json.loads(data['Message']) + + message = '{applicationName} ({deploymentGroupName}) deployment has the status {status}'.format(**message_data) + + flow.send_message(ORG_ID, CHANNEL_ID, message) + + return 'foop' + + if __name__ == "__main__": - app.run() + import sys + port = int(sys.argv[1]) + app.run(port=port, debug=True)
--- a/bot.py +++ b/bot.py @@ -1,2 +1,6 @@ DEL from flask import Flask ADD import json ADD ADD import requests ADD ADD from flask import Flask, request CON from flow import Flow @@ -15,3 +19,25 @@ CON ADD @app.route('/deployments/', methods=['POST']) ADD def failures(): ADD ADD data = json.loads(request.data.decode('utf-8')) ADD message_type = data['Type'] ADD ADD if message_type == 'SubscriptionConfirmation': ADD confirmation = requests.get(data['SubscribeURL']) ADD ADD elif message_type == 'Notification': ADD ADD message_data = json.loads(data['Message']) ADD ADD message = '{applicationName} ({deploymentGroupName}) deployment has the status {status}'.format(**message_data) ADD ADD flow.send_message(ORG_ID, CHANNEL_ID, message) ADD ADD return 'foop' ADD ADD CON if __name__ == "__main__": DEL app.run() ADD import sys ADD port = int(sys.argv[1]) ADD app.run(port=port, debug=True)
<<<<<<< SEARCH from flask import Flask from flow import Flow ======= import json import requests from flask import Flask, request from flow import Flow >>>>>>> REPLACE
adamjc/rust_calc
c2c8e4325dec929af86222e30715f67fdcbf0478
src/main.rs
rust
mit
Change how we do operators
use std::env; fn multiply (a: f32, b: f32) -> f32 { return a * b; } fn add (a: f32, b: f32) -> f32 { return a + b; } fn divide (a: f32, b: f32) -> f32 { return a / b; } fn subtract (a: f32, b: f32) -> f32 { return a - b; } fn exponent (a: f32, b: f32) -> f32 { return a.powf(b); } fn main () { let args: Vec<_> = env::args().collect(); let tokens: Vec<&str> = args[1].split(" ").collect(); let mut output: Vec<i32> = vec![]; let mut operator: Vec<_> = vec![]; for i in 1..tokens.len() { let r = tokens[i].parse::<i32>(); match r { Ok(_) => output.push(r.unwrap()), Err(_) => { if operator.len() > 0 { } operator.push(&tokens[i]) } } } }
use std::env; use std::collections::HashMap; struct Operator { precedence: i32, func: Box<Fn(f32, f32) -> f32> } fn main () { let args: Vec<_> = env::args().collect(); let tokens: Vec<&str> = args[1].split(" ").collect(); let mut output: Vec<i32> = vec![]; let mut operator: Vec<_> = vec![]; let multiply = Operator { precedence: 3, func: Box::new(move |a: f32, b:f32| a * b) }; let divide = Operator { precedence: 3, func: Box::new(move |a: f32, b:f32| a / b) }; let add = Operator { precedence: 4, func: Box::new(move |a: f32, b:f32| a + b) }; let subtract = Operator { precedence: 4, func: Box::new(move |a: f32, b:f32| a - b) }; let mut operators: HashMap<char, Operator> = HashMap::new(); operators.insert('*', multiply); operators.insert('/', divide); operators.insert('+', add); operators.insert('-', subtract); for i in 1..tokens.len() { let r = tokens[i].parse::<i32>(); match r { Ok(_) => output.push(r.unwrap()), Err(_) => { if operator.len() > 0 { } operator.push(&tokens[i]) } } } }
31
18
2
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -1,21 +1,7 @@ use std::env; +use std::collections::HashMap; -fn multiply (a: f32, b: f32) -> f32 { - return a * b; -} - -fn add (a: f32, b: f32) -> f32 { - return a + b; -} - -fn divide (a: f32, b: f32) -> f32 { - return a / b; -} - -fn subtract (a: f32, b: f32) -> f32 { - return a - b; -} - -fn exponent (a: f32, b: f32) -> f32 { - return a.powf(b); +struct Operator { + precedence: i32, + func: Box<Fn(f32, f32) -> f32> } @@ -27,2 +13,29 @@ let mut operator: Vec<_> = vec![]; + + let multiply = Operator { + precedence: 3, + func: Box::new(move |a: f32, b:f32| a * b) + }; + + let divide = Operator { + precedence: 3, + func: Box::new(move |a: f32, b:f32| a / b) + }; + + let add = Operator { + precedence: 4, + func: Box::new(move |a: f32, b:f32| a + b) + }; + + let subtract = Operator { + precedence: 4, + func: Box::new(move |a: f32, b:f32| a - b) + }; + + let mut operators: HashMap<char, Operator> = HashMap::new(); + + operators.insert('*', multiply); + operators.insert('/', divide); + operators.insert('+', add); + operators.insert('-', subtract);
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ use std::env; +use std::collections::HashMap; -fn multiply (a: f32, b: f32) -> f32 { - return a * b; -} - -fn add (a: f32, b: f32) -> f32 { - return a + b; -} - -fn divide (a: f32, b: f32) -> f32 { - return a / b; -} - -fn subtract (a: f32, b: f32) -> f32 { - return a - b; -} - -fn exponent (a: f32, b: f32) -> f32 { - return a.powf(b); +struct Operator { + precedence: i32, + func: Box<Fn(f32, f32) -> f32> } @@ ... @@ let mut operator: Vec<_> = vec![]; + + let multiply = Operator { + precedence: 3, + func: Box::new(move |a: f32, b:f32| a * b) + }; + + let divide = Operator { + precedence: 3, + func: Box::new(move |a: f32, b:f32| a / b) + }; + + let add = Operator { + precedence: 4, + func: Box::new(move |a: f32, b:f32| a + b) + }; + + let subtract = Operator { + precedence: 4, + func: Box::new(move |a: f32, b:f32| a - b) + }; + + let mut operators: HashMap<char, Operator> = HashMap::new(); + + operators.insert('*', multiply); + operators.insert('/', divide); + operators.insert('+', add); + operators.insert('-', subtract);
--- a/src/main.rs +++ b/src/main.rs @@ -1,21 +1,7 @@ CON use std::env; ADD use std::collections::HashMap; CON DEL fn multiply (a: f32, b: f32) -> f32 { DEL return a * b; DEL } DEL DEL fn add (a: f32, b: f32) -> f32 { DEL return a + b; DEL } DEL DEL fn divide (a: f32, b: f32) -> f32 { DEL return a / b; DEL } DEL DEL fn subtract (a: f32, b: f32) -> f32 { DEL return a - b; DEL } DEL DEL fn exponent (a: f32, b: f32) -> f32 { DEL return a.powf(b); ADD struct Operator { ADD precedence: i32, ADD func: Box<Fn(f32, f32) -> f32> CON } @@ -27,2 +13,29 @@ CON let mut operator: Vec<_> = vec![]; ADD ADD let multiply = Operator { ADD precedence: 3, ADD func: Box::new(move |a: f32, b:f32| a * b) ADD }; ADD ADD let divide = Operator { ADD precedence: 3, ADD func: Box::new(move |a: f32, b:f32| a / b) ADD }; ADD ADD let add = Operator { ADD precedence: 4, ADD func: Box::new(move |a: f32, b:f32| a + b) ADD }; ADD ADD let subtract = Operator { ADD precedence: 4, ADD func: Box::new(move |a: f32, b:f32| a - b) ADD }; ADD ADD let mut operators: HashMap<char, Operator> = HashMap::new(); ADD ADD operators.insert('*', multiply); ADD operators.insert('/', divide); ADD operators.insert('+', add); ADD operators.insert('-', subtract); CON
<<<<<<< SEARCH use std::env; fn multiply (a: f32, b: f32) -> f32 { return a * b; } fn add (a: f32, b: f32) -> f32 { return a + b; } fn divide (a: f32, b: f32) -> f32 { return a / b; } fn subtract (a: f32, b: f32) -> f32 { return a - b; } fn exponent (a: f32, b: f32) -> f32 { return a.powf(b); } ======= use std::env; use std::collections::HashMap; struct Operator { precedence: i32, func: Box<Fn(f32, f32) -> f32> } >>>>>>> REPLACE
philippsied/smartcard-course
0ba953e8f3f78e89d573f322334dfaf345c8bdec
OffCardAPP/src/main/java/clientAPI/ClientFactory.java
java
mit
Rename method for getting PersonalData instance
package clientAPI; import clientAPI.impl.BonusCreditStoreConnector; import clientAPI.impl.CryptoStoreConnector; import clientAPI.impl.PersonalDataConnector; import clientAPI.impl.TicketManagerConnector; import clientAPI.impl.WalletConnector; import javax.smartcardio.Card; public class ClientFactory { /** * * @return */ public static TicketManager getTicketManager(Card card) { return new TicketManagerConnector(card); } /** * * @return */ public static Wallet getWallet(Card card) { return new WalletConnector(card); } /** * * @return */ public static BonusCreditStore getBonusCreditStore(Card card) { return new BonusCreditStoreConnector(card); } /** * * @return */ public static PersonalData getCustomerData(Card card) { return new PersonalDataConnector(card); } /** * * @return */ public static CryptoStore getCryptoStore(Card card) { return new CryptoStoreConnector(card); } }
package clientAPI; import clientAPI.impl.BonusCreditStoreConnector; import clientAPI.impl.CryptoStoreConnector; import clientAPI.impl.PersonalDataConnector; import clientAPI.impl.TicketManagerConnector; import clientAPI.impl.WalletConnector; import javax.smartcardio.Card; public class ClientFactory { /** * * @return */ public static TicketManager getTicketManager(Card card) { return new TicketManagerConnector(card); } /** * * @return */ public static Wallet getWallet(Card card) { return new WalletConnector(card); } /** * * @return */ public static BonusCreditStore getBonusCreditStore(Card card) { return new BonusCreditStoreConnector(card); } /** * * @return */ public static PersonalData getPersonalData(Card card) { return new PersonalDataConnector(card); } /** * * @return */ public static CryptoStore getCryptoStore(Card card) { return new CryptoStoreConnector(card); } }
1
1
1
mixed
--- a/OffCardAPP/src/main/java/clientAPI/ClientFactory.java +++ b/OffCardAPP/src/main/java/clientAPI/ClientFactory.java @@ -42,3 +42,3 @@ */ - public static PersonalData getCustomerData(Card card) { + public static PersonalData getPersonalData(Card card) { return new PersonalDataConnector(card);
--- a/OffCardAPP/src/main/java/clientAPI/ClientFactory.java +++ b/OffCardAPP/src/main/java/clientAPI/ClientFactory.java @@ ... @@ */ - public static PersonalData getCustomerData(Card card) { + public static PersonalData getPersonalData(Card card) { return new PersonalDataConnector(card);
--- a/OffCardAPP/src/main/java/clientAPI/ClientFactory.java +++ b/OffCardAPP/src/main/java/clientAPI/ClientFactory.java @@ -42,3 +42,3 @@ CON */ DEL public static PersonalData getCustomerData(Card card) { ADD public static PersonalData getPersonalData(Card card) { CON return new PersonalDataConnector(card);
<<<<<<< SEARCH * @return */ public static PersonalData getCustomerData(Card card) { return new PersonalDataConnector(card); } ======= * @return */ public static PersonalData getPersonalData(Card card) { return new PersonalDataConnector(card); } >>>>>>> REPLACE
cazacugmihai/codebrag
ebdd89802aed62c234093bb196da091d2f7d8b4d
codebrag-ui/app/scripts/invitations/invitationService.js
javascript
agpl-3.0
Change email validator regexp. Previous one was too dummy :)
angular.module('codebrag.invitations') .service('invitationService', function($http, $q) { this.loadRegisteredUsers = function() { return $http.get('rest/users/all').then(function(response) { return response.data.registeredUsers; }); }; this.loadInvitationLink = function() { var dfd = $q.defer(); function success(response) { dfd.resolve(response.data.invitationLink); return dfd.promise; } function error() { dfd.resolve('Sorry. We could not generate invitation link.'); return dfd.promise; } return $http.get('rest/invitation').then(success, error); }; this.sendInvitation = function(invitations, invitationLink) { var invitationRequestPayload = { emails: invitations.map(function(i) { return i.email; }), invitationLink: invitationLink }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); } this.validateEmails = function(emailsString) { var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); }); return !foundInvalid; } });
angular.module('codebrag.invitations') .service('invitationService', function($http, $q) { this.loadRegisteredUsers = function() { return $http.get('rest/users/all').then(function(response) { return response.data.registeredUsers; }); }; this.loadInvitationLink = function() { var dfd = $q.defer(); function success(response) { dfd.resolve(response.data.invitationLink); return dfd.promise; } function error() { dfd.resolve('Sorry. We could not generate invitation link.'); return dfd.promise; } return $http.get('rest/invitation').then(success, error); }; this.sendInvitation = function(invitations, invitationLink) { var invitationRequestPayload = { emails: invitations.map(function(i) { return i.email; }), invitationLink: invitationLink }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); }; this.validateEmails = function(emailsString) { var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(regexp.test(email)); }); return !foundInvalid; } });
3
2
1
mixed
--- a/codebrag-ui/app/scripts/invitations/invitationService.js +++ b/codebrag-ui/app/scripts/invitations/invitationService.js @@ -32,7 +32,8 @@ return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); - } + }; this.validateEmails = function(emailsString) { + var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { - return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); + return !(regexp.test(email)); });
--- a/codebrag-ui/app/scripts/invitations/invitationService.js +++ b/codebrag-ui/app/scripts/invitations/invitationService.js @@ ... @@ return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); - } + }; this.validateEmails = function(emailsString) { + var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { - return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); + return !(regexp.test(email)); });
--- a/codebrag-ui/app/scripts/invitations/invitationService.js +++ b/codebrag-ui/app/scripts/invitations/invitationService.js @@ -32,7 +32,8 @@ CON return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); DEL } ADD }; CON CON this.validateEmails = function(emailsString) { ADD var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; CON var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { DEL return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); ADD return !(regexp.test(email)); CON });
<<<<<<< SEARCH }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); } this.validateEmails = function(emailsString) { var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); }); return !foundInvalid; ======= }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); }; this.validateEmails = function(emailsString) { var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(regexp.test(email)); }); return !foundInvalid; >>>>>>> REPLACE
ufocoder/redux-universal-boilerplate
bcada25f33f4c8595b54c2af03ea84142535b62b
src/common/containers/Layout/Header.js
javascript
mit
Add link to 404 example page
import React, {Component, PropTypes} from 'react'; import {IndexLink, Link} from 'react-router'; import {connect} from 'react-redux'; @connect( state => ({ loggedIn: state.auth.loggedIn }) ) export default class Header extends Component { static propTypes = { loggedIn: PropTypes.bool } render() { let links = [ { to: '/trends', title: 'Github trends' }, { to: '/about', title: 'About' } ]; if (this.props.loggedIn) { links.push({ to: '/profile', title: 'Profile' }); links.push({ to: '/logout', title: 'Logout' }); } else { links.push({ to: '/login', title: 'Login' }); } return ( <div className="ui text container"> <h1 className="ui dividing header">Redux universal boilerplate</h1> <div className="ui secondary pointing menu"> <IndexLink to="/" className="item" activeClassName="active">Homepage</IndexLink> { links.map(function(link, i) { return <Link to={link.to} key={i} className="item" activeClassName="active">{link.title}</Link>; }) } </div> </div> ); } }
import React, {Component, PropTypes} from 'react'; import {IndexLink, Link} from 'react-router'; import {connect} from 'react-redux'; @connect( state => ({ loggedIn: state.auth.loggedIn }) ) export default class Header extends Component { static propTypes = { loggedIn: PropTypes.bool } render() { let links = [ { to: '/trends', title: 'Github trends' }, { to: '/about', title: 'About' }, { to: '/404', title: 'Non-exists page' } ]; if (this.props.loggedIn) { links.push({ to: '/profile', title: 'Profile' }); links.push({ to: '/logout', title: 'Logout' }); } else { links.push({ to: '/login', title: 'Login' }); } return ( <div className="ui text container"> <h1 className="ui dividing header">Redux universal boilerplate</h1> <div className="ui secondary pointing menu"> <IndexLink to="/" className="item" activeClassName="active">Homepage</IndexLink> { links.map(function(link, i) { return <Link to={link.to} key={i} className="item" activeClassName="active">{link.title}</Link>; }) } </div> </div> ); } }
4
0
1
add_only
--- a/src/common/containers/Layout/Header.js +++ b/src/common/containers/Layout/Header.js @@ -23,2 +23,6 @@ title: 'About' + }, + { + to: '/404', + title: 'Non-exists page' }
--- a/src/common/containers/Layout/Header.js +++ b/src/common/containers/Layout/Header.js @@ ... @@ title: 'About' + }, + { + to: '/404', + title: 'Non-exists page' }
--- a/src/common/containers/Layout/Header.js +++ b/src/common/containers/Layout/Header.js @@ -23,2 +23,6 @@ CON title: 'About' ADD }, ADD { ADD to: '/404', ADD title: 'Non-exists page' CON }
<<<<<<< SEARCH to: '/about', title: 'About' } ]; ======= to: '/about', title: 'About' }, { to: '/404', title: 'Non-exists page' } ]; >>>>>>> REPLACE
liujed/polyglot-eclipse
1df3b8ae40c3bf878ea687b39734398dcda10296
src/polyglot/frontend/VisitorPass.java
java
lgpl-2.1
Call NodeVisitor.begin() before visiting ast.
package jltools.frontend; import jltools.ast.*; import jltools.util.*; /** A pass which runs a visitor. */ public class VisitorPass extends AbstractPass { Job job; NodeVisitor v; public VisitorPass(Job job) { this(job, null); } public VisitorPass(Job job, NodeVisitor v) { this.job = job; this.v = v; } public void visitor(NodeVisitor v) { this.v = v; } public NodeVisitor visitor() { return v; } public boolean run() { Node ast = job.ast(); if (ast == null) { throw new InternalCompilerError("Null AST: did the parser run?"); } ErrorQueue q = job.compiler().errorQueue(); int nErrsBefore = q.errorCount(); ast = ast.visit(v); v.finish(); int nErrsAfter = q.errorCount(); job.ast(ast); return (nErrsBefore == nErrsAfter); // because, if they're equal, no new errors occured, // so the run was successful. } public String toString() { return v.getClass().getName() + "(" + job + ")"; } }
package jltools.frontend; import jltools.ast.*; import jltools.util.*; /** A pass which runs a visitor. */ public class VisitorPass extends AbstractPass { Job job; NodeVisitor v; public VisitorPass(Job job) { this(job, null); } public VisitorPass(Job job, NodeVisitor v) { this.job = job; this.v = v; } public void visitor(NodeVisitor v) { this.v = v; } public NodeVisitor visitor() { return v; } public boolean run() { Node ast = job.ast(); if (ast == null) { throw new InternalCompilerError("Null AST: did the parser run?"); } if (v.begin()) { ErrorQueue q = job.compiler().errorQueue(); int nErrsBefore = q.errorCount(); ast = ast.visit(v); v.finish(); int nErrsAfter = q.errorCount(); job.ast(ast); return (nErrsBefore == nErrsAfter); // because, if they're equal, no new errors occured, // so the run was successful. } return false; } public String toString() { return v.getClass().getName() + "(" + job + ")"; } }
13
9
1
mixed
--- a/src/polyglot/frontend/VisitorPass.java +++ b/src/polyglot/frontend/VisitorPass.java @@ -35,15 +35,19 @@ - ErrorQueue q = job.compiler().errorQueue(); - int nErrsBefore = q.errorCount(); + if (v.begin()) { + ErrorQueue q = job.compiler().errorQueue(); + int nErrsBefore = q.errorCount(); - ast = ast.visit(v); - v.finish(); + ast = ast.visit(v); + v.finish(); - int nErrsAfter = q.errorCount(); + int nErrsAfter = q.errorCount(); - job.ast(ast); + job.ast(ast); - return (nErrsBefore == nErrsAfter); - // because, if they're equal, no new errors occured, - // so the run was successful. + return (nErrsBefore == nErrsAfter); + // because, if they're equal, no new errors occured, + // so the run was successful. + } + + return false; }
--- a/src/polyglot/frontend/VisitorPass.java +++ b/src/polyglot/frontend/VisitorPass.java @@ ... @@ - ErrorQueue q = job.compiler().errorQueue(); - int nErrsBefore = q.errorCount(); + if (v.begin()) { + ErrorQueue q = job.compiler().errorQueue(); + int nErrsBefore = q.errorCount(); - ast = ast.visit(v); - v.finish(); + ast = ast.visit(v); + v.finish(); - int nErrsAfter = q.errorCount(); + int nErrsAfter = q.errorCount(); - job.ast(ast); + job.ast(ast); - return (nErrsBefore == nErrsAfter); - // because, if they're equal, no new errors occured, - // so the run was successful. + return (nErrsBefore == nErrsAfter); + // because, if they're equal, no new errors occured, + // so the run was successful. + } + + return false; }
--- a/src/polyglot/frontend/VisitorPass.java +++ b/src/polyglot/frontend/VisitorPass.java @@ -35,15 +35,19 @@ CON DEL ErrorQueue q = job.compiler().errorQueue(); DEL int nErrsBefore = q.errorCount(); ADD if (v.begin()) { ADD ErrorQueue q = job.compiler().errorQueue(); ADD int nErrsBefore = q.errorCount(); CON DEL ast = ast.visit(v); DEL v.finish(); ADD ast = ast.visit(v); ADD v.finish(); CON DEL int nErrsAfter = q.errorCount(); ADD int nErrsAfter = q.errorCount(); CON DEL job.ast(ast); ADD job.ast(ast); CON DEL return (nErrsBefore == nErrsAfter); DEL // because, if they're equal, no new errors occured, DEL // so the run was successful. ADD return (nErrsBefore == nErrsAfter); ADD // because, if they're equal, no new errors occured, ADD // so the run was successful. ADD } ADD ADD return false; CON }
<<<<<<< SEARCH } ErrorQueue q = job.compiler().errorQueue(); int nErrsBefore = q.errorCount(); ast = ast.visit(v); v.finish(); int nErrsAfter = q.errorCount(); job.ast(ast); return (nErrsBefore == nErrsAfter); // because, if they're equal, no new errors occured, // so the run was successful. } ======= } if (v.begin()) { ErrorQueue q = job.compiler().errorQueue(); int nErrsBefore = q.errorCount(); ast = ast.visit(v); v.finish(); int nErrsAfter = q.errorCount(); job.ast(ast); return (nErrsBefore == nErrsAfter); // because, if they're equal, no new errors occured, // so the run was successful. } return false; } >>>>>>> REPLACE
klingtnet/rosc
b5d64dab892eeeecbdcf667ab8c797d5d3c4fdc7
src/osc_types.rs
rust
apache-2.0
Define `OscMessage` and `OscBundle` structs
use errors; // see OSC Type Tag String: http://opensoundcontrol.org/spec-1_0 // padding: zero bytes (n*4) pub enum OscType { OscInt(i32), OscFloat(f32), OscString(String), OscBlob(Vec<u8>), OscTime(u32, u32), // nonstandard argument types // ignore them if not implemented OscLong(i64), OscDouble(f64), OscChar(u8), OscColor(u32), // byte-order: RGBA OscMidi(OscMidiType), OscTrue, OscFalse, OscNil, OscInf, OscArray(Vec<OscType>), } pub struct OscMidiType { port: u8, status: u8, data1: u8, // maybe use an enum for data? data2: u8, } /// An *osc packet* can contain an *osc message* or a bundle of nested messages /// which is called *osc bundle*. pub enum OscPacket { Message(OscMessage), Bundle(OscBundle), } pub struct OscMessage; pub struct OscBundle; pub type OscResult<T> = Result<T, errors::OscError>;
use errors; // see OSC Type Tag String: http://opensoundcontrol.org/spec-1_0 // padding: zero bytes (n*4) pub enum OscType { OscInt(i32), OscFloat(f32), OscString(String), OscBlob(Vec<u8>), OscTime(u32, u32), // nonstandard argument types // ignore them if not implemented OscLong(i64), OscDouble(f64), OscChar(u8), OscColor(u32), // byte-order: RGBA OscMidi(OscMidiType), OscTrue, OscFalse, OscNil, OscInf, OscArray(Vec<OscType>), } pub struct OscMidiType { port: u8, status: u8, data1: u8, // maybe use an enum for data? data2: u8, } /// An *osc packet* can contain an *osc message* or a bundle of nested messages /// which is called *osc bundle*. pub enum OscPacket { Message(OscMessage), Bundle(OscBundle), } pub struct OscMessage { pub addr: String, pub args: Option<Vec<OscType>>, } pub struct OscBundle { pub timetag: OscType, pub content: Vec<OscPacket>, } pub type OscResult<T> = Result<T, errors::OscError>;
9
2
1
mixed
--- a/src/osc_types.rs +++ b/src/osc_types.rs @@ -38,4 +38,11 @@ -pub struct OscMessage; -pub struct OscBundle; +pub struct OscMessage { + pub addr: String, + pub args: Option<Vec<OscType>>, +} + +pub struct OscBundle { + pub timetag: OscType, + pub content: Vec<OscPacket>, +}
--- a/src/osc_types.rs +++ b/src/osc_types.rs @@ ... @@ -pub struct OscMessage; -pub struct OscBundle; +pub struct OscMessage { + pub addr: String, + pub args: Option<Vec<OscType>>, +} + +pub struct OscBundle { + pub timetag: OscType, + pub content: Vec<OscPacket>, +}
--- a/src/osc_types.rs +++ b/src/osc_types.rs @@ -38,4 +38,11 @@ CON DEL pub struct OscMessage; DEL pub struct OscBundle; ADD pub struct OscMessage { ADD pub addr: String, ADD pub args: Option<Vec<OscType>>, ADD } ADD ADD pub struct OscBundle { ADD pub timetag: OscType, ADD pub content: Vec<OscPacket>, ADD } CON
<<<<<<< SEARCH } pub struct OscMessage; pub struct OscBundle; pub type OscResult<T> = Result<T, errors::OscError>; ======= } pub struct OscMessage { pub addr: String, pub args: Option<Vec<OscType>>, } pub struct OscBundle { pub timetag: OscType, pub content: Vec<OscPacket>, } pub type OscResult<T> = Result<T, errors::OscError>; >>>>>>> REPLACE
elifarley/kotlin-misc-lib
6216431462d726a96e1c9ab9ac9d591beb695d0d
src/com/github/elifarley/kotlin/DateTimeKit.kt
kotlin
mit
Use ZoneId; Check for java.sql.Date instance
import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneOffset import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.time.temporal.TemporalAccessor import java.util.* /** * Created by elifarley on 31/08/16. */ object DateTimeKit { @JvmOverloads fun TemporalAccessor.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.from(this).toDate(zoneOffset) @JvmOverloads fun LocalDate.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.atStartOfDay().toDate(zoneOffset) @JvmOverloads fun LocalDateTime.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = Date.from(this.toInstant(zoneOffset))!! @JvmOverloads fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!! @JvmOverloads fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset) fun Instant.toGregorianCalendar() = GregorianCalendar.from(ZonedDateTime.ofInstant(this, ZoneOffset.UTC)) val DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss").withZone(ZoneOffset.UTC)!! fun DateTimeFormatter.format(date: Date) = this.format(date.toInstant())!! }
import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneOffset import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.time.temporal.TemporalAccessor import java.util.* /** * Created by elifarley on 31/08/16. */ object DateTimeKit { @JvmOverloads fun TemporalAccessor.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.from(this).toDate(zoneOffset) @JvmOverloads fun LocalDate.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.atStartOfDay().toDate(zoneOffset) @JvmOverloads fun LocalDateTime.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = Date.from(this.toInstant(zoneOffset))!! @JvmOverloads fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!! @JvmOverloads fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when { this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId) else -> this.toInstant().toLocalDateTime(zoneId) } fun Instant.toGregorianCalendar() = GregorianCalendar.from(ZonedDateTime.ofInstant(this, ZoneOffset.UTC)) val DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss").withZone(ZoneOffset.UTC)!! fun DateTimeFormatter.format(date: Date) = this.format(date.toInstant())!! }
5
2
1
mixed
--- a/src/com/github/elifarley/kotlin/DateTimeKit.kt +++ b/src/com/github/elifarley/kotlin/DateTimeKit.kt @@ -25,6 +25,9 @@ @JvmOverloads - fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!! + fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!! @JvmOverloads - fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset) + fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when { + this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId) + else -> this.toInstant().toLocalDateTime(zoneId) + }
--- a/src/com/github/elifarley/kotlin/DateTimeKit.kt +++ b/src/com/github/elifarley/kotlin/DateTimeKit.kt @@ ... @@ @JvmOverloads - fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!! + fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!! @JvmOverloads - fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset) + fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when { + this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId) + else -> this.toInstant().toLocalDateTime(zoneId) + }
--- a/src/com/github/elifarley/kotlin/DateTimeKit.kt +++ b/src/com/github/elifarley/kotlin/DateTimeKit.kt @@ -25,6 +25,9 @@ CON @JvmOverloads DEL fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!! ADD fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!! CON CON @JvmOverloads DEL fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset) ADD fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when { ADD this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId) ADD else -> this.toInstant().toLocalDateTime(zoneId) ADD } CON
<<<<<<< SEARCH @JvmOverloads fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!! @JvmOverloads fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset) fun Instant.toGregorianCalendar() = ======= @JvmOverloads fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!! @JvmOverloads fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when { this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId) else -> this.toInstant().toLocalDateTime(zoneId) } fun Instant.toGregorianCalendar() = >>>>>>> REPLACE
emmerge/rockup
0312a04fc38bf6f174764cb606693e3cb948f4c5
commands/rock-prepare.js
javascript
mit
Prepare CLI: Wait for all hosts, Capture output Allow all hosts to finish preparation. Capture output, track on erros, accept limit to single host.
// RockUp // Commands-Prepare -- Prepare the server-side to accept deployments var Spinner = require('clui').Spinner; var Config = require('../lib/Config'); var RockUtil = require('./util'); module.exports = PrepareCommand; function PrepareCommand (program) { program .command("prepare <environment>") .alias("prep") .description("Prepare a server host to accept deployments") .action( function(env, options) { var config = Config._loadLocalConfigFile(env); var spinner = new Spinner('Preparing '+config.hosts.count+' host(s) for deployment... '); spinner.start(); config.hosts.each( function(host) { console.log(" -", host.name, "..."); host.prepare( RockUtil._endCommandCallback("Preparation") ); // TODO: callback should only be fired after ALL servers have been prepped }); spinner.stop(); console.log(""); }); return program; }
// RockUp // Commands-Prepare -- Prepare the server-side to accept deployments var Config = require('../lib/Config'); var reduceAsync = require('../lib/Async').reduce; var inspect = require('util').inspect; //var _ = require('underscore'); module.exports = PrepareCommand; function PrepareCommand (program) { program .command("prepare <environment>") .alias("prep") .description("Prepare a server host to accept deployments") .option("--host <name>", "Specify an individual host to prep") .action( function(env, cliOptions) { var config = Config._loadLocalConfigFile(env); var hosts; if ( cliOptions.host ) { var host = config.hosts.get(cliOptions.host); if (!host) { console.error("Cannot find host:".red.bold, cliOptions.host, "\n"); process.exit(1); } hosts = [host]; } else { hosts = config.hosts.list; } var numHosts = hosts.length; var operations = _.map(hosts, function(host) { return function (memo, cb) { host.prepare( function(results) { if (results[host.name].error) memo[host.name] = false; else memo[host.name] = _.every(results[host.name].history, function(obj) { return obj.status === 'SUCCESS'; }); cb(); }); }; }); function _allHostsComplete (hostMap) { console.log("\nPreparation complete for "+numHosts+" host(s):"); _.each(hostMap, function(success, hostName) { console.log(hostName.bold, "\t", success ? 'SUCCESS'.green.bold : 'FAIL'.red.bold); }); console.log(""); process.exit(0); } operations.unshift({}); operations.push(_allHostsComplete); reduceAsync.apply(this, operations); }); return program; }
44
11
2
mixed
--- a/commands/rock-prepare.js +++ b/commands/rock-prepare.js @@ -3,5 +3,7 @@ -var Spinner = require('clui').Spinner; var Config = require('../lib/Config'); -var RockUtil = require('./util'); +var reduceAsync = require('../lib/Async').reduce; + +var inspect = require('util').inspect; +//var _ = require('underscore'); @@ -14,15 +16,46 @@ .description("Prepare a server host to accept deployments") - .action( function(env, options) { + .option("--host <name>", "Specify an individual host to prep") + .action( function(env, cliOptions) { var config = Config._loadLocalConfigFile(env); - var spinner = new Spinner('Preparing '+config.hosts.count+' host(s) for deployment... '); - spinner.start(); + var hosts; + if ( cliOptions.host ) { + var host = config.hosts.get(cliOptions.host); + if (!host) { + console.error("Cannot find host:".red.bold, cliOptions.host, "\n"); + process.exit(1); + } + hosts = [host]; + } else { + hosts = config.hosts.list; + } + var numHosts = hosts.length; - config.hosts.each( function(host) { - console.log(" -", host.name, "..."); - host.prepare( RockUtil._endCommandCallback("Preparation") ); - // TODO: callback should only be fired after ALL servers have been prepped + var operations = _.map(hosts, function(host) { + return function (memo, cb) { + host.prepare( function(results) { + if (results[host.name].error) + memo[host.name] = false; + else + memo[host.name] = _.every(results[host.name].history, function(obj) { + return obj.status === 'SUCCESS'; + }); + cb(); + }); + }; }); - spinner.stop(); - console.log(""); + + function _allHostsComplete (hostMap) { + console.log("\nPreparation complete for "+numHosts+" host(s):"); + _.each(hostMap, function(success, hostName) { + console.log(hostName.bold, "\t", success ? 'SUCCESS'.green.bold : 'FAIL'.red.bold); + }); + console.log(""); + process.exit(0); + } + + operations.unshift({}); + operations.push(_allHostsComplete); + reduceAsync.apply(this, operations); + });
--- a/commands/rock-prepare.js +++ b/commands/rock-prepare.js @@ ... @@ -var Spinner = require('clui').Spinner; var Config = require('../lib/Config'); -var RockUtil = require('./util'); +var reduceAsync = require('../lib/Async').reduce; + +var inspect = require('util').inspect; +//var _ = require('underscore'); @@ ... @@ .description("Prepare a server host to accept deployments") - .action( function(env, options) { + .option("--host <name>", "Specify an individual host to prep") + .action( function(env, cliOptions) { var config = Config._loadLocalConfigFile(env); - var spinner = new Spinner('Preparing '+config.hosts.count+' host(s) for deployment... '); - spinner.start(); + var hosts; + if ( cliOptions.host ) { + var host = config.hosts.get(cliOptions.host); + if (!host) { + console.error("Cannot find host:".red.bold, cliOptions.host, "\n"); + process.exit(1); + } + hosts = [host]; + } else { + hosts = config.hosts.list; + } + var numHosts = hosts.length; - config.hosts.each( function(host) { - console.log(" -", host.name, "..."); - host.prepare( RockUtil._endCommandCallback("Preparation") ); - // TODO: callback should only be fired after ALL servers have been prepped + var operations = _.map(hosts, function(host) { + return function (memo, cb) { + host.prepare( function(results) { + if (results[host.name].error) + memo[host.name] = false; + else + memo[host.name] = _.every(results[host.name].history, function(obj) { + return obj.status === 'SUCCESS'; + }); + cb(); + }); + }; }); - spinner.stop(); - console.log(""); + + function _allHostsComplete (hostMap) { + console.log("\nPreparation complete for "+numHosts+" host(s):"); + _.each(hostMap, function(success, hostName) { + console.log(hostName.bold, "\t", success ? 'SUCCESS'.green.bold : 'FAIL'.red.bold); + }); + console.log(""); + process.exit(0); + } + + operations.unshift({}); + operations.push(_allHostsComplete); + reduceAsync.apply(this, operations); + });
--- a/commands/rock-prepare.js +++ b/commands/rock-prepare.js @@ -3,5 +3,7 @@ CON DEL var Spinner = require('clui').Spinner; CON var Config = require('../lib/Config'); DEL var RockUtil = require('./util'); ADD var reduceAsync = require('../lib/Async').reduce; ADD ADD var inspect = require('util').inspect; ADD //var _ = require('underscore'); CON @@ -14,15 +16,46 @@ CON .description("Prepare a server host to accept deployments") DEL .action( function(env, options) { ADD .option("--host <name>", "Specify an individual host to prep") ADD .action( function(env, cliOptions) { CON var config = Config._loadLocalConfigFile(env); CON DEL var spinner = new Spinner('Preparing '+config.hosts.count+' host(s) for deployment... '); DEL spinner.start(); ADD var hosts; ADD if ( cliOptions.host ) { ADD var host = config.hosts.get(cliOptions.host); ADD if (!host) { ADD console.error("Cannot find host:".red.bold, cliOptions.host, "\n"); ADD process.exit(1); ADD } ADD hosts = [host]; ADD } else { ADD hosts = config.hosts.list; ADD } ADD var numHosts = hosts.length; CON DEL config.hosts.each( function(host) { DEL console.log(" -", host.name, "..."); DEL host.prepare( RockUtil._endCommandCallback("Preparation") ); DEL // TODO: callback should only be fired after ALL servers have been prepped ADD var operations = _.map(hosts, function(host) { ADD return function (memo, cb) { ADD host.prepare( function(results) { ADD if (results[host.name].error) ADD memo[host.name] = false; ADD else ADD memo[host.name] = _.every(results[host.name].history, function(obj) { ADD return obj.status === 'SUCCESS'; ADD }); ADD cb(); ADD }); ADD }; CON }); DEL spinner.stop(); DEL console.log(""); ADD ADD function _allHostsComplete (hostMap) { ADD console.log("\nPreparation complete for "+numHosts+" host(s):"); ADD _.each(hostMap, function(success, hostName) { ADD console.log(hostName.bold, "\t", success ? 'SUCCESS'.green.bold : 'FAIL'.red.bold); ADD }); ADD console.log(""); ADD process.exit(0); ADD } ADD ADD operations.unshift({}); ADD operations.push(_allHostsComplete); ADD reduceAsync.apply(this, operations); ADD CON });
<<<<<<< SEARCH // Commands-Prepare -- Prepare the server-side to accept deployments var Spinner = require('clui').Spinner; var Config = require('../lib/Config'); var RockUtil = require('./util'); module.exports = PrepareCommand; ======= // Commands-Prepare -- Prepare the server-side to accept deployments var Config = require('../lib/Config'); var reduceAsync = require('../lib/Async').reduce; var inspect = require('util').inspect; //var _ = require('underscore'); module.exports = PrepareCommand; >>>>>>> REPLACE
statsbiblioteket/newspaper-statistics
6d882e38aa7ef5a16dd46ff9d3c275c2ddda63a6
src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java
java
apache-2.0
Update to newest snapshot, including a few changes stemming from this.
package dk.statsbiblioteket.medieplatform.newspaper.statistics; import java.util.Arrays; import java.util.List; import java.util.Properties; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent { private Logger log = LoggerFactory.getLogger(getClass()); private Properties properties; protected StatisticsRunnableComponent(Properties properties) { super(properties); this.properties = properties; } @Override public String getEventID() { return "Statistics_Generated"; } @Override public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception { log.info("Starting statistics generation for '{}'", batch.getFullID()); List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch)); eventRunner.runEvents(statisticGenerator, resultCollector); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } }
package dk.statsbiblioteket.medieplatform.newspaper.statistics; import java.util.Arrays; import java.util.List; import java.util.Properties; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent { private Logger log = LoggerFactory.getLogger(getClass()); private Properties properties; protected StatisticsRunnableComponent(Properties properties) { super(properties); this.properties = properties; } @Override public String getEventID() { return "Statistics_Generated"; } @Override public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception { log.info("Starting statistics generation for '{}'", batch.getFullID()); List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); eventRunner.run(); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } }
2
2
1
mixed
--- a/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java +++ b/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java @@ -35,4 +35,4 @@ { new StatisticGenerator(batch, properties) }); - EventRunner eventRunner = new EventRunner(createIterator(batch)); - eventRunner.runEvents(statisticGenerator, resultCollector); + EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); + eventRunner.run(); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess());
--- a/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java +++ b/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java @@ ... @@ { new StatisticGenerator(batch, properties) }); - EventRunner eventRunner = new EventRunner(createIterator(batch)); - eventRunner.runEvents(statisticGenerator, resultCollector); + EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); + eventRunner.run(); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess());
--- a/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java +++ b/src/main/java/dk/statsbiblioteket/medieplatform/newspaper/statistics/StatisticsRunnableComponent.java @@ -35,4 +35,4 @@ CON { new StatisticGenerator(batch, properties) }); DEL EventRunner eventRunner = new EventRunner(createIterator(batch)); DEL eventRunner.runEvents(statisticGenerator, resultCollector); ADD EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); ADD eventRunner.run(); CON log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess());
<<<<<<< SEARCH List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch)); eventRunner.runEvents(statisticGenerator, resultCollector); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } ======= List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); eventRunner.run(); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } >>>>>>> REPLACE
brainwane/zulip
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f
zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py
python
apache-2.0
migrations: Fix zulipinternal migration corner case. It's theoretically possible to have configured a Zulip server where the system bots live in the same realm as normal users (and may have in fact been the default in early Zulip releases? Unclear.). We should handle these without the migration intended to clean up naming for the system bot realm crashing. Fixes #13660.
# -*- coding: utf-8 -*- from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="[email protected]") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
# -*- coding: utf-8 -*- from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return if not Realm.objects.filter(string_id="zulip").exists(): # If the user renamed the `zulip` system bot realm (or deleted # it), there's nothing for us to do. return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="[email protected]") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
4
0
1
add_only
--- a/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py +++ b/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py @@ -19,2 +19,6 @@ if Realm.objects.filter(string_id="zulipinternal").exists(): + return + if not Realm.objects.filter(string_id="zulip").exists(): + # If the user renamed the `zulip` system bot realm (or deleted + # it), there's nothing for us to do. return
--- a/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py +++ b/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py @@ ... @@ if Realm.objects.filter(string_id="zulipinternal").exists(): + return + if not Realm.objects.filter(string_id="zulip").exists(): + # If the user renamed the `zulip` system bot realm (or deleted + # it), there's nothing for us to do. return
--- a/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py +++ b/zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py @@ -19,2 +19,6 @@ CON if Realm.objects.filter(string_id="zulipinternal").exists(): ADD return ADD if not Realm.objects.filter(string_id="zulip").exists(): ADD # If the user renamed the `zulip` system bot realm (or deleted ADD # it), there's nothing for us to do. CON return
<<<<<<< SEARCH if Realm.objects.filter(string_id="zulipinternal").exists(): return ======= if Realm.objects.filter(string_id="zulipinternal").exists(): return if not Realm.objects.filter(string_id="zulip").exists(): # If the user renamed the `zulip` system bot realm (or deleted # it), there's nothing for us to do. return >>>>>>> REPLACE
MaxWhere/electron
dc1056891723ea4ca63730114384bb2bb1502f1e
lib/renderer/extensions/storage.js
javascript
mit
Handle the three get cases
const getStorage = () => { const data = window.localStorage.getItem('__chrome.storage.sync__') if (data != null) { return JSON.parse(data) } else { return {} } } const setStorage = (storage) => { const json = JSON.stringify(storage) window.localStorage.setItem('__chrome.storage.sync__', json) } module.exports = { sync: { get (keys, callback) { const storage = getStorage() if (keys === {} || keys === []) return {} if (keys === null) return storage if (typeof keys === 'string') keys = [keys] let items = {} // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] keys.forEach(function (key) { if (typeof key === 'string') { items[key] = storage[key] } else { const objKey = Object.keys(key) if (!storage[objKey] || storage[objKey] === '') { items[objKey] = key[objKey] } else { items[objKey] = storage[objKey] } } }) setTimeout(function () { callback(items) }) }, set (items, callback) { const storage = getStorage() Object.keys(items).forEach(function (name) { storage[name] = items[name] }) setStorage(storage) setTimeout(callback) } } }
const getStorage = () => { const data = window.localStorage.getItem('__chrome.storage.sync__') if (data != null) { return JSON.parse(data) } else { return {} } } const setStorage = (storage) => { const json = JSON.stringify(storage) window.localStorage.setItem('__chrome.storage.sync__', json) } module.exports = { sync: { get (keys, callback) { const storage = getStorage() if (keys == null) return storage let defaults = {} switch (typeof keys) { case 'string': keys = [keys] break case 'object': if (!Array.isArray(keys)) { defaults = keys keys = Object.keys(keys) } break; } if (keys.length === 0 ) return {} let items = {} keys.forEach(function (key) { var value = storage[key] if (value == null) value = defaults[key] items[key] = value }) setTimeout(function () { callback(items) }) }, set (items, callback) { const storage = getStorage() Object.keys(items).forEach(function (name) { storage[name] = items[name] }) setStorage(storage) setTimeout(callback) } } }
17
16
1
mixed
--- a/lib/renderer/extensions/storage.js +++ b/lib/renderer/extensions/storage.js @@ -19,22 +19,23 @@ const storage = getStorage() + if (keys == null) return storage - if (keys === {} || keys === []) return {} - if (keys === null) return storage - - if (typeof keys === 'string') keys = [keys] + let defaults = {} + switch (typeof keys) { + case 'string': + keys = [keys] + break + case 'object': + if (!Array.isArray(keys)) { + defaults = keys + keys = Object.keys(keys) + } + break; + } + if (keys.length === 0 ) return {} let items = {} - // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] keys.forEach(function (key) { - if (typeof key === 'string') { - items[key] = storage[key] - } - else { - const objKey = Object.keys(key) - if (!storage[objKey] || storage[objKey] === '') { - items[objKey] = key[objKey] - } else { - items[objKey] = storage[objKey] - } - } + var value = storage[key] + if (value == null) value = defaults[key] + items[key] = value })
--- a/lib/renderer/extensions/storage.js +++ b/lib/renderer/extensions/storage.js @@ ... @@ const storage = getStorage() + if (keys == null) return storage - if (keys === {} || keys === []) return {} - if (keys === null) return storage - - if (typeof keys === 'string') keys = [keys] + let defaults = {} + switch (typeof keys) { + case 'string': + keys = [keys] + break + case 'object': + if (!Array.isArray(keys)) { + defaults = keys + keys = Object.keys(keys) + } + break; + } + if (keys.length === 0 ) return {} let items = {} - // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] keys.forEach(function (key) { - if (typeof key === 'string') { - items[key] = storage[key] - } - else { - const objKey = Object.keys(key) - if (!storage[objKey] || storage[objKey] === '') { - items[objKey] = key[objKey] - } else { - items[objKey] = storage[objKey] - } - } + var value = storage[key] + if (value == null) value = defaults[key] + items[key] = value })
--- a/lib/renderer/extensions/storage.js +++ b/lib/renderer/extensions/storage.js @@ -19,22 +19,23 @@ CON const storage = getStorage() ADD if (keys == null) return storage CON DEL if (keys === {} || keys === []) return {} DEL if (keys === null) return storage DEL DEL if (typeof keys === 'string') keys = [keys] ADD let defaults = {} ADD switch (typeof keys) { ADD case 'string': ADD keys = [keys] ADD break ADD case 'object': ADD if (!Array.isArray(keys)) { ADD defaults = keys ADD keys = Object.keys(keys) ADD } ADD break; ADD } ADD if (keys.length === 0 ) return {} CON CON let items = {} DEL // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] CON keys.forEach(function (key) { DEL if (typeof key === 'string') { DEL items[key] = storage[key] DEL } DEL else { DEL const objKey = Object.keys(key) DEL if (!storage[objKey] || storage[objKey] === '') { DEL items[objKey] = key[objKey] DEL } else { DEL items[objKey] = storage[objKey] DEL } DEL } ADD var value = storage[key] ADD if (value == null) value = defaults[key] ADD items[key] = value CON })
<<<<<<< SEARCH get (keys, callback) { const storage = getStorage() if (keys === {} || keys === []) return {} if (keys === null) return storage if (typeof keys === 'string') keys = [keys] let items = {} // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] keys.forEach(function (key) { if (typeof key === 'string') { items[key] = storage[key] } else { const objKey = Object.keys(key) if (!storage[objKey] || storage[objKey] === '') { items[objKey] = key[objKey] } else { items[objKey] = storage[objKey] } } }) ======= get (keys, callback) { const storage = getStorage() if (keys == null) return storage let defaults = {} switch (typeof keys) { case 'string': keys = [keys] break case 'object': if (!Array.isArray(keys)) { defaults = keys keys = Object.keys(keys) } break; } if (keys.length === 0 ) return {} let items = {} keys.forEach(function (key) { var value = storage[key] if (value == null) value = defaults[key] items[key] = value }) >>>>>>> REPLACE
graydon/rust
5e983d7b3f03e9243d905e0579f32be00170c9af
src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs
rust
apache-2.0
Add a test for syntax like: ..t.s
// run-pass // Test that functional record update/struct update syntax works inside // a closure when the feature `capture_disjoint_fields` is enabled. #![feature(capture_disjoint_fields)] //~^ WARNING: the feature `capture_disjoint_fields` is incomplete //~| NOTE: `#[warn(incomplete_features)]` on by default //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> struct S { a: String, b: String, } fn main() { let a = String::new(); let b = String::new(); let s = S {a, b}; let c = || { let s2 = S { a: format!("New a"), ..s }; println!("{} {}", s2.a, s2.b); }; c(); }
// run-pass // Test that functional record update/struct update syntax works inside // a closure when the feature `capture_disjoint_fields` is enabled. #![feature(capture_disjoint_fields)] //~^ WARNING: the feature `capture_disjoint_fields` is incomplete //~| NOTE: `#[warn(incomplete_features)]` on by default //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> #[derive(Clone)] struct S { a: String, b: String, } struct T { a: String, s: S, } fn main() { let a = String::new(); let b = String::new(); let c = String::new(); let s = S {a, b}; let t = T { a: c, s: s.clone() }; let c = || { let s2 = S { a: format!("New s2"), ..s }; let s3 = S { a: format!("New s3"), ..t.s }; println!("{} {}", s2.a, s2.b); println!("{} {} {}", s3.a, s3.b, t.a); }; c(); }
17
1
4
mixed
--- a/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs +++ b/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs @@ -10,2 +10,3 @@ +#[derive(Clone)] struct S { @@ -15,2 +16,7 @@ +struct T { + a: String, + s: S, +} + fn main() { @@ -18,3 +24,8 @@ let b = String::new(); + let c = String::new(); let s = S {a, b}; + let t = T { + a: c, + s: s.clone() + }; @@ -22,6 +33,11 @@ let s2 = S { - a: format!("New a"), + a: format!("New s2"), ..s }; + let s3 = S { + a: format!("New s3"), + ..t.s + }; println!("{} {}", s2.a, s2.b); + println!("{} {} {}", s3.a, s3.b, t.a); };
--- a/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs +++ b/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs @@ ... @@ +#[derive(Clone)] struct S { @@ ... @@ +struct T { + a: String, + s: S, +} + fn main() { @@ ... @@ let b = String::new(); + let c = String::new(); let s = S {a, b}; + let t = T { + a: c, + s: s.clone() + }; @@ ... @@ let s2 = S { - a: format!("New a"), + a: format!("New s2"), ..s }; + let s3 = S { + a: format!("New s3"), + ..t.s + }; println!("{} {}", s2.a, s2.b); + println!("{} {} {}", s3.a, s3.b, t.a); };
--- a/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs +++ b/src/test/ui/closures/2229_closure_analysis/run_pass/fru_syntax.rs @@ -10,2 +10,3 @@ CON ADD #[derive(Clone)] CON struct S { @@ -15,2 +16,7 @@ CON ADD struct T { ADD a: String, ADD s: S, ADD } ADD CON fn main() { @@ -18,3 +24,8 @@ CON let b = String::new(); ADD let c = String::new(); CON let s = S {a, b}; ADD let t = T { ADD a: c, ADD s: s.clone() ADD }; CON @@ -22,6 +33,11 @@ CON let s2 = S { DEL a: format!("New a"), ADD a: format!("New s2"), CON ..s CON }; ADD let s3 = S { ADD a: format!("New s3"), ADD ..t.s ADD }; CON println!("{} {}", s2.a, s2.b); ADD println!("{} {} {}", s3.a, s3.b, t.a); CON };
<<<<<<< SEARCH //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> struct S { a: String, b: String, } fn main() { let a = String::new(); let b = String::new(); let s = S {a, b}; let c = || { let s2 = S { a: format!("New a"), ..s }; println!("{} {}", s2.a, s2.b); }; ======= //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> #[derive(Clone)] struct S { a: String, b: String, } struct T { a: String, s: S, } fn main() { let a = String::new(); let b = String::new(); let c = String::new(); let s = S {a, b}; let t = T { a: c, s: s.clone() }; let c = || { let s2 = S { a: format!("New s2"), ..s }; let s3 = S { a: format!("New s3"), ..t.s }; println!("{} {}", s2.a, s2.b); println!("{} {} {}", s3.a, s3.b, t.a); }; >>>>>>> REPLACE
handstandsam/ShoppingApp
547358e198e0a9e820aa5d5ee0c6792d796c04f5
shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt
kotlin
apache-2.0
Make it more clear how we are sending updates to the channel.
package com.handstandsam.shoppingapp.cart import com.handstandsam.shoppingapp.models.ItemWithQuantity import kotlinx.coroutines.channels.ConflatedBroadcastChannel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow /** * In memory implementation of our [ShoppingCartDao] */ class InMemoryShoppingCartDao : ShoppingCartDao { private val itemsInCart: MutableMap<String, ItemWithQuantity> = mutableMapOf() private val channel = ConflatedBroadcastChannel(listOf<ItemWithQuantity>()) override suspend fun findByLabel(label: String): ItemWithQuantity? { return itemsInCart[label] } override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemsInCart[itemWithQuantity.item.label] = itemWithQuantity sendUpdateChannel() } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemsInCart.remove(itemWithQuantity.item.label) sendUpdateChannel() } override suspend fun empty() { itemsInCart.clear() sendUpdateChannel() } override val allItems: Flow<List<ItemWithQuantity>> get() = channel.asFlow() private suspend fun sendUpdateChannel() { channel.send( itemsInCart.values.toList() .sortedBy { it.item.label } ) } }
package com.handstandsam.shoppingapp.cart import com.handstandsam.shoppingapp.models.ItemWithQuantity import kotlinx.coroutines.channels.ConflatedBroadcastChannel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow /** * In memory implementation of our [ShoppingCartDao] */ class InMemoryShoppingCartDao : ShoppingCartDao { private val itemsInCart: MutableMap<String, ItemWithQuantity> = mutableMapOf() private val channel = ConflatedBroadcastChannel(listOf<ItemWithQuantity>()) override suspend fun findByLabel(label: String): ItemWithQuantity? { return itemsInCart[label] } override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemsInCart[itemWithQuantity.item.label] = itemWithQuantity channel.send(itemsInCart.asSortedList()) } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemsInCart.remove(itemWithQuantity.item.label) channel.send(itemsInCart.asSortedList()) } override suspend fun empty() { itemsInCart.clear() channel.send(itemsInCart.asSortedList()) } override val allItems: Flow<List<ItemWithQuantity>> get() = channel.asFlow() private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> { return values.toList() .sortedBy { it.item.label } } }
6
8
4
mixed
--- a/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt +++ b/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt @@ -22,3 +22,3 @@ itemsInCart[itemWithQuantity.item.label] = itemWithQuantity - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ -27,3 +27,3 @@ itemsInCart.remove(itemWithQuantity.item.label) - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ -32,3 +32,3 @@ itemsInCart.clear() - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ -38,7 +38,5 @@ - private suspend fun sendUpdateChannel() { - channel.send( - itemsInCart.values.toList() - .sortedBy { it.item.label } - ) + private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> { + return values.toList() + .sortedBy { it.item.label } }
--- a/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt +++ b/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt @@ ... @@ itemsInCart[itemWithQuantity.item.label] = itemWithQuantity - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ ... @@ itemsInCart.remove(itemWithQuantity.item.label) - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ ... @@ itemsInCart.clear() - sendUpdateChannel() + channel.send(itemsInCart.asSortedList()) } @@ ... @@ - private suspend fun sendUpdateChannel() { - channel.send( - itemsInCart.values.toList() - .sortedBy { it.item.label } - ) + private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> { + return values.toList() + .sortedBy { it.item.label } }
--- a/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt +++ b/shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/InMemoryShoppingCartDao.kt @@ -22,3 +22,3 @@ CON itemsInCart[itemWithQuantity.item.label] = itemWithQuantity DEL sendUpdateChannel() ADD channel.send(itemsInCart.asSortedList()) CON } @@ -27,3 +27,3 @@ CON itemsInCart.remove(itemWithQuantity.item.label) DEL sendUpdateChannel() ADD channel.send(itemsInCart.asSortedList()) CON } @@ -32,3 +32,3 @@ CON itemsInCart.clear() DEL sendUpdateChannel() ADD channel.send(itemsInCart.asSortedList()) CON } @@ -38,7 +38,5 @@ CON DEL private suspend fun sendUpdateChannel() { DEL channel.send( DEL itemsInCart.values.toList() DEL .sortedBy { it.item.label } DEL ) ADD private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> { ADD return values.toList() ADD .sortedBy { it.item.label } CON }
<<<<<<< SEARCH override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemsInCart[itemWithQuantity.item.label] = itemWithQuantity sendUpdateChannel() } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemsInCart.remove(itemWithQuantity.item.label) sendUpdateChannel() } override suspend fun empty() { itemsInCart.clear() sendUpdateChannel() } override val allItems: Flow<List<ItemWithQuantity>> get() = channel.asFlow() private suspend fun sendUpdateChannel() { channel.send( itemsInCart.values.toList() .sortedBy { it.item.label } ) } ======= override suspend fun upsert(itemWithQuantity: ItemWithQuantity) { itemsInCart[itemWithQuantity.item.label] = itemWithQuantity channel.send(itemsInCart.asSortedList()) } override suspend fun remove(itemWithQuantity: ItemWithQuantity) { itemsInCart.remove(itemWithQuantity.item.label) channel.send(itemsInCart.asSortedList()) } override suspend fun empty() { itemsInCart.clear() channel.send(itemsInCart.asSortedList()) } override val allItems: Flow<List<ItemWithQuantity>> get() = channel.asFlow() private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> { return values.toList() .sortedBy { it.item.label } } >>>>>>> REPLACE
virajs/selenium-1
03075139596781aeeab98f4f1ea17644d10220f5
selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java
java
apache-2.0
SimonStewart: Make the selenium-backed webdriver emulate the normal webdriver's xpath mode git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@10674 07704840-8298-11de-bf8c-fd130f914ac9
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.internal.selenesedriver; import com.thoughtworks.selenium.Selenium; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import java.util.HashMap; import java.util.Map; public class NewSession implements SeleneseFunction<Map<String, Object>> { public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); seenCapabilities.put("browserName", capabilities.getBrowserName()); seenCapabilities.put("version", capabilities.getVersion()); seenCapabilities.put("platform", Platform.getCurrent().toString()); seenCapabilities.put("javascriptEnabled", true); return seenCapabilities; } }
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.internal.selenesedriver; import com.thoughtworks.selenium.Selenium; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import java.util.HashMap; import java.util.Map; public class NewSession implements SeleneseFunction<Map<String, Object>> { public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); // Emulate behaviour of webdriver selenium.useXpathLibrary("javascript-xpath"); selenium.allowNativeXpath("true"); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); seenCapabilities.put("browserName", capabilities.getBrowserName()); seenCapabilities.put("version", capabilities.getVersion()); seenCapabilities.put("platform", Platform.getCurrent().toString()); seenCapabilities.put("javascriptEnabled", true); return seenCapabilities; } }
5
0
1
add_only
--- a/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java +++ b/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java @@ -29,2 +29,7 @@ selenium.start(); + + // Emulate behaviour of webdriver + selenium.useXpathLibrary("javascript-xpath"); + selenium.allowNativeXpath("true"); + Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
--- a/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java +++ b/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java @@ ... @@ selenium.start(); + + // Emulate behaviour of webdriver + selenium.useXpathLibrary("javascript-xpath"); + selenium.allowNativeXpath("true"); + Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
--- a/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java +++ b/selenium/src/java/org/openqa/selenium/internal/selenesedriver/NewSession.java @@ -29,2 +29,7 @@ CON selenium.start(); ADD ADD // Emulate behaviour of webdriver ADD selenium.useXpathLibrary("javascript-xpath"); ADD selenium.allowNativeXpath("true"); ADD CON Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
<<<<<<< SEARCH public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); ======= public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); // Emulate behaviour of webdriver selenium.useXpathLibrary("javascript-xpath"); selenium.allowNativeXpath("true"); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); >>>>>>> REPLACE
TAOTheCrab/CrabBot
9cb406e18cedf8995c31a1760968a1ee86423c5f
setup.py
python
mit
Tweak the package name, add a note
#!/usr/bin/env python3 from setuptools import setup, find_packages # We want to restrict newer versions while we deal with upstream breaking changes. discordpy_version = '==0.10.0' # TODO read README(.rst? .md looks bad on pypi) for long_description. # Could use pandoc, but the end user shouldn't need to do this in setup. # Alt. could have package-specific description. More error-prone though. setup( # More permanent entries name='CrabBot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License' 'Programming Language :: Python :: 3.5' ], # Entries likely to be modified description='A simple Discord bot', version='0.0.1', # TODO figure out a version scheme. Ensure this gets updated. packages=find_packages(), # A little lazy install_requires=[ 'discord.py{}'.format(discordpy_version) ], extras_require={ 'voice': [ 'discord.py[voice]{}'.format(discordpy_version), 'youtube_dl' ] } )
#!/usr/bin/env python3 from setuptools import setup, find_packages # We want to restrict newer versions while we deal with upstream breaking changes. discordpy_version = '==0.10.0' # TODO read README(.rst? .md looks bad on pypi) for long_description. # Could use pandoc, but the end user shouldn't need to do this in setup. # Alt. could have package-specific description. More error-prone though. setup( # More permanent entries name='crabbot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License' 'Programming Language :: Python :: 3.5' ], # Entries likely to be modified description='A simple Discord bot', version='0.0.1', # TODO figure out a version scheme. Ensure this gets updated. packages=find_packages(), # A little lazy install_requires=[ 'discord.py{}'.format(discordpy_version) ], extras_require={ 'voice': [ 'discord.py[voice]{}'.format(discordpy_version), 'youtube_dl' ] } # scripts=['__main__.py'] )
3
1
2
mixed
--- a/setup.py +++ b/setup.py @@ -13,3 +13,3 @@ # More permanent entries - name='CrabBot', + name='crabbot', author='TAOTheCrab', @@ -38,2 +38,4 @@ } + + # scripts=['__main__.py'] )
--- a/setup.py +++ b/setup.py @@ ... @@ # More permanent entries - name='CrabBot', + name='crabbot', author='TAOTheCrab', @@ ... @@ } + + # scripts=['__main__.py'] )
--- a/setup.py +++ b/setup.py @@ -13,3 +13,3 @@ CON # More permanent entries DEL name='CrabBot', ADD name='crabbot', CON author='TAOTheCrab', @@ -38,2 +38,4 @@ CON } ADD ADD # scripts=['__main__.py'] CON )
<<<<<<< SEARCH setup( # More permanent entries name='CrabBot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', ======= setup( # More permanent entries name='crabbot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', >>>>>>> REPLACE
zalando/nakadi
c3cdff70a8ecf349b0655fda59a765fd9bd1e172
core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java
java
mit
Revert "Trying direct printing instead of logs" This reverts commit 92953b6f541fc94e7f4b93d5d8ac1faa8d240ca9.
package org.zalando.nakadi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.HashSet; import java.util.Set; public class ShutdownHooks { private static final Set<Runnable> HOOKS = new HashSet<>(); private static final Logger LOG = LoggerFactory.getLogger(ShutdownHooks.class); static { Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::onNodeShutdown)); } private static void onNodeShutdown() { System.out.println("Processing shutdown hooks"); boolean haveHooks = true; while (haveHooks) { final Runnable hook; synchronized (HOOKS) { hook = HOOKS.isEmpty() ? null : HOOKS.iterator().next(); HOOKS.remove(hook); haveHooks = !HOOKS.isEmpty(); } if (null != hook) { try { hook.run(); } catch (final RuntimeException ex) { LOG.warn("Failed to call on shutdown hook for {}", hook, ex); } } } System.out.println("Finished processing shutdown hooks"); } public static Closeable addHook(final Runnable runnable) { synchronized (HOOKS) { HOOKS.add(runnable); } return () -> removeHook(runnable); } private static void removeHook(final Runnable runnable) { synchronized (HOOKS) { HOOKS.remove(runnable); } } }
package org.zalando.nakadi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.HashSet; import java.util.Set; public class ShutdownHooks { private static final Set<Runnable> HOOKS = new HashSet<>(); private static final Logger LOG = LoggerFactory.getLogger(ShutdownHooks.class); static { Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::onNodeShutdown)); } private static void onNodeShutdown() { LOG.info("Processing shutdown hooks"); boolean haveHooks = true; while (haveHooks) { final Runnable hook; synchronized (HOOKS) { hook = HOOKS.isEmpty() ? null : HOOKS.iterator().next(); HOOKS.remove(hook); haveHooks = !HOOKS.isEmpty(); } if (null != hook) { try { hook.run(); } catch (final RuntimeException ex) { LOG.warn("Failed to call on shutdown hook for {}", hook, ex); } } } LOG.info("Finished processing shutdown hooks"); } public static Closeable addHook(final Runnable runnable) { synchronized (HOOKS) { HOOKS.add(runnable); } return () -> removeHook(runnable); } private static void removeHook(final Runnable runnable) { synchronized (HOOKS) { HOOKS.remove(runnable); } } }
2
2
2
mixed
--- a/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java +++ b/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java @@ -19,3 +19,3 @@ private static void onNodeShutdown() { - System.out.println("Processing shutdown hooks"); + LOG.info("Processing shutdown hooks"); boolean haveHooks = true; @@ -36,3 +36,3 @@ } - System.out.println("Finished processing shutdown hooks"); + LOG.info("Finished processing shutdown hooks"); }
--- a/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java +++ b/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java @@ ... @@ private static void onNodeShutdown() { - System.out.println("Processing shutdown hooks"); + LOG.info("Processing shutdown hooks"); boolean haveHooks = true; @@ ... @@ } - System.out.println("Finished processing shutdown hooks"); + LOG.info("Finished processing shutdown hooks"); }
--- a/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java +++ b/core-services/src/main/java/org/zalando/nakadi/ShutdownHooks.java @@ -19,3 +19,3 @@ CON private static void onNodeShutdown() { DEL System.out.println("Processing shutdown hooks"); ADD LOG.info("Processing shutdown hooks"); CON boolean haveHooks = true; @@ -36,3 +36,3 @@ CON } DEL System.out.println("Finished processing shutdown hooks"); ADD LOG.info("Finished processing shutdown hooks"); CON }
<<<<<<< SEARCH private static void onNodeShutdown() { System.out.println("Processing shutdown hooks"); boolean haveHooks = true; while (haveHooks) { ======= private static void onNodeShutdown() { LOG.info("Processing shutdown hooks"); boolean haveHooks = true; while (haveHooks) { >>>>>>> REPLACE
robinverduijn/gradle
aa7e53822a3815ccb655b1c12dabedc7b2302578
provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt
kotlin
apache-2.0
Add newly added configurations to test case expectation
package org.gradle.kotlin.dsl.accessors import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class GenerateProjectSchemaTest : AbstractIntegrationTest() { @Test fun `writes multi-project schema to gradle slash project dash schema dot json`() { withBuildScript(""" plugins { java } """) build("kotlinDslAccessorsSnapshot") val generatedSchema = loadMultiProjectSchemaFrom( existing("gradle/project-schema.json")) val expectedSchema = mapOf( ":" to ProjectSchema( extensions = mapOf( "defaultArtifacts" to "org.gradle.api.internal.plugins.DefaultArtifactPublicationSet", "ext" to "org.gradle.api.plugins.ExtraPropertiesExtension", "reporting" to "org.gradle.api.reporting.ReportingExtension"), conventions = mapOf( "base" to "org.gradle.api.plugins.BasePluginConvention", "java" to "org.gradle.api.plugins.JavaPluginConvention"), configurations = listOf( "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation", "testRuntime", "testRuntimeClasspath", "testRuntimeOnly"))) assertThat( generatedSchema, equalTo(expectedSchema)) } }
package org.gradle.kotlin.dsl.accessors import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class GenerateProjectSchemaTest : AbstractIntegrationTest() { @Test fun `writes multi-project schema to gradle slash project dash schema dot json`() { withBuildScript(""" plugins { java } """) build("kotlinDslAccessorsSnapshot") val generatedSchema = loadMultiProjectSchemaFrom( existing("gradle/project-schema.json")) val expectedSchema = mapOf( ":" to ProjectSchema( extensions = mapOf( "defaultArtifacts" to "org.gradle.api.internal.plugins.DefaultArtifactPublicationSet", "ext" to "org.gradle.api.plugins.ExtraPropertiesExtension", "reporting" to "org.gradle.api.reporting.ReportingExtension"), conventions = mapOf( "base" to "org.gradle.api.plugins.BasePluginConvention", "java" to "org.gradle.api.plugins.JavaPluginConvention"), configurations = listOf( "annotationProcessor", "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", "testAnnotationProcessor", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation", "testRuntime", "testRuntimeClasspath", "testRuntimeOnly"))) assertThat( generatedSchema, equalTo(expectedSchema)) } }
2
0
1
add_only
--- a/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt +++ b/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt @@ -34,4 +34,6 @@ configurations = listOf( + "annotationProcessor", "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", + "testAnnotationProcessor", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation",
--- a/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt +++ b/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt @@ ... @@ configurations = listOf( + "annotationProcessor", "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", + "testAnnotationProcessor", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation",
--- a/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt +++ b/provider/src/test/kotlin/org/gradle/kotlin/dsl/accessors/GenerateProjectSchemaTest.kt @@ -34,4 +34,6 @@ CON configurations = listOf( ADD "annotationProcessor", CON "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", CON "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", ADD "testAnnotationProcessor", CON "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation",
<<<<<<< SEARCH "java" to "org.gradle.api.plugins.JavaPluginConvention"), configurations = listOf( "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation", "testRuntime", "testRuntimeClasspath", "testRuntimeOnly"))) ======= "java" to "org.gradle.api.plugins.JavaPluginConvention"), configurations = listOf( "annotationProcessor", "apiElements", "archives", "compile", "compileClasspath", "compileOnly", "default", "implementation", "runtime", "runtimeClasspath", "runtimeElements", "runtimeOnly", "testAnnotationProcessor", "testCompile", "testCompileClasspath", "testCompileOnly", "testImplementation", "testRuntime", "testRuntimeClasspath", "testRuntimeOnly"))) >>>>>>> REPLACE
sourrust/flac
1c8e33fbb051c4ab70e421164f03f557788f5741
examples/metadata.rs
rust
bsd-3-clause
Fix typo for picture subcommand
extern crate docopt; extern crate flac; extern crate rustc_serialize; #[macro_use] mod commands; use std::env; use commands::{streaminfo, comments, seektable, picture}; use docopt::Docopt; const USAGE: &'static str = " Usage: metadata <command> [<args>...] metadata [options] Options: -h, --help Show this message. Commands: streaminfo Display stream information. comments Display or export comment tags. seektable Display seek table. picture Export picutes. "; #[derive(Debug, RustcDecodable)] struct Arguments { arg_command: Option<Command>, arg_args: Vec<String>, } #[derive(Clone, Copy, Debug, RustcDecodable)] enum Command { StreamInfo, Comments, SeekTable, Picture, } fn handle_subcommand(command: Command) { match command { Command::StreamInfo => command!(streaminfo), Command::Comments => command!(comments), Command::SeekTable => command!(seektable), Command::Picture => command!(picture), } } fn main() { let args: Arguments = Docopt::new(USAGE) .and_then(|d| d.options_first(true).decode()) .unwrap_or_else(|e| e.exit()); if let Some(command) = args.arg_command { handle_subcommand(command); } else { println!("{}", USAGE); } }
extern crate docopt; extern crate flac; extern crate rustc_serialize; #[macro_use] mod commands; use std::env; use commands::{streaminfo, comments, seektable, picture}; use docopt::Docopt; const USAGE: &'static str = " Usage: metadata <command> [<args>...] metadata [options] Options: -h, --help Show this message. Commands: streaminfo Display stream information. comments Display or export comment tags. seektable Display seek table. picture Export pictures. "; #[derive(Debug, RustcDecodable)] struct Arguments { arg_command: Option<Command>, arg_args: Vec<String>, } #[derive(Clone, Copy, Debug, RustcDecodable)] enum Command { StreamInfo, Comments, SeekTable, Picture, } fn handle_subcommand(command: Command) { match command { Command::StreamInfo => command!(streaminfo), Command::Comments => command!(comments), Command::SeekTable => command!(seektable), Command::Picture => command!(picture), } } fn main() { let args: Arguments = Docopt::new(USAGE) .and_then(|d| d.options_first(true).decode()) .unwrap_or_else(|e| e.exit()); if let Some(command) = args.arg_command { handle_subcommand(command); } else { println!("{}", USAGE); } }
1
1
1
mixed
--- a/examples/metadata.rs +++ b/examples/metadata.rs @@ -23,3 +23,3 @@ seektable Display seek table. - picture Export picutes. + picture Export pictures. ";
--- a/examples/metadata.rs +++ b/examples/metadata.rs @@ ... @@ seektable Display seek table. - picture Export picutes. + picture Export pictures. ";
--- a/examples/metadata.rs +++ b/examples/metadata.rs @@ -23,3 +23,3 @@ CON seektable Display seek table. DEL picture Export picutes. ADD picture Export pictures. CON ";
<<<<<<< SEARCH comments Display or export comment tags. seektable Display seek table. picture Export picutes. "; ======= comments Display or export comment tags. seektable Display seek table. picture Export pictures. "; >>>>>>> REPLACE
KotlinNLP/SimpleDNN
b93fa5bac8557476a03f6d53f042bac1db909ebc
src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt
kotlin
mpl-2.0
Add shape and size attributes
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.simplemath.ndarray /** * */ class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> { init { require(dim1.size == dim2.size) } /** * */ private inner class NDArrayMaskIterator : Iterator<Indices> { /** * */ private var curIndex = 0 /** * */ override fun hasNext(): Boolean = curIndex < [email protected] /** * */ override fun next(): Indices { val next = Pair([email protected][curIndex], [email protected][curIndex]) this.curIndex++ return next } } /** * */ override fun iterator(): Iterator<Indices> = this.NDArrayMaskIterator() }
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.simplemath.ndarray /** * */ class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> { init { require(dim1.size == dim2.size) } /** * */ val size = dim1.size /** * */ private inner class NDArrayMaskIterator : Iterator<Indices> { /** * */ private var curIndex = 0 /** * */ override fun hasNext(): Boolean = curIndex < [email protected] /** * */ override fun next(): Indices { val next = Pair([email protected][curIndex], [email protected][curIndex]) this.curIndex++ return next } } /** * */ override fun iterator(): Iterator<Indices> = this.NDArrayMaskIterator() }
6
1
2
mixed
--- a/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt +++ b/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt @@ -12,3 +12,3 @@ */ -class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> { +class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> { @@ -17,2 +17,7 @@ } + + /** + * + */ + val size = dim1.size
--- a/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt +++ b/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt @@ ... @@ */ -class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> { +class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> { @@ ... @@ } + + /** + * + */ + val size = dim1.size
--- a/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt +++ b/src/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArrayMask.kt @@ -12,3 +12,3 @@ CON */ DEL class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> { ADD class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> { CON @@ -17,2 +17,7 @@ CON } ADD ADD /** ADD * ADD */ ADD val size = dim1.size CON
<<<<<<< SEARCH * */ class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> { init { require(dim1.size == dim2.size) } /** ======= * */ class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> { init { require(dim1.size == dim2.size) } /** * */ val size = dim1.size /** >>>>>>> REPLACE
squanchy-dev/squanchy-android
5e29239f9c775d2bbda771c4a9f4688d2bc7028d
app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt
kotlin
apache-2.0
Change scrolling to next event logic If we're less than 60% through the current item, scroll to the current item. Otherwise, scroll to the next item.
package net.squanchy.schedule.domain.view import net.squanchy.support.system.CurrentTime import org.joda.time.DateTimeZone private const val NOT_FOUND_INDEX = -1 private const val FIRST_PAGE_INDEX = 0 data class Schedule(val pages: List<SchedulePage>, val timezone: DateTimeZone) { val isEmpty: Boolean get() = pages.isEmpty() companion object { fun create(pages: List<SchedulePage>, timezone: DateTimeZone) = Schedule(pages, timezone) } fun findTodayIndexOrDefault(currentTime: CurrentTime) = pages .indexOfFirst { page -> val now = currentTime.currentDateTime().toDateTime(timezone) page.date.toLocalDate().isEqual(now.toLocalDate()) } .let { when (it) { NOT_FOUND_INDEX -> FIRST_PAGE_INDEX else -> it } } fun findNextEventForPage(page: SchedulePage, currentTime: CurrentTime) = page .events .firstOrNull { event -> val startDateTime = event.startTime.toDateTime().withZone(event.timeZone) val currentDateTime = currentTime.currentDateTime().toDateTime().withZone(event.timeZone) startDateTime.isAfter(currentDateTime) } }
package net.squanchy.schedule.domain.view import net.squanchy.support.system.CurrentTime import org.joda.time.DateTimeZone private const val NOT_FOUND_INDEX = -1 private const val FIRST_PAGE_INDEX = 0 private const val CURRENT_SLOT_THRESHOLD = .6f data class Schedule(val pages: List<SchedulePage>, val timezone: DateTimeZone) { val isEmpty: Boolean get() = pages.isEmpty() companion object { fun create(pages: List<SchedulePage>, timezone: DateTimeZone) = Schedule(pages, timezone) } fun findTodayIndexOrDefault(currentTime: CurrentTime) = pages .indexOfFirst { page -> val now = currentTime.currentDateTime().toDateTime(timezone) page.date.toLocalDate().isEqual(now.toLocalDate()) } .let { when (it) { NOT_FOUND_INDEX -> FIRST_PAGE_INDEX else -> it } } fun findNextEventForPage(page: SchedulePage, currentTime: CurrentTime) = page.events .firstOrNull { event -> val startDateTime = event.startTime.toDateTime().withZone(event.timeZone) val currentDateTime = currentTime.currentDateTime().toDateTime().withZone(event.timeZone) val endDateTime = event.endTime.toDateTime().withZone(event.timeZone) if (currentDateTime.isAfter(endDateTime)) { false } else { val duration = endDateTime.millis - startDateTime.millis val offset = currentDateTime.millis - startDateTime.millis offset.toFloat() / duration < CURRENT_SLOT_THRESHOLD } } }
13
3
3
mixed
--- a/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt +++ b/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt @@ -7,2 +7,4 @@ private const val FIRST_PAGE_INDEX = 0 + +private const val CURRENT_SLOT_THRESHOLD = .6f @@ -32,4 +34,3 @@ fun findNextEventForPage(page: SchedulePage, currentTime: CurrentTime) = - page - .events + page.events .firstOrNull { event -> @@ -37,3 +38,12 @@ val currentDateTime = currentTime.currentDateTime().toDateTime().withZone(event.timeZone) - startDateTime.isAfter(currentDateTime) + val endDateTime = event.endTime.toDateTime().withZone(event.timeZone) + + if (currentDateTime.isAfter(endDateTime)) { + false + } else { + val duration = endDateTime.millis - startDateTime.millis + val offset = currentDateTime.millis - startDateTime.millis + + offset.toFloat() / duration < CURRENT_SLOT_THRESHOLD + } }
--- a/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt +++ b/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt @@ ... @@ private const val FIRST_PAGE_INDEX = 0 + +private const val CURRENT_SLOT_THRESHOLD = .6f @@ ... @@ fun findNextEventForPage(page: SchedulePage, currentTime: CurrentTime) = - page - .events + page.events .firstOrNull { event -> @@ ... @@ val currentDateTime = currentTime.currentDateTime().toDateTime().withZone(event.timeZone) - startDateTime.isAfter(currentDateTime) + val endDateTime = event.endTime.toDateTime().withZone(event.timeZone) + + if (currentDateTime.isAfter(endDateTime)) { + false + } else { + val duration = endDateTime.millis - startDateTime.millis + val offset = currentDateTime.millis - startDateTime.millis + + offset.toFloat() / duration < CURRENT_SLOT_THRESHOLD + } }
--- a/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt +++ b/app/src/main/java/net/squanchy/schedule/domain/view/Schedule.kt @@ -7,2 +7,4 @@ CON private const val FIRST_PAGE_INDEX = 0 ADD ADD private const val CURRENT_SLOT_THRESHOLD = .6f CON @@ -32,4 +34,3 @@ CON fun findNextEventForPage(page: SchedulePage, currentTime: CurrentTime) = DEL page DEL .events ADD page.events CON .firstOrNull { event -> @@ -37,3 +38,12 @@ CON val currentDateTime = currentTime.currentDateTime().toDateTime().withZone(event.timeZone) DEL startDateTime.isAfter(currentDateTime) ADD val endDateTime = event.endTime.toDateTime().withZone(event.timeZone) ADD ADD if (currentDateTime.isAfter(endDateTime)) { ADD false ADD } else { ADD val duration = endDateTime.millis - startDateTime.millis ADD val offset = currentDateTime.millis - startDateTime.millis ADD ADD offset.toFloat() / duration < CURRENT_SLOT_THRESHOLD ADD } CON }
<<<<<<< SEARCH private const val NOT_FOUND_INDEX = -1 private const val FIRST_PAGE_INDEX = 0 data class Schedule(val pages: List<SchedulePage>, val timezone: DateTimeZone) { ======= private const val NOT_FOUND_INDEX = -1 private const val FIRST_PAGE_INDEX = 0 private const val CURRENT_SLOT_THRESHOLD = .6f data class Schedule(val pages: List<SchedulePage>, val timezone: DateTimeZone) { >>>>>>> REPLACE
ampl/amplpy
48394c55599968c456f1f58c0fcdf58e1750f293
amplpy/tests/TestBase.py
python
bsd-3-clause
Add workaround for tests on MSYS2 and MINGW
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def str2file(self, filename, content): fullpath = self.tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return fullpath def tmpfile(self, filename): return os.path.join(self.dirpath, filename) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os # For MSYS2, MINGW, etc., run with: # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests REAL_ROOT = os.environ.get('REAL_ROOT', None) class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def _tmpfile(self, filename): return os.path.join(self.dirpath, filename) def _real_filename(self, filename): # Workaround for MSYS2, MINGW paths if REAL_ROOT is not None and filename.startswith('/'): filename = filename.replace('/', REAL_ROOT, 1) return filename def str2file(self, filename, content): fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return self._real_filename(fullpath) def tmpfile(self, filename): return self._real_filename(self._tmpfile(filename)) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
17
3
2
mixed
--- a/amplpy/tests/TestBase.py +++ b/amplpy/tests/TestBase.py @@ -12,2 +12,7 @@ +# For MSYS2, MINGW, etc., run with: +# $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests +REAL_ROOT = os.environ.get('REAL_ROOT', None) + + class TestBase(unittest.TestCase): @@ -17,10 +22,19 @@ + def _tmpfile(self, filename): + return os.path.join(self.dirpath, filename) + + def _real_filename(self, filename): + # Workaround for MSYS2, MINGW paths + if REAL_ROOT is not None and filename.startswith('/'): + filename = filename.replace('/', REAL_ROOT, 1) + return filename + def str2file(self, filename, content): - fullpath = self.tmpfile(filename) + fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) - return fullpath + return self._real_filename(fullpath) def tmpfile(self, filename): - return os.path.join(self.dirpath, filename) + return self._real_filename(self._tmpfile(filename))
--- a/amplpy/tests/TestBase.py +++ b/amplpy/tests/TestBase.py @@ ... @@ +# For MSYS2, MINGW, etc., run with: +# $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests +REAL_ROOT = os.environ.get('REAL_ROOT', None) + + class TestBase(unittest.TestCase): @@ ... @@ + def _tmpfile(self, filename): + return os.path.join(self.dirpath, filename) + + def _real_filename(self, filename): + # Workaround for MSYS2, MINGW paths + if REAL_ROOT is not None and filename.startswith('/'): + filename = filename.replace('/', REAL_ROOT, 1) + return filename + def str2file(self, filename, content): - fullpath = self.tmpfile(filename) + fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) - return fullpath + return self._real_filename(fullpath) def tmpfile(self, filename): - return os.path.join(self.dirpath, filename) + return self._real_filename(self._tmpfile(filename))
--- a/amplpy/tests/TestBase.py +++ b/amplpy/tests/TestBase.py @@ -12,2 +12,7 @@ CON ADD # For MSYS2, MINGW, etc., run with: ADD # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests ADD REAL_ROOT = os.environ.get('REAL_ROOT', None) ADD ADD CON class TestBase(unittest.TestCase): @@ -17,10 +22,19 @@ CON ADD def _tmpfile(self, filename): ADD return os.path.join(self.dirpath, filename) ADD ADD def _real_filename(self, filename): ADD # Workaround for MSYS2, MINGW paths ADD if REAL_ROOT is not None and filename.startswith('/'): ADD filename = filename.replace('/', REAL_ROOT, 1) ADD return filename ADD CON def str2file(self, filename, content): DEL fullpath = self.tmpfile(filename) ADD fullpath = self._tmpfile(filename) CON with open(fullpath, 'w') as f: CON print(content, file=f) DEL return fullpath ADD return self._real_filename(fullpath) CON CON def tmpfile(self, filename): DEL return os.path.join(self.dirpath, filename) ADD return self._real_filename(self._tmpfile(filename)) CON
<<<<<<< SEARCH class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def str2file(self, filename, content): fullpath = self.tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return fullpath def tmpfile(self, filename): return os.path.join(self.dirpath, filename) def tearDown(self): ======= # For MSYS2, MINGW, etc., run with: # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests REAL_ROOT = os.environ.get('REAL_ROOT', None) class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def _tmpfile(self, filename): return os.path.join(self.dirpath, filename) def _real_filename(self, filename): # Workaround for MSYS2, MINGW paths if REAL_ROOT is not None and filename.startswith('/'): filename = filename.replace('/', REAL_ROOT, 1) return filename def str2file(self, filename, content): fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return self._real_filename(fullpath) def tmpfile(self, filename): return self._real_filename(self._tmpfile(filename)) def tearDown(self): >>>>>>> REPLACE
achanda/crates.io
fadf6b94caec4c9fc1afd4cc7767afdb1105668c
src/dist.rs
rust
apache-2.0
Revert "Assume html if no Accept header is presented" This reverts commit c9e1c375841ddc4a21d7792ecabbe4b7c7cc0a46.
use std::error::Error; use conduit::{Request, Response, Handler}; use conduit_static::Static; use conduit_middleware::AroundMiddleware; use util::RequestProxy; pub struct Middleware { handler: Option<Box<Handler>>, dist: Static, } impl Middleware { pub fn new() -> Middleware { Middleware { handler: None, dist: Static::new("dist"), } } } impl AroundMiddleware for Middleware { fn with_handler(&mut self, handler: Box<Handler>) { self.handler = Some(handler); } } impl Handler for Middleware { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { // First, attempt to serve a static file. If we're missing a static // file, then keep going. match self.dist.call(req) { Ok(ref resp) if resp.status.0 == 404 => {} ret => return ret, } // Second, if we're requesting html, then we've only got one page so // serve up that page. Otherwise proxy on to the rest of the app. let wants_html = req.headers().find("Accept").map(|accept| { accept.iter().any(|s| s.contains("html")) }).unwrap_or(true); // If no Accept header is specified, serve up html. if wants_html { self.dist.call(&mut RequestProxy { other: req, path: Some("/index.html"), method: None, }) } else { self.handler.as_ref().unwrap().call(req) } } }
use std::error::Error; use conduit::{Request, Response, Handler}; use conduit_static::Static; use conduit_middleware::AroundMiddleware; use util::RequestProxy; pub struct Middleware { handler: Option<Box<Handler>>, dist: Static, } impl Middleware { pub fn new() -> Middleware { Middleware { handler: None, dist: Static::new("dist"), } } } impl AroundMiddleware for Middleware { fn with_handler(&mut self, handler: Box<Handler>) { self.handler = Some(handler); } } impl Handler for Middleware { fn call(&self, req: &mut Request) -> Result<Response, Box<Error+Send>> { // First, attempt to serve a static file. If we're missing a static // file, then keep going. match self.dist.call(req) { Ok(ref resp) if resp.status.0 == 404 => {} ret => return ret, } // Second, if we're requesting html, then we've only got one page so // serve up that page. Otherwise proxy on to the rest of the app. let wants_html = req.headers().find("Accept").map(|accept| { accept.iter().any(|s| s.contains("html")) }).unwrap_or(false); if wants_html { self.dist.call(&mut RequestProxy { other: req, path: Some("/index.html"), method: None, }) } else { self.handler.as_ref().unwrap().call(req) } } }
1
1
1
mixed
--- a/src/dist.rs +++ b/src/dist.rs @@ -41,3 +41,3 @@ accept.iter().any(|s| s.contains("html")) - }).unwrap_or(true); // If no Accept header is specified, serve up html. + }).unwrap_or(false); if wants_html {
--- a/src/dist.rs +++ b/src/dist.rs @@ ... @@ accept.iter().any(|s| s.contains("html")) - }).unwrap_or(true); // If no Accept header is specified, serve up html. + }).unwrap_or(false); if wants_html {
--- a/src/dist.rs +++ b/src/dist.rs @@ -41,3 +41,3 @@ CON accept.iter().any(|s| s.contains("html")) DEL }).unwrap_or(true); // If no Accept header is specified, serve up html. ADD }).unwrap_or(false); CON if wants_html {
<<<<<<< SEARCH let wants_html = req.headers().find("Accept").map(|accept| { accept.iter().any(|s| s.contains("html")) }).unwrap_or(true); // If no Accept header is specified, serve up html. if wants_html { self.dist.call(&mut RequestProxy { ======= let wants_html = req.headers().find("Accept").map(|accept| { accept.iter().any(|s| s.contains("html")) }).unwrap_or(false); if wants_html { self.dist.call(&mut RequestProxy { >>>>>>> REPLACE
suutari-ai/django-enumfields
5c3900e12216164712c9e7fe7ea064e70fae8d1b
enumfields/enums.py
python
mit
Fix 'Labels' class in Python 3. In Python 3, the attrs dict will already be an _EnumDict, which has a separate list of member names (in Python 2, it is still a plain dict at this point).
import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not None and inspect.isclass(Labels): del attrs['Labels'] obj = BaseEnumMeta.__new__(cls, name, bases, attrs) for m in obj: try: m.label = getattr(Labels, m.name) except AttributeError: m.label = m.name.replace('_', ' ').title() return obj @python_2_unicode_compatible class Enum(six.with_metaclass(EnumMeta, BaseEnum)): @classmethod def choices(cls): """ Returns a list formatted for use as field choices. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices) """ return tuple((m.value, m.label) for m in cls) def __str__(self): """ Show our label when Django uses the Enum for displaying in a view """ return force_bytes(self.label)
import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not None and inspect.isclass(Labels): del attrs['Labels'] if hasattr(attrs, '_member_names'): attrs._member_names.remove('Labels') obj = BaseEnumMeta.__new__(cls, name, bases, attrs) for m in obj: try: m.label = getattr(Labels, m.name) except AttributeError: m.label = m.name.replace('_', ' ').title() return obj @python_2_unicode_compatible class Enum(six.with_metaclass(EnumMeta, BaseEnum)): @classmethod def choices(cls): """ Returns a list formatted for use as field choices. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices) """ return tuple((m.value, m.label) for m in cls) def __str__(self): """ Show our label when Django uses the Enum for displaying in a view """ return force_bytes(self.label)
2
0
1
add_only
--- a/enumfields/enums.py +++ b/enumfields/enums.py @@ -12,2 +12,4 @@ del attrs['Labels'] + if hasattr(attrs, '_member_names'): + attrs._member_names.remove('Labels')
--- a/enumfields/enums.py +++ b/enumfields/enums.py @@ ... @@ del attrs['Labels'] + if hasattr(attrs, '_member_names'): + attrs._member_names.remove('Labels')
--- a/enumfields/enums.py +++ b/enumfields/enums.py @@ -12,2 +12,4 @@ CON del attrs['Labels'] ADD if hasattr(attrs, '_member_names'): ADD attrs._member_names.remove('Labels') CON
<<<<<<< SEARCH if Labels is not None and inspect.isclass(Labels): del attrs['Labels'] obj = BaseEnumMeta.__new__(cls, name, bases, attrs) ======= if Labels is not None and inspect.isclass(Labels): del attrs['Labels'] if hasattr(attrs, '_member_names'): attrs._member_names.remove('Labels') obj = BaseEnumMeta.__new__(cls, name, bases, attrs) >>>>>>> REPLACE
millerdev/django-nose
e01697c5d5e5e45a0dd20870c71bb17399991ca1
setup.py
python
bsd-3-clause
Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='[email protected]', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], entry_points=""" [nose.plugins.0.10] fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='[email protected]', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], # This blows up tox runs that install django-nose into a virtualenv, # because it causes Nose to import django_nose.runner before the Django # settings are initialized, leading to a mess of errors. There's no reason # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you # need to be using django-nose to find the it useful, and django-nose knows # about it intrinsically. #entry_points=""" # [nose.plugins.0.10] # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin # """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
10
4
1
mixed
--- a/setup.py +++ b/setup.py @@ -19,6 +19,12 @@ tests_require=['Django', 'south'], - entry_points=""" - [nose.plugins.0.10] - fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin - """, + # This blows up tox runs that install django-nose into a virtualenv, + # because it causes Nose to import django_nose.runner before the Django + # settings are initialized, leading to a mess of errors. There's no reason + # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you + # need to be using django-nose to find the it useful, and django-nose knows + # about it intrinsically. + #entry_points=""" + # [nose.plugins.0.10] + # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin + # """, classifiers=[
--- a/setup.py +++ b/setup.py @@ ... @@ tests_require=['Django', 'south'], - entry_points=""" - [nose.plugins.0.10] - fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin - """, + # This blows up tox runs that install django-nose into a virtualenv, + # because it causes Nose to import django_nose.runner before the Django + # settings are initialized, leading to a mess of errors. There's no reason + # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you + # need to be using django-nose to find the it useful, and django-nose knows + # about it intrinsically. + #entry_points=""" + # [nose.plugins.0.10] + # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin + # """, classifiers=[
--- a/setup.py +++ b/setup.py @@ -19,6 +19,12 @@ CON tests_require=['Django', 'south'], DEL entry_points=""" DEL [nose.plugins.0.10] DEL fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin DEL """, ADD # This blows up tox runs that install django-nose into a virtualenv, ADD # because it causes Nose to import django_nose.runner before the Django ADD # settings are initialized, leading to a mess of errors. There's no reason ADD # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you ADD # need to be using django-nose to find the it useful, and django-nose knows ADD # about it intrinsically. ADD #entry_points=""" ADD # [nose.plugins.0.10] ADD # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin ADD # """, CON classifiers=[
<<<<<<< SEARCH install_requires=['nose'], tests_require=['Django', 'south'], entry_points=""" [nose.plugins.0.10] fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin """, classifiers=[ 'Development Status :: 4 - Beta', ======= install_requires=['nose'], tests_require=['Django', 'south'], # This blows up tox runs that install django-nose into a virtualenv, # because it causes Nose to import django_nose.runner before the Django # settings are initialized, leading to a mess of errors. There's no reason # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you # need to be using django-nose to find the it useful, and django-nose knows # about it intrinsically. #entry_points=""" # [nose.plugins.0.10] # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin # """, classifiers=[ 'Development Status :: 4 - Beta', >>>>>>> REPLACE
Musician101/ServerSaturday
cd7e4b63ebbb2c14d27d9bcdeb3d6388dff58522
serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java
java
mit
Fix an issue with updating builds.
package com.campmongoose.serversaturday.common.submission; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class AbstractSubmitter<B extends AbstractBuild, I, L> { protected final Map<String, B> builds = new HashMap<>(); @Nonnull protected final String name; @Nonnull protected final UUID uuid; protected AbstractSubmitter(@Nonnull String name, @Nonnull UUID uuid) { this.name = name; this.uuid = uuid; } @Nullable public B getBuild(@Nonnull String name) { return builds.get(name); } @Nonnull public List<B> getBuilds() { return new ArrayList<>(builds.values()); } @Nonnull public abstract I getMenuRepresentation(); @Nonnull public String getName() { return name; } @Nonnull public UUID getUUID() { return uuid; } @Nonnull public abstract B newBuild(@Nonnull String name, @Nonnull L location); public boolean removeBuild(@Nonnull String name) { return builds.remove(name) != null; } public abstract void save(@Nonnull File file); }
package com.campmongoose.serversaturday.common.submission; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class AbstractSubmitter<B extends AbstractBuild, I, L> { protected final Map<String, B> builds = new HashMap<>(); @Nonnull protected final String name; @Nonnull protected final UUID uuid; protected AbstractSubmitter(@Nonnull String name, @Nonnull UUID uuid) { this.name = name; this.uuid = uuid; } @Nullable public B getBuild(@Nonnull String name) { return builds.get(name); } @Nonnull public List<B> getBuilds() { return new ArrayList<>(builds.values()); } @Nonnull public abstract I getMenuRepresentation(); @Nonnull public String getName() { return name; } @Nonnull public UUID getUUID() { return uuid; } @Nonnull public abstract B newBuild(@Nonnull String name, @Nonnull L location); public boolean removeBuild(@Nonnull String name) { return builds.remove(name) != null; } public void renameBuild(String newName, B build) { builds.remove(build.getName()); build.setName(newName); builds.put(newName, build); } public abstract void save(@Nonnull File file); }
6
0
1
add_only
--- a/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java +++ b/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java @@ -54,2 +54,8 @@ + public void renameBuild(String newName, B build) { + builds.remove(build.getName()); + build.setName(newName); + builds.put(newName, build); + } + public abstract void save(@Nonnull File file);
--- a/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java +++ b/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java @@ ... @@ + public void renameBuild(String newName, B build) { + builds.remove(build.getName()); + build.setName(newName); + builds.put(newName, build); + } + public abstract void save(@Nonnull File file);
--- a/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java +++ b/serversaturday-common/src/main/java/com/campmongoose/serversaturday/common/submission/AbstractSubmitter.java @@ -54,2 +54,8 @@ CON ADD public void renameBuild(String newName, B build) { ADD builds.remove(build.getName()); ADD build.setName(newName); ADD builds.put(newName, build); ADD } ADD CON public abstract void save(@Nonnull File file);
<<<<<<< SEARCH } public abstract void save(@Nonnull File file); } ======= } public void renameBuild(String newName, B build) { builds.remove(build.getName()); build.setName(newName); builds.put(newName, build); } public abstract void save(@Nonnull File file); } >>>>>>> REPLACE
ericvaladas/formwood
68dd29d7c91eb2d01cfb0518adb7091a7fa8d3d2
src/js/forms/components/field.js
javascript
mit
Add case for select-multiple inputs
import React from 'react'; import classNames from 'classnames'; export default function(WrappedComponent) { const Field = React.createClass({ getInitialState() { return { value: "", message: "", valid: true }; }, componentDidMount() { this.validators = this.validators || []; let validators = this.props.validators; if (validators && validators.constructor === Array) { this.validators = this.validators.concat(validators); } }, validate() { for (let validator of this.validators) { let result = validator(this.state.value); if (result !== true) { this.setState({valid: false, message: result}); return false; } } this.setState({valid: true, message: ""}); return true; }, handleChange(event) { return new Promise((resolve) => { switch (event.target.type) { case "checkbox": this.setState({value: event.target.checked}, resolve); break; default: this.setState({value: event.target.value}, resolve); break; } }); }, render() { return ( <WrappedComponent handleChange={this.handleChange} message={this.state.message} validate={this.validate}/> ); } }); return Field; }
import React from 'react'; export default function(WrappedComponent) { const Field = React.createClass({ getInitialState() { return { value: "", message: "", valid: true }; }, componentDidMount() { this.validators = this.validators || []; let validators = this.props.validators; if (validators && validators.constructor === Array) { this.validators = this.validators.concat(validators); } }, validate() { for (let validator of this.validators) { let result = validator(this.state.value); if (result !== true) { this.setState({valid: false, message: result}); return false; } } this.setState({valid: true, message: ""}); return true; }, handleChange(event) { return new Promise((resolve) => { switch (event.target.type) { case "checkbox": this.setState({value: event.target.checked}, resolve); break; case "select-multiple": this.setState({ value: Array.from(event.target.selectedOptions).map((option) => { return option.value; }) }, resolve); break; default: this.setState({value: event.target.value}, resolve); break; } }); }, render() { return ( <WrappedComponent handleChange={this.handleChange} message={this.state.message} validate={this.validate}/> ); } }); return Field; }
7
1
2
mixed
--- a/src/js/forms/components/field.js +++ b/src/js/forms/components/field.js @@ -1,3 +1,2 @@ import React from 'react'; -import classNames from 'classnames'; @@ -39,2 +38,9 @@ this.setState({value: event.target.checked}, resolve); break; + case "select-multiple": + this.setState({ + value: Array.from(event.target.selectedOptions).map((option) => { + return option.value; + }) + }, resolve); + break; default:
--- a/src/js/forms/components/field.js +++ b/src/js/forms/components/field.js @@ ... @@ import React from 'react'; -import classNames from 'classnames'; @@ ... @@ this.setState({value: event.target.checked}, resolve); break; + case "select-multiple": + this.setState({ + value: Array.from(event.target.selectedOptions).map((option) => { + return option.value; + }) + }, resolve); + break; default:
--- a/src/js/forms/components/field.js +++ b/src/js/forms/components/field.js @@ -1,3 +1,2 @@ CON import React from 'react'; DEL import classNames from 'classnames'; CON @@ -39,2 +38,9 @@ CON this.setState({value: event.target.checked}, resolve); break; ADD case "select-multiple": ADD this.setState({ ADD value: Array.from(event.target.selectedOptions).map((option) => { ADD return option.value; ADD }) ADD }, resolve); ADD break; CON default:
<<<<<<< SEARCH import React from 'react'; import classNames from 'classnames'; ======= import React from 'react'; >>>>>>> REPLACE
gradle/gradle
514533f6bc7f062b30f54fe80e3ec10b699a1486
subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts
kotlin
apache-2.0
Fix broken Kotlin sample test.
// tag::apply[] // tag::publish[] plugins { `kotlin-dsl` // end::apply[] `maven-publish` // tag::apply[] } // end::apply[] group = "com.myorg.conventions" version = "1.0" publishing { repositories { maven { // change to point to your repo, e.g. http://my.org/repo url = uri(layout.buildDirectory.dir("repo")) } } } tasks.publish { dependsOn("check") } // end::publish[] testing { suites { test { useJUnit() } } } // tag::repositories-and-dependencies[] repositories { gradlePluginPortal() // so that external plugins can be resolved in dependencies section } dependencies { implementation("gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:4.7.2") } // end::repositories-and-dependencies[]
// tag::apply[] // tag::publish[] plugins { `kotlin-dsl` // end::apply[] `maven-publish` // tag::apply[] } // end::apply[] group = "com.myorg.conventions" version = "1.0" publishing { repositories { maven { // change to point to your repo, e.g. http://my.org/repo url = uri(layout.buildDirectory.dir("repo")) } } } tasks.publish { dependsOn("check") } // end::publish[] testing { suites { val test by getting(JvmTestSuite::class) { useJUnit() } } } // tag::repositories-and-dependencies[] repositories { gradlePluginPortal() // so that external plugins can be resolved in dependencies section } dependencies { implementation("gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:4.7.2") } // end::repositories-and-dependencies[]
1
1
1
mixed
--- a/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts +++ b/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts @@ -30,3 +30,3 @@ suites { - test { + val test by getting(JvmTestSuite::class) { useJUnit()
--- a/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts +++ b/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts @@ ... @@ suites { - test { + val test by getting(JvmTestSuite::class) { useJUnit()
--- a/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts +++ b/subprojects/docs/src/samples/incubating/build-organization/publishing-convention-plugins/kotlin/convention-plugins/build.gradle.kts @@ -30,3 +30,3 @@ CON suites { DEL test { ADD val test by getting(JvmTestSuite::class) { CON useJUnit()
<<<<<<< SEARCH testing { suites { test { useJUnit() } ======= testing { suites { val test by getting(JvmTestSuite::class) { useJUnit() } >>>>>>> REPLACE
dubrowgn/tcalc
2f8d78dc78e2bd0eee456541d4e57e3f7bd23c6b
src/main.rs
rust
mit
Add support for passing equations via args $ tcalc 1+1 2
use std::env; use std::io; use std::io::Write; #[macro_use] mod macros; mod buffered_iterator; mod ast; mod scanning; mod parsing; mod running; use ast::*; fn main() { for arg in env::args() { println!("{}", arg); } loop { let mut line = String::new(); print!("> "); io::stdout().flush().expect("Could not flush stdout"); match io::stdin().read_line(&mut line) { Ok(_) => { match parsing::parse(&line) { Some(Ast::Command(Command::Exit)) => break, Some(Ast::Expression(expr)) => { match expr.run() { Ok(v) => println!(" {}", v), Err(msg) => println!("{}", msg), } }, None => {} } } Err(msg) => println!("error: {}", msg), } } // loop } // main
use std::env; use std::io; use std::io::Write; #[macro_use] mod macros; mod buffered_iterator; mod ast; mod scanning; mod parsing; mod running; use ast::*; fn parse_args() { for arg in env::args().skip(1) { match parsing::parse(&arg) { Some(Ast::Expression(expr)) => { match expr.run() { Ok(v) => println!("{}", v), Err(msg) => println!("{}", msg), } }, _ => {} } // match } // for (arg) } // parse_args fn repl() { loop { let mut line = String::new(); print!("> "); io::stdout().flush().expect("Could not flush stdout"); match io::stdin().read_line(&mut line) { Ok(_) => { match parsing::parse(&line) { Some(Ast::Command(Command::Exit)) => break, Some(Ast::Expression(expr)) => { match expr.run() { Ok(v) => println!(" {}", v), Err(msg) => println!("{}", msg), } }, None => {} } } Err(msg) => println!("error: {}", msg), } } // loop } // repl fn main() { if env::args().len() > 1 { return parse_args(); } repl(); } // main
22
4
2
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,17 @@ -fn main() { - for arg in env::args() { - println!("{}", arg); - } +fn parse_args() { + for arg in env::args().skip(1) { + match parsing::parse(&arg) { + Some(Ast::Expression(expr)) => { + match expr.run() { + Ok(v) => println!("{}", v), + Err(msg) => println!("{}", msg), + } + }, + _ => {} + } // match + } // for (arg) +} // parse_args +fn repl() { loop { @@ -42,2 +52,10 @@ } // loop +} // repl + +fn main() { + if env::args().len() > 1 { + return parse_args(); + } + + repl(); } // main
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ -fn main() { - for arg in env::args() { - println!("{}", arg); - } +fn parse_args() { + for arg in env::args().skip(1) { + match parsing::parse(&arg) { + Some(Ast::Expression(expr)) => { + match expr.run() { + Ok(v) => println!("{}", v), + Err(msg) => println!("{}", msg), + } + }, + _ => {} + } // match + } // for (arg) +} // parse_args +fn repl() { loop { @@ ... @@ } // loop +} // repl + +fn main() { + if env::args().len() > 1 { + return parse_args(); + } + + repl(); } // main
--- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,17 @@ CON DEL fn main() { DEL for arg in env::args() { DEL println!("{}", arg); DEL } ADD fn parse_args() { ADD for arg in env::args().skip(1) { ADD match parsing::parse(&arg) { ADD Some(Ast::Expression(expr)) => { ADD match expr.run() { ADD Ok(v) => println!("{}", v), ADD Err(msg) => println!("{}", msg), ADD } ADD }, ADD _ => {} ADD } // match ADD } // for (arg) ADD } // parse_args CON ADD fn repl() { CON loop { @@ -42,2 +52,10 @@ CON } // loop ADD } // repl ADD ADD fn main() { ADD if env::args().len() > 1 { ADD return parse_args(); ADD } ADD ADD repl(); CON } // main
<<<<<<< SEARCH use ast::*; fn main() { for arg in env::args() { println!("{}", arg); } loop { let mut line = String::new(); ======= use ast::*; fn parse_args() { for arg in env::args().skip(1) { match parsing::parse(&arg) { Some(Ast::Expression(expr)) => { match expr.run() { Ok(v) => println!("{}", v), Err(msg) => println!("{}", msg), } }, _ => {} } // match } // for (arg) } // parse_args fn repl() { loop { let mut line = String::new(); >>>>>>> REPLACE
SpineEventEngine/core-java
3a2efe8677580387b26bead8907370d4c44c6c89
core/src/main/java/io/spine/core/ResponseMixin.java
java
apache-2.0
Add shortcut method for obtaining the error
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.core; /** * Mixin interface for the {@link Response} objects. */ public interface ResponseMixin extends ResponseOrBuilder { /** * Verifies if this response has the {@link Status.StatusCase#OK OK} status. */ default boolean isOk() { return getStatus().getStatusCase() == Status.StatusCase.OK; } /** * Verifies if this response has the {@link Status.StatusCase#ERROR ERROR} status. */ default boolean isError() { return getStatus().getStatusCase() == Status.StatusCase.ERROR; } }
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.core; import io.spine.base.Error; /** * Mixin interface for the {@link Response} objects. */ public interface ResponseMixin extends ResponseOrBuilder { /** * Verifies if this response has the {@link Status.StatusCase#OK OK} status. */ default boolean isOk() { return getStatus().getStatusCase() == Status.StatusCase.OK; } /** * Verifies if this response has the {@link Status.StatusCase#ERROR ERROR} status. */ default boolean isError() { return getStatus().getStatusCase() == Status.StatusCase.ERROR; } /** * Obtains the error associated with the response or default instance is the response is not * an error. */ default Error error() { return getStatus().getError(); } }
10
0
2
add_only
--- a/core/src/main/java/io/spine/core/ResponseMixin.java +++ b/core/src/main/java/io/spine/core/ResponseMixin.java @@ -22,2 +22,4 @@ +import io.spine.base.Error; + /** @@ -40,2 +42,10 @@ } + + /** + * Obtains the error associated with the response or default instance is the response is not + * an error. + */ + default Error error() { + return getStatus().getError(); + } }
--- a/core/src/main/java/io/spine/core/ResponseMixin.java +++ b/core/src/main/java/io/spine/core/ResponseMixin.java @@ ... @@ +import io.spine.base.Error; + /** @@ ... @@ } + + /** + * Obtains the error associated with the response or default instance is the response is not + * an error. + */ + default Error error() { + return getStatus().getError(); + } }
--- a/core/src/main/java/io/spine/core/ResponseMixin.java +++ b/core/src/main/java/io/spine/core/ResponseMixin.java @@ -22,2 +22,4 @@ CON ADD import io.spine.base.Error; ADD CON /** @@ -40,2 +42,10 @@ CON } ADD ADD /** ADD * Obtains the error associated with the response or default instance is the response is not ADD * an error. ADD */ ADD default Error error() { ADD return getStatus().getError(); ADD } CON }
<<<<<<< SEARCH package io.spine.core; /** * Mixin interface for the {@link Response} objects. ======= package io.spine.core; import io.spine.base.Error; /** * Mixin interface for the {@link Response} objects. >>>>>>> REPLACE
rorasa/RPiClockArray
ea1c62ae3f13d47ee820eae31a2e284e3d66b6ab
libPiLite.py
python
mit
Add setGrid and resetGrid functions
#!/usr/bin/env python def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] rowstr = '' for j in row: rowstr += str(j)+' ' print(rowstr) def serializeGrid(grid): numRow = len(grid) numCol = len(grid[0]) gridstr = '' for j in range(0,numCol): for i in range(0,numRow): gridstr += str(grid[i][j]) return gridstr
#!/usr/bin/env python def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] rowstr = '' for j in row: rowstr += str(j)+' ' print(rowstr) def serializeGrid(grid): numRow = len(grid) numCol = len(grid[0]) gridstr = '' for j in range(0,numCol): for i in range(0,numRow): gridstr += str(grid[i][j]) return gridstr def setGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 return grid def resetGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 return grid
10
1
1
mixed
--- a/libPiLite.py +++ b/libPiLite.py @@ -30,2 +30,11 @@ return gridstr - + +def setGrid(grid, setlist, rowoffset, coloffset): + for entry in setlist: + grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 + return grid + +def resetGrid(grid, setlist, rowoffset, coloffset): + for entry in setlist: + grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 + return grid
--- a/libPiLite.py +++ b/libPiLite.py @@ ... @@ return gridstr - + +def setGrid(grid, setlist, rowoffset, coloffset): + for entry in setlist: + grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 + return grid + +def resetGrid(grid, setlist, rowoffset, coloffset): + for entry in setlist: + grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 + return grid
--- a/libPiLite.py +++ b/libPiLite.py @@ -30,2 +30,11 @@ CON return gridstr DEL ADD ADD def setGrid(grid, setlist, rowoffset, coloffset): ADD for entry in setlist: ADD grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 ADD return grid ADD ADD def resetGrid(grid, setlist, rowoffset, coloffset): ADD for entry in setlist: ADD grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 ADD return grid
<<<<<<< SEARCH gridstr += str(grid[i][j]) return gridstr ======= gridstr += str(grid[i][j]) return gridstr def setGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 1 return grid def resetGrid(grid, setlist, rowoffset, coloffset): for entry in setlist: grid[entry[0]+rowoffset][entry[1]+coloffset] = 0 return grid >>>>>>> REPLACE
BAJ-/robot-breakout
7a150953a835e22a22a0aaf332b1673d5a61c3cf
js/RobotCore.js
javascript
mit
Fix call to incorrect function name
/* * Game core for Robots Order BreakOut Trepidation! * * @canvas = reference to an HTML5 canvas element. */ 'use strict'; import Actors from 'Actors.js'; import Collision from 'Collision.js'; export default class { constructor(canvas) { // Player settings. this._score = 0; this._lives = 3; // Game settings. this._running = false; this._canvas = canvas; this._ctx = this._canvas.getContext("2d"); this._actors = new Actors(this._canvas.width, this._canvas.height); this._collision = new Collision(); } _clearScene() { this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); // TODO: Draw background. } _drawScene() { this.clearScene(); // TODO: Draw scene. if (this._running) { requestAnimationFrame(()=> this.drawScene()); } } _startGameLoop() { requestAnimationFrame(()=> this.drawScene()); } // This is kinda out of place here, but haven't found a better // place for it yet. movePaddle(direction) { // TODO: Implement paddle movement. } start() { this._startGameLoop(); } pause() { // TODO: Implement some kind of pause. } stop() { this._running = false; } }
/* * Game core for Robots Order BreakOut Trepidation! * * @canvas = reference to an HTML5 canvas element. */ 'use strict'; import Actors from 'Actors.js'; import Collision from 'Collision.js'; export default class { constructor(canvas) { // Player settings. this._score = 0; this._lives = 3; // Game settings. this._running = false; this._canvas = canvas; this._ctx = this._canvas.getContext("2d"); this._actors = new Actors(this._canvas.width, this._canvas.height); this._collision = new Collision(); } _clearScene() { this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); // TODO: Draw background. } _drawScene() { this._clearScene(); // TODO: Draw scene. if (this._running) { requestAnimationFrame(()=> this._drawScene()); } } _startGameLoop() { requestAnimationFrame(()=> this._drawScene()); } // This is kinda out of place here, but haven't found a better // place for it yet. movePaddle(direction) { // TODO: Implement paddle movement. } start() { this._startGameLoop(); } pause() { // TODO: Implement some kind of pause. } stop() { this._running = false; } }
3
3
3
mixed
--- a/js/RobotCore.js +++ b/js/RobotCore.js @@ -33,3 +33,3 @@ _drawScene() { - this.clearScene(); + this._clearScene(); // TODO: Draw scene. @@ -37,3 +37,3 @@ if (this._running) { - requestAnimationFrame(()=> this.drawScene()); + requestAnimationFrame(()=> this._drawScene()); } @@ -42,3 +42,3 @@ _startGameLoop() { - requestAnimationFrame(()=> this.drawScene()); + requestAnimationFrame(()=> this._drawScene()); }
--- a/js/RobotCore.js +++ b/js/RobotCore.js @@ ... @@ _drawScene() { - this.clearScene(); + this._clearScene(); // TODO: Draw scene. @@ ... @@ if (this._running) { - requestAnimationFrame(()=> this.drawScene()); + requestAnimationFrame(()=> this._drawScene()); } @@ ... @@ _startGameLoop() { - requestAnimationFrame(()=> this.drawScene()); + requestAnimationFrame(()=> this._drawScene()); }
--- a/js/RobotCore.js +++ b/js/RobotCore.js @@ -33,3 +33,3 @@ CON _drawScene() { DEL this.clearScene(); ADD this._clearScene(); CON // TODO: Draw scene. @@ -37,3 +37,3 @@ CON if (this._running) { DEL requestAnimationFrame(()=> this.drawScene()); ADD requestAnimationFrame(()=> this._drawScene()); CON } @@ -42,3 +42,3 @@ CON _startGameLoop() { DEL requestAnimationFrame(()=> this.drawScene()); ADD requestAnimationFrame(()=> this._drawScene()); CON }
<<<<<<< SEARCH _drawScene() { this.clearScene(); // TODO: Draw scene. if (this._running) { requestAnimationFrame(()=> this.drawScene()); } } _startGameLoop() { requestAnimationFrame(()=> this.drawScene()); } ======= _drawScene() { this._clearScene(); // TODO: Draw scene. if (this._running) { requestAnimationFrame(()=> this._drawScene()); } } _startGameLoop() { requestAnimationFrame(()=> this._drawScene()); } >>>>>>> REPLACE
fredyw/leetcode
2769a6b4faf0d9663297bcb2c2cc2ce2982bda65
src/main/java/leetcode/Problem63.java
java
mit
Update problem 63 (too slow)
package leetcode; /** * https://leetcode.com/problems/unique-paths-ii/ */ public class Problem63 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { // TODO: implement this return 0; } public static void main(String[] args) { Problem63 prob = new Problem63(); int[][] grid = new int[][]{ new int[]{0, 0, 0}, new int[]{0, 1, 0}, new int[]{0, 0, 0} }; System.out.println(prob.uniquePathsWithObstacles(grid)); } }
package leetcode; /** * https://leetcode.com/problems/unique-paths-ii/ */ public class Problem63 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid.length == 0) { return 0; } return findPaths(obstacleGrid, obstacleGrid.length-1, obstacleGrid[0].length-1, 0, 0); } private int findPaths(int[][] grid, int destRow, int destCol, int row, int col) { if (row == destRow && col == destCol) { return 1; } if (row > destRow || col > destCol) { return 0; } if (grid[row][col] == 1) { return 0; } int a = findPaths(grid, destRow, destCol, row+1, col); int b = findPaths(grid, destRow, destCol, row, col+1); return a + b; } public static void main(String[] args) { Problem63 prob = new Problem63(); int[][] grid = new int[][]{ new int[]{0, 0, 0}, new int[]{0, 1, 0}, new int[]{0, 0, 0}, new int[]{0, 0, 0}, new int[]{0, 0, 0}, }; System.out.println(prob.uniquePathsWithObstacles(grid)); } }
23
3
2
mixed
--- a/src/main/java/leetcode/Problem63.java +++ b/src/main/java/leetcode/Problem63.java @@ -7,4 +7,22 @@ public int uniquePathsWithObstacles(int[][] obstacleGrid) { - // TODO: implement this - return 0; + if (obstacleGrid.length == 0) { + return 0; + } + return findPaths(obstacleGrid, obstacleGrid.length-1, obstacleGrid[0].length-1, + 0, 0); + } + + private int findPaths(int[][] grid, int destRow, int destCol, int row, int col) { + if (row == destRow && col == destCol) { + return 1; + } + if (row > destRow || col > destCol) { + return 0; + } + if (grid[row][col] == 1) { + return 0; + } + int a = findPaths(grid, destRow, destCol, row+1, col); + int b = findPaths(grid, destRow, destCol, row, col+1); + return a + b; } @@ -16,3 +34,5 @@ new int[]{0, 1, 0}, - new int[]{0, 0, 0} + new int[]{0, 0, 0}, + new int[]{0, 0, 0}, + new int[]{0, 0, 0}, };
--- a/src/main/java/leetcode/Problem63.java +++ b/src/main/java/leetcode/Problem63.java @@ ... @@ public int uniquePathsWithObstacles(int[][] obstacleGrid) { - // TODO: implement this - return 0; + if (obstacleGrid.length == 0) { + return 0; + } + return findPaths(obstacleGrid, obstacleGrid.length-1, obstacleGrid[0].length-1, + 0, 0); + } + + private int findPaths(int[][] grid, int destRow, int destCol, int row, int col) { + if (row == destRow && col == destCol) { + return 1; + } + if (row > destRow || col > destCol) { + return 0; + } + if (grid[row][col] == 1) { + return 0; + } + int a = findPaths(grid, destRow, destCol, row+1, col); + int b = findPaths(grid, destRow, destCol, row, col+1); + return a + b; } @@ ... @@ new int[]{0, 1, 0}, - new int[]{0, 0, 0} + new int[]{0, 0, 0}, + new int[]{0, 0, 0}, + new int[]{0, 0, 0}, };
--- a/src/main/java/leetcode/Problem63.java +++ b/src/main/java/leetcode/Problem63.java @@ -7,4 +7,22 @@ CON public int uniquePathsWithObstacles(int[][] obstacleGrid) { DEL // TODO: implement this DEL return 0; ADD if (obstacleGrid.length == 0) { ADD return 0; ADD } ADD return findPaths(obstacleGrid, obstacleGrid.length-1, obstacleGrid[0].length-1, ADD 0, 0); ADD } ADD ADD private int findPaths(int[][] grid, int destRow, int destCol, int row, int col) { ADD if (row == destRow && col == destCol) { ADD return 1; ADD } ADD if (row > destRow || col > destCol) { ADD return 0; ADD } ADD if (grid[row][col] == 1) { ADD return 0; ADD } ADD int a = findPaths(grid, destRow, destCol, row+1, col); ADD int b = findPaths(grid, destRow, destCol, row, col+1); ADD return a + b; CON } @@ -16,3 +34,5 @@ CON new int[]{0, 1, 0}, DEL new int[]{0, 0, 0} ADD new int[]{0, 0, 0}, ADD new int[]{0, 0, 0}, ADD new int[]{0, 0, 0}, CON };
<<<<<<< SEARCH public class Problem63 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { // TODO: implement this return 0; } ======= public class Problem63 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid.length == 0) { return 0; } return findPaths(obstacleGrid, obstacleGrid.length-1, obstacleGrid[0].length-1, 0, 0); } private int findPaths(int[][] grid, int destRow, int destCol, int row, int col) { if (row == destRow && col == destCol) { return 1; } if (row > destRow || col > destCol) { return 0; } if (grid[row][col] == 1) { return 0; } int a = findPaths(grid, destRow, destCol, row+1, col); int b = findPaths(grid, destRow, destCol, row, col+1); return a + b; } >>>>>>> REPLACE
l1048576/fbx_direct
3d0fc3decc6e46be75870bbfd6b56393d6db016c
src/error.rs
rust
apache-2.0
Implement conversion from `byteorder::Error` to `ErrorKind`
use std::io; use std::string; pub type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] pub struct Error { pos: u64, kind: ErrorKind, } impl Error { pub fn new<K: Into<ErrorKind>>(pos: u64, kind: K) -> Self { Error { pos: pos, kind: kind.into(), } } } #[derive(Debug)] pub enum ErrorKind { FromUtf8Error(string::FromUtf8Error), InvalidMagic, Io(io::Error), UnexpectedEof, Unimplemented(String), } impl From<string::FromUtf8Error> for ErrorKind { fn from(err: string::FromUtf8Error) -> ErrorKind { ErrorKind::FromUtf8Error(err) } } impl From<io::Error> for ErrorKind { fn from(err: io::Error) -> ErrorKind { ErrorKind::Io(err) } }
extern crate byteorder; use std::io; use std::string; pub type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] pub struct Error { pos: u64, kind: ErrorKind, } impl Error { pub fn new<K: Into<ErrorKind>>(pos: u64, kind: K) -> Self { Error { pos: pos, kind: kind.into(), } } } #[derive(Debug)] pub enum ErrorKind { FromUtf8Error(string::FromUtf8Error), InvalidMagic, Io(io::Error), UnexpectedEof, Unimplemented(String), } impl From<string::FromUtf8Error> for ErrorKind { fn from(err: string::FromUtf8Error) -> ErrorKind { ErrorKind::FromUtf8Error(err) } } impl From<io::Error> for ErrorKind { fn from(err: io::Error) -> ErrorKind { ErrorKind::Io(err) } } impl From<byteorder::Error> for ErrorKind { fn from(err: byteorder::Error) -> ErrorKind { match err { byteorder::Error::UnexpectedEOF => ErrorKind::UnexpectedEof, byteorder::Error::Io(err) => ErrorKind::Io(err), } } }
11
0
2
add_only
--- a/src/error.rs +++ b/src/error.rs @@ -1 +1,3 @@ +extern crate byteorder; + use std::io; @@ -40 +42,10 @@ } + +impl From<byteorder::Error> for ErrorKind { + fn from(err: byteorder::Error) -> ErrorKind { + match err { + byteorder::Error::UnexpectedEOF => ErrorKind::UnexpectedEof, + byteorder::Error::Io(err) => ErrorKind::Io(err), + } + } +}
--- a/src/error.rs +++ b/src/error.rs @@ ... @@ +extern crate byteorder; + use std::io; @@ ... @@ } + +impl From<byteorder::Error> for ErrorKind { + fn from(err: byteorder::Error) -> ErrorKind { + match err { + byteorder::Error::UnexpectedEOF => ErrorKind::UnexpectedEof, + byteorder::Error::Io(err) => ErrorKind::Io(err), + } + } +}
--- a/src/error.rs +++ b/src/error.rs @@ -1 +1,3 @@ ADD extern crate byteorder; ADD CON use std::io; @@ -40 +42,10 @@ CON } ADD ADD impl From<byteorder::Error> for ErrorKind { ADD fn from(err: byteorder::Error) -> ErrorKind { ADD match err { ADD byteorder::Error::UnexpectedEOF => ErrorKind::UnexpectedEof, ADD byteorder::Error::Io(err) => ErrorKind::Io(err), ADD } ADD } ADD }
<<<<<<< SEARCH use std::io; use std::string; ======= extern crate byteorder; use std::io; use std::string; >>>>>>> REPLACE
yinhe402/spring-security
acf4b91a893b4d13e95304d541f3a50aae67efda
web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java
java
apache-2.0
SEC-1674: Test to check that absolute URLs work in SimpleUrlLogoutSuccessHandler.
package org.springframework.security.web.authentication.logout; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; /** * * @author Luke Taylor */ public class SimpleUrlLogoutSuccessHandlerTests { @Test public void doesntRedirectIfResponseIsCommitted() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("/target"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCommitted(true); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertNull(request.getSession(false)); assertNull(response.getRedirectedUrl()); assertNull(response.getForwardedUrl()); } }
package org.springframework.security.web.authentication.logout; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; /** * * @author Luke Taylor */ public class SimpleUrlLogoutSuccessHandlerTests { @Test public void doesntRedirectIfResponseIsCommitted() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("/target"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCommitted(true); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertNull(request.getSession(false)); assertNull(response.getRedirectedUrl()); assertNull(response.getForwardedUrl()); } @Test public void absoluteUrlIsSupported() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("http://someurl.com/"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertEquals("http://someurl.com/", response.getRedirectedUrl()); } }
11
0
1
add_only
--- a/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java @@ -28,2 +28,13 @@ } + + @Test + public void absoluteUrlIsSupported() throws Exception { + SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); + lsh.setDefaultTargetUrl("http://someurl.com/"); + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + lsh.onLogoutSuccess(request, response, mock(Authentication.class)); + assertEquals("http://someurl.com/", response.getRedirectedUrl()); + } + }
--- a/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java @@ ... @@ } + + @Test + public void absoluteUrlIsSupported() throws Exception { + SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); + lsh.setDefaultTargetUrl("http://someurl.com/"); + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + lsh.onLogoutSuccess(request, response, mock(Authentication.class)); + assertEquals("http://someurl.com/", response.getRedirectedUrl()); + } + }
--- a/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandlerTests.java @@ -28,2 +28,13 @@ CON } ADD ADD @Test ADD public void absoluteUrlIsSupported() throws Exception { ADD SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); ADD lsh.setDefaultTargetUrl("http://someurl.com/"); ADD MockHttpServletRequest request = new MockHttpServletRequest(); ADD MockHttpServletResponse response = new MockHttpServletResponse(); ADD lsh.onLogoutSuccess(request, response, mock(Authentication.class)); ADD assertEquals("http://someurl.com/", response.getRedirectedUrl()); ADD } ADD CON }
<<<<<<< SEARCH assertNull(response.getForwardedUrl()); } } ======= assertNull(response.getForwardedUrl()); } @Test public void absoluteUrlIsSupported() throws Exception { SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler(); lsh.setDefaultTargetUrl("http://someurl.com/"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); lsh.onLogoutSuccess(request, response, mock(Authentication.class)); assertEquals("http://someurl.com/", response.getRedirectedUrl()); } } >>>>>>> REPLACE
EsotericSoftware/kryo
a4501b27f8f53033968d89f955f589603416c51d
src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java
java
bsd-3-clause
Remove the not needed import
package com.esotericsoftware.kryo.pool; import java.lang.ref.SoftReference; import java.util.Queue; import com.esotericsoftware.kryo.Kryo; /** * A simple {@link Queue} based {@link KryoPool} implementation, should be built * using the KryoPool.Builder. * * @author Martin Grotzke */ class KryoPoolQueueImpl implements KryoPool { private final Queue<Kryo> queue; private final KryoFactory factory; KryoPoolQueueImpl(KryoFactory factory, Queue<Kryo> queue) { this.factory = factory; this.queue = queue; } public int size () { return queue.size(); } public Kryo borrow () { Kryo res; if((res = queue.poll()) != null) { return res; } return factory.create(); } public void release (Kryo kryo) { queue.offer(kryo); } public <T> T run(KryoCallback<T> callback) { Kryo kryo = borrow(); try { return callback.execute(kryo); } finally { release(kryo); } } public void clear() { queue.clear(); } }
package com.esotericsoftware.kryo.pool; import java.util.Queue; import com.esotericsoftware.kryo.Kryo; /** * A simple {@link Queue} based {@link KryoPool} implementation, should be built * using the KryoPool.Builder. * * @author Martin Grotzke */ class KryoPoolQueueImpl implements KryoPool { private final Queue<Kryo> queue; private final KryoFactory factory; KryoPoolQueueImpl(KryoFactory factory, Queue<Kryo> queue) { this.factory = factory; this.queue = queue; } public int size () { return queue.size(); } public Kryo borrow () { Kryo res; if((res = queue.poll()) != null) { return res; } return factory.create(); } public void release (Kryo kryo) { queue.offer(kryo); } public <T> T run(KryoCallback<T> callback) { Kryo kryo = borrow(); try { return callback.execute(kryo); } finally { release(kryo); } } public void clear() { queue.clear(); } }
0
1
1
del_only
--- a/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java +++ b/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java @@ -2,3 +2,2 @@ -import java.lang.ref.SoftReference; import java.util.Queue;
--- a/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java +++ b/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java @@ ... @@ -import java.lang.ref.SoftReference; import java.util.Queue;
--- a/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java +++ b/src/com/esotericsoftware/kryo/pool/KryoPoolQueueImpl.java @@ -2,3 +2,2 @@ CON DEL import java.lang.ref.SoftReference; CON import java.util.Queue;
<<<<<<< SEARCH package com.esotericsoftware.kryo.pool; import java.lang.ref.SoftReference; import java.util.Queue; ======= package com.esotericsoftware.kryo.pool; import java.util.Queue; >>>>>>> REPLACE
aidancully/rust
c34c77c764491460449a6bef06b2149c3ab82f2d
src/test/debuginfo/function-arguments-naked.rs
rust
apache-2.0
Apply `extern "C"` calling convention Co-authored-by: Amanieu d'Antras <[email protected]>
// min-lldb-version: 310 // We have to ignore android because of this issue: // https://github.com/rust-lang/rust/issues/74847 // ignore-android // // We need to use inline assembly, so just use one platform // only-x86_64 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:info args // gdb-check:No arguments. // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:frame variable // lldbg-check:(unsigned long) = 111 (unsigned long) = 222 // lldbr-check:(unsigned long) = 111 (unsigned long) = 222 // lldb-command:continue #![feature(asm)] #![feature(naked_functions)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] fn main() { naked(111, 222); } #[naked] fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break }
// min-lldb-version: 310 // We have to ignore android because of this issue: // https://github.com/rust-lang/rust/issues/74847 // ignore-android // // We need to use inline assembly, so just use one platform // only-x86_64 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:info args // gdb-check:No arguments. // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:frame variable // lldbg-check:(unsigned long) = 111 (unsigned long) = 222 // lldbr-check:(unsigned long) = 111 (unsigned long) = 222 // lldb-command:continue #![feature(asm)] #![feature(naked_functions)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] fn main() { naked(111, 222); } #[naked] extern "C" fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break }
1
1
1
mixed
--- a/src/test/debuginfo/function-arguments-naked.rs +++ b/src/test/debuginfo/function-arguments-naked.rs @@ -39,3 +39,3 @@ #[naked] -fn naked(x: usize, y: usize) { +extern "C" fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break
--- a/src/test/debuginfo/function-arguments-naked.rs +++ b/src/test/debuginfo/function-arguments-naked.rs @@ ... @@ #[naked] -fn naked(x: usize, y: usize) { +extern "C" fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break
--- a/src/test/debuginfo/function-arguments-naked.rs +++ b/src/test/debuginfo/function-arguments-naked.rs @@ -39,3 +39,3 @@ CON #[naked] DEL fn naked(x: usize, y: usize) { ADD extern "C" fn naked(x: usize, y: usize) { CON unsafe { asm!("ret"); } // #break
<<<<<<< SEARCH #[naked] fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break } ======= #[naked] extern "C" fn naked(x: usize, y: usize) { unsafe { asm!("ret"); } // #break } >>>>>>> REPLACE
JetBrains/kotlin-native
c80e6be6582fdf5f5cf013cf4374348755858bdb
runtime/src/main/kotlin/kotlin/test/Assertions.kt
kotlin
apache-2.0
Introduce 'fail' method to throw AssertionError with cause #KT-37804 (cherry picked from commit 0449df5f64b1c2f639786d1865979662331f56d6)
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ /** * A number of common helper methods for writing unit tests. */ @file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") package kotlin.test import kotlin.reflect.KClass /** * Takes the given [block] of test code and _doesn't_ execute it. * * This keeps the code under test referenced, but doesn't actually test it until it is implemented. */ @Suppress("UNUSED_PARAMETER") public actual inline fun todo(block: () -> Unit) { println("TODO") } @PublishedApi internal actual fun <T : Throwable> checkResultIsFailure(exceptionClass: KClass<T>, message: String?, blockResult: Result<Unit>): T { blockResult.fold( onSuccess = { asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was completed successfully.") }, onFailure = { e -> if (exceptionClass.isInstance(e)) { @Suppress("UNCHECKED_CAST") return e as T } asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was $e") } ) } internal actual fun lookupAsserter(): Asserter = DefaultAsserter
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ /** * A number of common helper methods for writing unit tests. */ @file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") package kotlin.test import kotlin.reflect.KClass /** * Takes the given [block] of test code and _doesn't_ execute it. * * This keeps the code under test referenced, but doesn't actually test it until it is implemented. */ @Suppress("UNUSED_PARAMETER") public actual inline fun todo(block: () -> Unit) { println("TODO") } @PublishedApi internal actual fun <T : Throwable> checkResultIsFailure(exceptionClass: KClass<T>, message: String?, blockResult: Result<Unit>): T { blockResult.fold( onSuccess = { asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was completed successfully.") }, onFailure = { e -> if (exceptionClass.isInstance(e)) { @Suppress("UNCHECKED_CAST") return e as T } asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was $e") } ) } /** Platform-specific construction of AssertionError with cause */ @Suppress("NOTHING_TO_INLINE") internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError = AssertionError(message, cause) internal actual fun lookupAsserter(): Asserter = DefaultAsserter
6
0
1
add_only
--- a/runtime/src/main/kotlin/kotlin/test/Assertions.kt +++ b/runtime/src/main/kotlin/kotlin/test/Assertions.kt @@ -40,2 +40,8 @@ +/** Platform-specific construction of AssertionError with cause */ +@Suppress("NOTHING_TO_INLINE") +internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError = + AssertionError(message, cause) + + internal actual fun lookupAsserter(): Asserter = DefaultAsserter
--- a/runtime/src/main/kotlin/kotlin/test/Assertions.kt +++ b/runtime/src/main/kotlin/kotlin/test/Assertions.kt @@ ... @@ +/** Platform-specific construction of AssertionError with cause */ +@Suppress("NOTHING_TO_INLINE") +internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError = + AssertionError(message, cause) + + internal actual fun lookupAsserter(): Asserter = DefaultAsserter
--- a/runtime/src/main/kotlin/kotlin/test/Assertions.kt +++ b/runtime/src/main/kotlin/kotlin/test/Assertions.kt @@ -40,2 +40,8 @@ CON ADD /** Platform-specific construction of AssertionError with cause */ ADD @Suppress("NOTHING_TO_INLINE") ADD internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError = ADD AssertionError(message, cause) ADD ADD CON internal actual fun lookupAsserter(): Asserter = DefaultAsserter
<<<<<<< SEARCH } internal actual fun lookupAsserter(): Asserter = DefaultAsserter ======= } /** Platform-specific construction of AssertionError with cause */ @Suppress("NOTHING_TO_INLINE") internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError = AssertionError(message, cause) internal actual fun lookupAsserter(): Asserter = DefaultAsserter >>>>>>> REPLACE
gamechanger/dusty
c90fd7d026cdeeff7d073c1d15ff550cc937f961
dusty/daemon.py
python
mit
Set up a Unix socket we can use for input
import sys import logging from .preflight import preflight_check from .notifier import notify def configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.captureWarnings(True) def main(): notify('Dusty initializing...') configure_logging() preflight_check() if __name__ == '__main__': main()
import os import sys import logging import socket from .preflight import preflight_check from .notifier import notify SOCKET_PATH = '/var/run/dusty/dusty.sock' def _configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.captureWarnings(True) def _clean_up_existing_socket(): try: os.unlink(SOCKET_PATH) except OSError: if os.path.exists(SOCKET_PATH): raise def _listen_on_socket(): _clean_up_existing_socket() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(SOCKET_PATH) sock.listen(1) notify('Dusty is listening for commands') while True: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break print data finally: connection.close() def main(): notify('Dusty initializing...') _configure_logging() preflight_check() _listen_on_socket() if __name__ == '__main__': main()
34
2
3
mixed
--- a/dusty/daemon.py +++ b/dusty/daemon.py @@ -1,3 +1,5 @@ +import os import sys import logging +import socket @@ -6,3 +8,5 @@ -def configure_logging(): +SOCKET_PATH = '/var/run/dusty/dusty.sock' + +def _configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) @@ -10,6 +14,34 @@ +def _clean_up_existing_socket(): + try: + os.unlink(SOCKET_PATH) + except OSError: + if os.path.exists(SOCKET_PATH): + raise + +def _listen_on_socket(): + _clean_up_existing_socket() + + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.bind(SOCKET_PATH) + sock.listen(1) + + notify('Dusty is listening for commands') + + while True: + connection, client_address = sock.accept() + try: + while True: + data = connection.recv(1024) + if not data: + break + print data + finally: + connection.close() + def main(): notify('Dusty initializing...') - configure_logging() + _configure_logging() preflight_check() + _listen_on_socket()
--- a/dusty/daemon.py +++ b/dusty/daemon.py @@ ... @@ +import os import sys import logging +import socket @@ ... @@ -def configure_logging(): +SOCKET_PATH = '/var/run/dusty/dusty.sock' + +def _configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) @@ ... @@ +def _clean_up_existing_socket(): + try: + os.unlink(SOCKET_PATH) + except OSError: + if os.path.exists(SOCKET_PATH): + raise + +def _listen_on_socket(): + _clean_up_existing_socket() + + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.bind(SOCKET_PATH) + sock.listen(1) + + notify('Dusty is listening for commands') + + while True: + connection, client_address = sock.accept() + try: + while True: + data = connection.recv(1024) + if not data: + break + print data + finally: + connection.close() + def main(): notify('Dusty initializing...') - configure_logging() + _configure_logging() preflight_check() + _listen_on_socket()
--- a/dusty/daemon.py +++ b/dusty/daemon.py @@ -1,3 +1,5 @@ ADD import os CON import sys CON import logging ADD import socket CON @@ -6,3 +8,5 @@ CON DEL def configure_logging(): ADD SOCKET_PATH = '/var/run/dusty/dusty.sock' ADD ADD def _configure_logging(): CON logging.basicConfig(stream=sys.stdout, level=logging.INFO) @@ -10,6 +14,34 @@ CON ADD def _clean_up_existing_socket(): ADD try: ADD os.unlink(SOCKET_PATH) ADD except OSError: ADD if os.path.exists(SOCKET_PATH): ADD raise ADD ADD def _listen_on_socket(): ADD _clean_up_existing_socket() ADD ADD sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) ADD sock.bind(SOCKET_PATH) ADD sock.listen(1) ADD ADD notify('Dusty is listening for commands') ADD ADD while True: ADD connection, client_address = sock.accept() ADD try: ADD while True: ADD data = connection.recv(1024) ADD if not data: ADD break ADD print data ADD finally: ADD connection.close() ADD CON def main(): CON notify('Dusty initializing...') DEL configure_logging() ADD _configure_logging() CON preflight_check() ADD _listen_on_socket() CON
<<<<<<< SEARCH import sys import logging from .preflight import preflight_check from .notifier import notify def configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.captureWarnings(True) def main(): notify('Dusty initializing...') configure_logging() preflight_check() if __name__ == '__main__': ======= import os import sys import logging import socket from .preflight import preflight_check from .notifier import notify SOCKET_PATH = '/var/run/dusty/dusty.sock' def _configure_logging(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.captureWarnings(True) def _clean_up_existing_socket(): try: os.unlink(SOCKET_PATH) except OSError: if os.path.exists(SOCKET_PATH): raise def _listen_on_socket(): _clean_up_existing_socket() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(SOCKET_PATH) sock.listen(1) notify('Dusty is listening for commands') while True: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break print data finally: connection.close() def main(): notify('Dusty initializing...') _configure_logging() preflight_check() _listen_on_socket() if __name__ == '__main__': >>>>>>> REPLACE
dtolnay/thiserror
6957309724e3f4030fb41d400a6932ed9a5dad0a
src/aserror.rs
rust
apache-2.0
Add Sealed supertrait to private AsDynError trait
use std::error::Error; use std::panic::UnwindSafe; pub trait AsDynError<'a> { fn as_dyn_error(&self) -> &(dyn Error + 'a); } impl<'a, T: Error + 'a> AsDynError<'a> for T { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + Sync + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + Sync + UnwindSafe + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } }
use self::private::Sealed; use std::error::Error; use std::panic::UnwindSafe; pub trait AsDynError<'a>: Sealed { fn as_dyn_error(&self) -> &(dyn Error + 'a); } impl<'a, T: Error + 'a> AsDynError<'a> for T { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + Sync + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } impl<'a> AsDynError<'a> for dyn Error + Send + Sync + UnwindSafe + 'a { #[inline] fn as_dyn_error(&self) -> &(dyn Error + 'a) { self } } mod private { use super::*; pub trait Sealed {} impl<'a, T: Error + 'a> Sealed for T {} impl<'a> Sealed for dyn Error + 'a {} impl<'a> Sealed for dyn Error + Send + 'a {} impl<'a> Sealed for dyn Error + Send + Sync + 'a {} impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {} }
13
1
3
mixed
--- a/src/aserror.rs +++ b/src/aserror.rs @@ -1 +1,2 @@ +use self::private::Sealed; use std::error::Error; @@ -3,3 +4,3 @@ -pub trait AsDynError<'a> { +pub trait AsDynError<'a>: Sealed { fn as_dyn_error(&self) -> &(dyn Error + 'a); @@ -41 +42,12 @@ } + +mod private { + use super::*; + + pub trait Sealed {} + impl<'a, T: Error + 'a> Sealed for T {} + impl<'a> Sealed for dyn Error + 'a {} + impl<'a> Sealed for dyn Error + Send + 'a {} + impl<'a> Sealed for dyn Error + Send + Sync + 'a {} + impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {} +}
--- a/src/aserror.rs +++ b/src/aserror.rs @@ ... @@ +use self::private::Sealed; use std::error::Error; @@ ... @@ -pub trait AsDynError<'a> { +pub trait AsDynError<'a>: Sealed { fn as_dyn_error(&self) -> &(dyn Error + 'a); @@ ... @@ } + +mod private { + use super::*; + + pub trait Sealed {} + impl<'a, T: Error + 'a> Sealed for T {} + impl<'a> Sealed for dyn Error + 'a {} + impl<'a> Sealed for dyn Error + Send + 'a {} + impl<'a> Sealed for dyn Error + Send + Sync + 'a {} + impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {} +}
--- a/src/aserror.rs +++ b/src/aserror.rs @@ -1 +1,2 @@ ADD use self::private::Sealed; CON use std::error::Error; @@ -3,3 +4,3 @@ CON DEL pub trait AsDynError<'a> { ADD pub trait AsDynError<'a>: Sealed { CON fn as_dyn_error(&self) -> &(dyn Error + 'a); @@ -41 +42,12 @@ CON } ADD ADD mod private { ADD use super::*; ADD ADD pub trait Sealed {} ADD impl<'a, T: Error + 'a> Sealed for T {} ADD impl<'a> Sealed for dyn Error + 'a {} ADD impl<'a> Sealed for dyn Error + Send + 'a {} ADD impl<'a> Sealed for dyn Error + Send + Sync + 'a {} ADD impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {} ADD }
<<<<<<< SEARCH use std::error::Error; use std::panic::UnwindSafe; pub trait AsDynError<'a> { fn as_dyn_error(&self) -> &(dyn Error + 'a); } ======= use self::private::Sealed; use std::error::Error; use std::panic::UnwindSafe; pub trait AsDynError<'a>: Sealed { fn as_dyn_error(&self) -> &(dyn Error + 'a); } >>>>>>> REPLACE
vimeo/vimeo-networking-java
0a8190aa2845190ec67806abbf24be59efff8529
auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt
kotlin
mit
Add google login method to service
package com.vimeo.networking2.requests import com.vimeo.networking2.VimeoAccount import com.vimeo.networking2.adapters.VimeoCall import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.Header import retrofit2.http.POST /** * All the authentication endpoints. */ interface AuthService { /** * Get an access token by providing the client id and client secret along with grant * and scope types. * * @param authHeader It is created from the client id and client secret. * @param grantType Determines whether you have access to public or private accessToken. * @param scope Determines what you want to access to in the Vimeo API. * * @return A [VimeoAccount] that has an access token. * */ @FormUrlEncoded @POST("oauth/authorize/client") fun authorizeWithClientCredentialsGrant( @Header("Authorization") authHeader: String, @Field("grant_type") grantType: String, @Field("scope") scope: String ): VimeoCall<VimeoAccount> }
package com.vimeo.networking2.requests import com.vimeo.networking2.VimeoAccount import com.vimeo.networking2.adapters.VimeoCall import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.Header import retrofit2.http.POST /** * All the authentication endpoints. */ interface AuthService { /** * Get an access token by providing the client id and client secret along with grant * and scope types. * * @param authHeader Created from the client id and client secret. * @param grantType Determines your access level. * @param scope Determines what you want to access to in the Vimeo API. * * @return A [VimeoAccount] that has an access token. * */ @FormUrlEncoded @POST("oauth/authorize/client") fun authorizeWithClientCredentialsGrant( @Header("Authorization") authHeader: String, @Field("grant_type") grantType: String, @Field("scope") scope: String ): VimeoCall<VimeoAccount> /** * Login with with Google. An access token will be returned after a successful login. * * @param authHeader Created from the client id and client secret. * @param grantType The grant type. Must be set to `google`. * @param idToken The Google ID token */ @FormUrlEncoded @POST("oauth/authorize/google") fun logInWithGoogle(@Header("Authorization") authHeader: String, @Field("grant_type") grantType: String, @Field("id_token") idToken: String ): Call<VimeoAccount> }
17
2
3
mixed
--- a/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt +++ b/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt @@ -4,2 +4,3 @@ import com.vimeo.networking2.adapters.VimeoCall +import retrofit2.Call import retrofit2.http.Field @@ -18,4 +19,4 @@ * - * @param authHeader It is created from the client id and client secret. - * @param grantType Determines whether you have access to public or private accessToken. + * @param authHeader Created from the client id and client secret. + * @param grantType Determines your access level. * @param scope Determines what you want to access to in the Vimeo API. @@ -33,2 +34,16 @@ + /** + * Login with with Google. An access token will be returned after a successful login. + * + * @param authHeader Created from the client id and client secret. + * @param grantType The grant type. Must be set to `google`. + * @param idToken The Google ID token + */ + @FormUrlEncoded + @POST("oauth/authorize/google") + fun logInWithGoogle(@Header("Authorization") authHeader: String, + @Field("grant_type") grantType: String, + @Field("id_token") idToken: String + ): Call<VimeoAccount> + }
--- a/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt +++ b/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt @@ ... @@ import com.vimeo.networking2.adapters.VimeoCall +import retrofit2.Call import retrofit2.http.Field @@ ... @@ * - * @param authHeader It is created from the client id and client secret. - * @param grantType Determines whether you have access to public or private accessToken. + * @param authHeader Created from the client id and client secret. + * @param grantType Determines your access level. * @param scope Determines what you want to access to in the Vimeo API. @@ ... @@ + /** + * Login with with Google. An access token will be returned after a successful login. + * + * @param authHeader Created from the client id and client secret. + * @param grantType The grant type. Must be set to `google`. + * @param idToken The Google ID token + */ + @FormUrlEncoded + @POST("oauth/authorize/google") + fun logInWithGoogle(@Header("Authorization") authHeader: String, + @Field("grant_type") grantType: String, + @Field("id_token") idToken: String + ): Call<VimeoAccount> + }
--- a/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt +++ b/auth/src/main/java/com/vimeo/networking2/requests/AuthService.kt @@ -4,2 +4,3 @@ CON import com.vimeo.networking2.adapters.VimeoCall ADD import retrofit2.Call CON import retrofit2.http.Field @@ -18,4 +19,4 @@ CON * DEL * @param authHeader It is created from the client id and client secret. DEL * @param grantType Determines whether you have access to public or private accessToken. ADD * @param authHeader Created from the client id and client secret. ADD * @param grantType Determines your access level. CON * @param scope Determines what you want to access to in the Vimeo API. @@ -33,2 +34,16 @@ CON ADD /** ADD * Login with with Google. An access token will be returned after a successful login. ADD * ADD * @param authHeader Created from the client id and client secret. ADD * @param grantType The grant type. Must be set to `google`. ADD * @param idToken The Google ID token ADD */ ADD @FormUrlEncoded ADD @POST("oauth/authorize/google") ADD fun logInWithGoogle(@Header("Authorization") authHeader: String, ADD @Field("grant_type") grantType: String, ADD @Field("id_token") idToken: String ADD ): Call<VimeoAccount> ADD CON }
<<<<<<< SEARCH import com.vimeo.networking2.VimeoAccount import com.vimeo.networking2.adapters.VimeoCall import retrofit2.http.Field import retrofit2.http.FormUrlEncoded ======= import com.vimeo.networking2.VimeoAccount import com.vimeo.networking2.adapters.VimeoCall import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded >>>>>>> REPLACE
allotria/intellij-community
6dc9388b6067c88f01717c1cf10d16b7579e30ad
plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt
kotlin
apache-2.0
[stats-collector] Allow to configure position changes showing not only in the internal mode GitOrigin-RevId: af7923b333eaafb28b8a06b2a82113f7986444a4
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.settings import com.intellij.application.options.CodeCompletionOptionsCustomSection import com.intellij.completion.StatsCollectorBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.registry.Registry import com.intellij.ui.layout.* class MLRankingConfigurable(private val supportedLanguages: List<String>) : BoundConfigurable("ML Ranking") { private val settings = CompletionMLRankingSettings.getInstance() override fun createPanel(): DialogPanel { return panel { titledRow(StatsCollectorBundle.message("ml.completion.settings.group")) { row { val enableRanking = checkBox(StatsCollectorBundle.message("ml.completion.enable"), settings::isRankingEnabled, { settings.isRankingEnabled = it }) for (language in supportedLanguages) { row { checkBox(language, { settings.isLanguageEnabled(language) }, { settings.setLanguageEnabled(language, it) }) .enableIf(enableRanking.selected) } } } if (ApplicationManager.getApplication().isInternal) { val registry = Registry.get("completion.stats.show.ml.ranking.diff") row { checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), { registry.asBoolean() }, { registry.setValue(it) }) } } } } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.settings import com.intellij.application.options.CodeCompletionOptionsCustomSection import com.intellij.completion.StatsCollectorBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.registry.Registry import com.intellij.ui.layout.* class MLRankingConfigurable(private val supportedLanguages: List<String>) : BoundConfigurable("ML Ranking") { private val settings = CompletionMLRankingSettings.getInstance() override fun createPanel(): DialogPanel { return panel { titledRow(StatsCollectorBundle.message("ml.completion.settings.group")) { row { val enableRanking = checkBox(StatsCollectorBundle.message("ml.completion.enable"), settings::isRankingEnabled, { settings.isRankingEnabled = it }) for (language in supportedLanguages) { row { checkBox(language, { settings.isLanguageEnabled(language) }, { settings.setLanguageEnabled(language, it) }) .enableIf(enableRanking.selected) } } } val registry = Registry.get("completion.stats.show.ml.ranking.diff") row { checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), { registry.asBoolean() }, { registry.setValue(it) }) } } } } }
5
7
1
mixed
--- a/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt +++ b/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt @@ -28,9 +28,7 @@ } - if (ApplicationManager.getApplication().isInternal) { - val registry = Registry.get("completion.stats.show.ml.ranking.diff") - row { - checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), - { registry.asBoolean() }, - { registry.setValue(it) }) - } + val registry = Registry.get("completion.stats.show.ml.ranking.diff") + row { + checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), + { registry.asBoolean() }, + { registry.setValue(it) }) }
--- a/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt +++ b/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt @@ ... @@ } - if (ApplicationManager.getApplication().isInternal) { - val registry = Registry.get("completion.stats.show.ml.ranking.diff") - row { - checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), - { registry.asBoolean() }, - { registry.setValue(it) }) - } + val registry = Registry.get("completion.stats.show.ml.ranking.diff") + row { + checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), + { registry.asBoolean() }, + { registry.setValue(it) }) }
--- a/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt +++ b/plugins/stats-collector/src/com/intellij/completion/settings/MLRankingConfigurable.kt @@ -28,9 +28,7 @@ CON } DEL if (ApplicationManager.getApplication().isInternal) { DEL val registry = Registry.get("completion.stats.show.ml.ranking.diff") DEL row { DEL checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), DEL { registry.asBoolean() }, DEL { registry.setValue(it) }) DEL } ADD val registry = Registry.get("completion.stats.show.ml.ranking.diff") ADD row { ADD checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), ADD { registry.asBoolean() }, ADD { registry.setValue(it) }) CON }
<<<<<<< SEARCH } } if (ApplicationManager.getApplication().isInternal) { val registry = Registry.get("completion.stats.show.ml.ranking.diff") row { checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), { registry.asBoolean() }, { registry.setValue(it) }) } } } ======= } } val registry = Registry.get("completion.stats.show.ml.ranking.diff") row { checkBox(StatsCollectorBundle.message("ml.completion.show.diff"), { registry.asBoolean() }, { registry.setValue(it) }) } } >>>>>>> REPLACE
SteveChalker/kotlin-koans
6ff2baac5e1a8246c3e8f29130c89297468a2a62
src/v_builders/_39_HtmlBuilders.kt
kotlin
mit
Improve `getCellColor` naming of arguments * `index` is actually `row` * `row` is actually `column`
package v_builders import util.TODO import util.doc39 import v_builders.data.getProducts import v_builders.htmlLibrary.* fun getTitleColor() = "#b9c9fe" fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( """ Task 39. 1) Fill the table with the proper values from products. 2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to functions 'tr', 'td'. You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table. """, documentation = doc39() ) fun renderProductTable(): String { return html { table { tr { td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() todoTask39() } }.toString() }
package v_builders import util.TODO import util.doc39 import v_builders.data.getProducts import v_builders.htmlLibrary.* fun getTitleColor() = "#b9c9fe" fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( """ Task 39. 1) Fill the table with the proper values from products. 2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to functions 'tr', 'td'. You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table. """, documentation = doc39() ) fun renderProductTable(): String { return html { table { tr { td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() todoTask39() } }.toString() }
1
1
1
mixed
--- a/src/v_builders/_39_HtmlBuilders.kt +++ b/src/v_builders/_39_HtmlBuilders.kt @@ -8,3 +8,3 @@ fun getTitleColor() = "#b9c9fe" -fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff" +fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"
--- a/src/v_builders/_39_HtmlBuilders.kt +++ b/src/v_builders/_39_HtmlBuilders.kt @@ ... @@ fun getTitleColor() = "#b9c9fe" -fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff" +fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"
--- a/src/v_builders/_39_HtmlBuilders.kt +++ b/src/v_builders/_39_HtmlBuilders.kt @@ -8,3 +8,3 @@ CON fun getTitleColor() = "#b9c9fe" DEL fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff" ADD fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff" CON
<<<<<<< SEARCH fun getTitleColor() = "#b9c9fe" fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( ======= fun getTitleColor() = "#b9c9fe" fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( >>>>>>> REPLACE
aakloxu/rust-by-example-cn
d2b8e36f0cf1ad52e093fd36b7346eef40c78bc7
examples/custom_types/structs/structs.rs
rust
apache-2.0
Switch from f64 to f32
// 单元结构体 struct Nil; // 元组结构体 struct Pair(i32, f64); // 带有两个字段的结构体 struct Point { x: f64, y: f64, } // 结构体可以作为另一个结构体的字段 #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn main() { // 实例化结构体 `Point` let point: Point = Point { x: 0.3, y: 0.4 }; // 访问 point 的字段 println!("point coordinates: ({}, {})", point.x, point.y); // 使用 `let` 绑定来解构 point let Point { x: my_x, y: my_y } = point; let _rectangle = Rectangle { // 结构体的实例化也是一个表达式 p1: Point { x: my_y, y: my_x }, p2: point, }; // 实例化一个单元结构体 let _nil = Nil; // 实例化一个元组结构体 let pair = Pair(1, 0.1); // 解构一个元组结构体 let Pair(integer, decimal) = pair; println!("pair contains {:?} and {:?}", integer, decimal); }
// 单元结构体 struct Nil; // 元组结构体 struct Pair(i32, f32); // 带有两个字段的结构体 struct Point { x: f32, y: f32, } // 结构体可以作为另一个结构体的字段 #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn main() { // 实例化结构体 `Point` let point: Point = Point { x: 0.3, y: 0.4 }; // 访问 point 的字段 println!("point coordinates: ({}, {})", point.x, point.y); // 使用 `let` 绑定来解构 point let Point { x: my_x, y: my_y } = point; let _rectangle = Rectangle { // 结构体的实例化也是一个表达式 p1: Point { x: my_y, y: my_x }, p2: point, }; // 实例化一个单元结构体 let _nil = Nil; // 实例化一个元组结构体 let pair = Pair(1, 0.1); // 解构一个元组结构体 let Pair(integer, decimal) = pair; println!("pair contains {:?} and {:?}", integer, decimal); }
3
3
2
mixed
--- a/examples/custom_types/structs/structs.rs +++ b/examples/custom_types/structs/structs.rs @@ -4,3 +4,3 @@ // 元组结构体 -struct Pair(i32, f64); +struct Pair(i32, f32); @@ -8,4 +8,4 @@ struct Point { - x: f64, - y: f64, + x: f32, + y: f32, }
--- a/examples/custom_types/structs/structs.rs +++ b/examples/custom_types/structs/structs.rs @@ ... @@ // 元组结构体 -struct Pair(i32, f64); +struct Pair(i32, f32); @@ ... @@ struct Point { - x: f64, - y: f64, + x: f32, + y: f32, }
--- a/examples/custom_types/structs/structs.rs +++ b/examples/custom_types/structs/structs.rs @@ -4,3 +4,3 @@ CON // 元组结构体 DEL struct Pair(i32, f64); ADD struct Pair(i32, f32); CON @@ -8,4 +8,4 @@ CON struct Point { DEL x: f64, DEL y: f64, ADD x: f32, ADD y: f32, CON }
<<<<<<< SEARCH // 元组结构体 struct Pair(i32, f64); // 带有两个字段的结构体 struct Point { x: f64, y: f64, } ======= // 元组结构体 struct Pair(i32, f32); // 带有两个字段的结构体 struct Point { x: f32, y: f32, } >>>>>>> REPLACE
dominicrodger/pywebfaction
a3df62c7da4aa29ab9977a0307e0634fd43e37e8
pywebfaction/exceptions.py
python
bsd-3-clause
Make code immune to bad fault messages
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying_fault): self.underlying_fault = underlying_fault exc_type, exc_message = underlying_fault.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message)
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying): self.underlying_fault = underlying try: exc_type, exc_message = underlying.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) except ValueError: self.exception_type = None self.exception_message = None
9
5
1
mixed
--- a/pywebfaction/exceptions.py +++ b/pywebfaction/exceptions.py @@ -35,6 +35,10 @@ class WebFactionFault(Exception): - def __init__(self, underlying_fault): - self.underlying_fault = underlying_fault - exc_type, exc_message = underlying_fault.faultString.split(':', 1) - self.exception_type = _parse_exc_type(exc_type) - self.exception_message = _parse_exc_message(exc_message) + def __init__(self, underlying): + self.underlying_fault = underlying + try: + exc_type, exc_message = underlying.faultString.split(':', 1) + self.exception_type = _parse_exc_type(exc_type) + self.exception_message = _parse_exc_message(exc_message) + except ValueError: + self.exception_type = None + self.exception_message = None
--- a/pywebfaction/exceptions.py +++ b/pywebfaction/exceptions.py @@ ... @@ class WebFactionFault(Exception): - def __init__(self, underlying_fault): - self.underlying_fault = underlying_fault - exc_type, exc_message = underlying_fault.faultString.split(':', 1) - self.exception_type = _parse_exc_type(exc_type) - self.exception_message = _parse_exc_message(exc_message) + def __init__(self, underlying): + self.underlying_fault = underlying + try: + exc_type, exc_message = underlying.faultString.split(':', 1) + self.exception_type = _parse_exc_type(exc_type) + self.exception_message = _parse_exc_message(exc_message) + except ValueError: + self.exception_type = None + self.exception_message = None
--- a/pywebfaction/exceptions.py +++ b/pywebfaction/exceptions.py @@ -35,6 +35,10 @@ CON class WebFactionFault(Exception): DEL def __init__(self, underlying_fault): DEL self.underlying_fault = underlying_fault DEL exc_type, exc_message = underlying_fault.faultString.split(':', 1) DEL self.exception_type = _parse_exc_type(exc_type) DEL self.exception_message = _parse_exc_message(exc_message) ADD def __init__(self, underlying): ADD self.underlying_fault = underlying ADD try: ADD exc_type, exc_message = underlying.faultString.split(':', 1) ADD self.exception_type = _parse_exc_type(exc_type) ADD self.exception_message = _parse_exc_message(exc_message) ADD except ValueError: ADD self.exception_type = None ADD self.exception_message = None
<<<<<<< SEARCH class WebFactionFault(Exception): def __init__(self, underlying_fault): self.underlying_fault = underlying_fault exc_type, exc_message = underlying_fault.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) ======= class WebFactionFault(Exception): def __init__(self, underlying): self.underlying_fault = underlying try: exc_type, exc_message = underlying.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) except ValueError: self.exception_type = None self.exception_message = None >>>>>>> REPLACE
philou/concurrency-kata
a079a955dfe3e0c1d098c24da85008353aa6417e
src/main/java/net/bourgau/philippe/concurrency/kata/Client.java
java
mit
Clean exit from the command line client - 'bye' keyword exits the client
package net.bourgau.philippe.concurrency.kata; import java.util.Scanner; public class Client implements Broadcast { private final ChatRoom chatRoom; private final String name; private final Output out; public Client(String name, ChatRoom chatRoom, Output out) { this.chatRoom = chatRoom; this.name = name; this.out = out; } public void enter() { chatRoom.enter(this); chatRoom.broadcast(welcomeMessage(name)); } public void write(String message) { chatRoom.broadcast(message(name, message)); } @Override public void broadcast(String message) { out.write(message); } public void leave() { chatRoom.broadcast(exitMessage(name)); chatRoom.leave(this); } public static String welcomeMessage(String name) { return "Welcome " + name + " !"; } public static String message(String name, String message) { return name + " > " + message; } static String exitMessage(String name) { return name + " left"; } public static void main(String[] args) { Client client = new Client(args[0], new ChatRoom(), new Output() { public void write(String line) { System.out.println(line); } }); client.enter(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { client.broadcast(scanner.nextLine()); } } }
package net.bourgau.philippe.concurrency.kata; import java.util.Scanner; public class Client implements Broadcast { private final ChatRoom chatRoom; private final String name; private final Output out; public Client(String name, ChatRoom chatRoom, Output out) { this.chatRoom = chatRoom; this.name = name; this.out = out; } public void enter() { chatRoom.enter(this); chatRoom.broadcast(welcomeMessage(name)); } public void write(String message) { chatRoom.broadcast(message(name, message)); } @Override public void broadcast(String message) { out.write(message); } public void leave() { chatRoom.broadcast(exitMessage(name)); chatRoom.leave(this); } public static String welcomeMessage(String name) { return "Welcome " + name + " !"; } public static String message(String name, String message) { return name + " > " + message; } static String exitMessage(String name) { return name + " left"; } public static void main(String[] args) { Client client = new Client(args[0], new ChatRoom(), new Output() { public void write(String line) { System.out.println(line); } }); try { client.enter(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String message = scanner.nextLine(); if (message.equals("bye")) { break; } client.broadcast(message); } } finally { client.leave(); } } }
12
4
1
mixed
--- a/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java +++ b/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java @@ -55,7 +55,15 @@ - client.enter(); + try { + client.enter(); - Scanner scanner = new Scanner(System.in); - while (scanner.hasNextLine()) { - client.broadcast(scanner.nextLine()); + Scanner scanner = new Scanner(System.in); + while (scanner.hasNextLine()) { + String message = scanner.nextLine(); + if (message.equals("bye")) { + break; + } + client.broadcast(message); + } + } finally { + client.leave(); }
--- a/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java +++ b/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java @@ ... @@ - client.enter(); + try { + client.enter(); - Scanner scanner = new Scanner(System.in); - while (scanner.hasNextLine()) { - client.broadcast(scanner.nextLine()); + Scanner scanner = new Scanner(System.in); + while (scanner.hasNextLine()) { + String message = scanner.nextLine(); + if (message.equals("bye")) { + break; + } + client.broadcast(message); + } + } finally { + client.leave(); }
--- a/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java +++ b/src/main/java/net/bourgau/philippe/concurrency/kata/Client.java @@ -55,7 +55,15 @@ CON DEL client.enter(); ADD try { ADD client.enter(); CON DEL Scanner scanner = new Scanner(System.in); DEL while (scanner.hasNextLine()) { DEL client.broadcast(scanner.nextLine()); ADD Scanner scanner = new Scanner(System.in); ADD while (scanner.hasNextLine()) { ADD String message = scanner.nextLine(); ADD if (message.equals("bye")) { ADD break; ADD } ADD client.broadcast(message); ADD } ADD } finally { ADD client.leave(); CON }
<<<<<<< SEARCH }); client.enter(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { client.broadcast(scanner.nextLine()); } } ======= }); try { client.enter(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String message = scanner.nextLine(); if (message.equals("bye")) { break; } client.broadcast(message); } } finally { client.leave(); } } >>>>>>> REPLACE
sosedoff/reeder
71ae65de4b3e2e71cc6fb0e3fd3285d51d599a07
app/assets/js/helpers.js
javascript
mit
Handle links with leading double slashes
function matchAll(str, regex) { var matches = []; while (result = regex.exec(str)) { matches.push(result[1]); } return matches; } angular.module('reeder.helpers', []). filter('postDateFormatter', function() { return function(unformatted_date) { var date = new Date(unformatted_date); return moment(date).format('dddd, h:m a'); }; }). filter('postFormatter', function() { return function(post) { var content = post.content; var regex = /<img.*?src=['|"](.*?)['|"]/gi; var matches = matchAll(content, regex); if (matches.length > 0) { for (i in matches) { var url = matches[i]; if (!url.match(/^http(s?):/)) { var new_url = post.feed.site_url; if (url[0] == '/') new_url += url; else new_url += '/' + url; content = content.replace(url, new_url); } } } return content; } });
function matchAll(str, regex) { var matches = []; while (result = regex.exec(str)) { matches.push(result[1]); } return matches; } angular.module('reeder.helpers', []). filter('postDateFormatter', function() { return function(unformatted_date) { var date = new Date(unformatted_date); return moment(date).format('dddd, h:m a'); }; }). filter('postFormatter', function() { return function(post) { var content = post.content; var regex = /<img.*?src=['|"](.*?)['|"]/gi; var matches = matchAll(content, regex); if (matches.length > 0) { for (i in matches) { var url = matches[i]; if (!url.match(/^http(s?):/)) { var new_url = post.feed.site_url; if (url.substring(0, 2) != '//') { if (url[0] == '/') new_url += url; else new_url += '/' + url; content = content.replace(url, new_url); } } } } return content; } });
6
3
1
mixed
--- a/app/assets/js/helpers.js +++ b/app/assets/js/helpers.js @@ -29,5 +29,8 @@ - if (url[0] == '/') new_url += url; - else new_url += '/' + url; - content = content.replace(url, new_url); + if (url.substring(0, 2) != '//') { + if (url[0] == '/') new_url += url; + else new_url += '/' + url; + + content = content.replace(url, new_url); + } }
--- a/app/assets/js/helpers.js +++ b/app/assets/js/helpers.js @@ ... @@ - if (url[0] == '/') new_url += url; - else new_url += '/' + url; - content = content.replace(url, new_url); + if (url.substring(0, 2) != '//') { + if (url[0] == '/') new_url += url; + else new_url += '/' + url; + + content = content.replace(url, new_url); + } }
--- a/app/assets/js/helpers.js +++ b/app/assets/js/helpers.js @@ -29,5 +29,8 @@ CON DEL if (url[0] == '/') new_url += url; DEL else new_url += '/' + url; DEL content = content.replace(url, new_url); ADD if (url.substring(0, 2) != '//') { ADD if (url[0] == '/') new_url += url; ADD else new_url += '/' + url; ADD ADD content = content.replace(url, new_url); ADD } CON }
<<<<<<< SEARCH var new_url = post.feed.site_url; if (url[0] == '/') new_url += url; else new_url += '/' + url; content = content.replace(url, new_url); } } ======= var new_url = post.feed.site_url; if (url.substring(0, 2) != '//') { if (url[0] == '/') new_url += url; else new_url += '/' + url; content = content.replace(url, new_url); } } } >>>>>>> REPLACE
mikegehard/user-management-evolution-kotlin
5e72bf8392bc4844ba5abcd49eb63c55d19d4657
applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt
kotlin
mit
Use constructor injection so you can make instance variables vals
package com.example.billing.reocurringPayments import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController class Controller { @Autowired private lateinit var paymentGateway: com.example.payments.Gateway @Autowired private lateinit var counter: CounterService @Autowired private lateinit var service: Service @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
package com.example.billing.reocurringPayments import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.inject.Inject @RestController class Controller { private val paymentGateway: com.example.payments.Gateway private val counter: CounterService private val service: Service @Inject constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { this.paymentGateway = paymentGateway this.counter = counterService this.service = service } @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders() responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString()) service.thisMayFail() val response: ResponseEntity<String> if (paymentGateway.createReocurringPayment(data["amount"] as Int)) { counter.increment("billing.reocurringPayment.created") response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
13
7
3
mixed
--- a/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt +++ b/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt @@ -2,3 +2,3 @@ -import org.springframework.beans.factory.annotation.Autowired +import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService @@ -12,2 +12,3 @@ import org.springframework.web.bind.annotation.RestController +import javax.inject.Inject @@ -15,10 +16,15 @@ class Controller { - @Autowired - private lateinit var paymentGateway: com.example.payments.Gateway + private val paymentGateway: com.example.payments.Gateway - @Autowired - private lateinit var counter: CounterService + private val counter: CounterService - @Autowired - private lateinit var service: Service + private val service: Service + + + @Inject + constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { + this.paymentGateway = paymentGateway + this.counter = counterService + this.service = service + }
--- a/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt +++ b/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt @@ ... @@ -import org.springframework.beans.factory.annotation.Autowired +import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService @@ ... @@ import org.springframework.web.bind.annotation.RestController +import javax.inject.Inject @@ ... @@ class Controller { - @Autowired - private lateinit var paymentGateway: com.example.payments.Gateway + private val paymentGateway: com.example.payments.Gateway - @Autowired - private lateinit var counter: CounterService + private val counter: CounterService - @Autowired - private lateinit var service: Service + private val service: Service + + + @Inject + constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { + this.paymentGateway = paymentGateway + this.counter = counterService + this.service = service + }
--- a/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt +++ b/applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt @@ -2,3 +2,3 @@ CON DEL import org.springframework.beans.factory.annotation.Autowired ADD import com.example.payments.Gateway CON import org.springframework.boot.actuate.metrics.CounterService @@ -12,2 +12,3 @@ CON import org.springframework.web.bind.annotation.RestController ADD import javax.inject.Inject CON @@ -15,10 +16,15 @@ CON class Controller { DEL @Autowired DEL private lateinit var paymentGateway: com.example.payments.Gateway ADD private val paymentGateway: com.example.payments.Gateway CON DEL @Autowired DEL private lateinit var counter: CounterService ADD private val counter: CounterService CON DEL @Autowired DEL private lateinit var service: Service ADD private val service: Service ADD ADD ADD @Inject ADD constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) { ADD this.paymentGateway = paymentGateway ADD this.counter = counterService ADD this.service = service ADD } CON
<<<<<<< SEARCH package com.example.billing.reocurringPayments import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders ======= package com.example.billing.reocurringPayments import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders >>>>>>> REPLACE
Vectorious/geom-rs
5ecacf200f4eaaad68e5fddd497596049c978f53
src/point.rs
rust
mit
Remove Point struct; Add Point trait
use rect::Rect; use std::ops::{Add, Sub}; pub const ZERO: Point = Point { x: 0, y: 0 }; pub const UP: Point = Point { x: 0, y: -1 }; pub const DOWN: Point = Point { x: 0, y: 1 }; pub const LEFT: Point = Point { x: -1, y: 0 }; pub const RIGHT: Point = Point { x: 1, y: 0 }; /// A simple two-dimensional Point structure. #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] pub struct Point { pub x: i32, pub y: i32 } impl Point { /// Creates a new point with the given `x` and `y` coordinates. pub fn new(x: i32, y: i32) -> Point { Point { x: x, y: y } } /// Creates a rect with `self` as the top-left point and `other` as the bottom-right point. pub fn rect(&self, other: Point) -> Rect { Rect::from_points(*self, other) } } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } /// Adds an `i32` value to both the `x` and `y` values of a point. impl Add<i32> for Point { type Output = Point; fn add(self, other: i32) -> Point { Point { x: self.x + other, y: self.y + other } } } impl Sub for Point { type Output = Point; fn sub(self, other: Point) -> Point { Point { x: self.x - other.x, y: self.y - other.y } } } /// Subtracts an `i32` value from both the `x` and `y` values of a point. impl Sub<i32> for Point { type Output = Point; fn sub(self, other: i32) -> Point { Point { x: self.x - other, y: self.y - other } } }
use rect::Rect; use std::ops::{Add, Sub}; trait Point<T> { fn new(x: T, y: T) -> Point<T>; fn x() -> T; fn y() -> T; }
4
56
1
mixed
--- a/src/point.rs +++ b/src/point.rs @@ -3,58 +3,6 @@ -pub const ZERO: Point = Point { x: 0, y: 0 }; -pub const UP: Point = Point { x: 0, y: -1 }; -pub const DOWN: Point = Point { x: 0, y: 1 }; -pub const LEFT: Point = Point { x: -1, y: 0 }; -pub const RIGHT: Point = Point { x: 1, y: 0 }; - - -/// A simple two-dimensional Point structure. -#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] -pub struct Point { - pub x: i32, - pub y: i32 +trait Point<T> { + fn new(x: T, y: T) -> Point<T>; + fn x() -> T; + fn y() -> T; } - -impl Point { - /// Creates a new point with the given `x` and `y` coordinates. - pub fn new(x: i32, y: i32) -> Point { - Point { x: x, y: y } - } - - /// Creates a rect with `self` as the top-left point and `other` as the bottom-right point. - pub fn rect(&self, other: Point) -> Rect { - Rect::from_points(*self, other) - } -} - - -impl Add for Point { - type Output = Point; - fn add(self, other: Point) -> Point { - Point { x: self.x + other.x, y: self.y + other.y } - } -} - -/// Adds an `i32` value to both the `x` and `y` values of a point. -impl Add<i32> for Point { - type Output = Point; - fn add(self, other: i32) -> Point { - Point { x: self.x + other, y: self.y + other } - } -} - -impl Sub for Point { - type Output = Point; - fn sub(self, other: Point) -> Point { - Point { x: self.x - other.x, y: self.y - other.y } - } -} - -/// Subtracts an `i32` value from both the `x` and `y` values of a point. -impl Sub<i32> for Point { - type Output = Point; - fn sub(self, other: i32) -> Point { - Point { x: self.x - other, y: self.y - other } - } -} -
--- a/src/point.rs +++ b/src/point.rs @@ ... @@ -pub const ZERO: Point = Point { x: 0, y: 0 }; -pub const UP: Point = Point { x: 0, y: -1 }; -pub const DOWN: Point = Point { x: 0, y: 1 }; -pub const LEFT: Point = Point { x: -1, y: 0 }; -pub const RIGHT: Point = Point { x: 1, y: 0 }; - - -/// A simple two-dimensional Point structure. -#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] -pub struct Point { - pub x: i32, - pub y: i32 +trait Point<T> { + fn new(x: T, y: T) -> Point<T>; + fn x() -> T; + fn y() -> T; } - -impl Point { - /// Creates a new point with the given `x` and `y` coordinates. - pub fn new(x: i32, y: i32) -> Point { - Point { x: x, y: y } - } - - /// Creates a rect with `self` as the top-left point and `other` as the bottom-right point. - pub fn rect(&self, other: Point) -> Rect { - Rect::from_points(*self, other) - } -} - - -impl Add for Point { - type Output = Point; - fn add(self, other: Point) -> Point { - Point { x: self.x + other.x, y: self.y + other.y } - } -} - -/// Adds an `i32` value to both the `x` and `y` values of a point. -impl Add<i32> for Point { - type Output = Point; - fn add(self, other: i32) -> Point { - Point { x: self.x + other, y: self.y + other } - } -} - -impl Sub for Point { - type Output = Point; - fn sub(self, other: Point) -> Point { - Point { x: self.x - other.x, y: self.y - other.y } - } -} - -/// Subtracts an `i32` value from both the `x` and `y` values of a point. -impl Sub<i32> for Point { - type Output = Point; - fn sub(self, other: i32) -> Point { - Point { x: self.x - other, y: self.y - other } - } -} -
--- a/src/point.rs +++ b/src/point.rs @@ -3,58 +3,6 @@ CON DEL pub const ZERO: Point = Point { x: 0, y: 0 }; DEL pub const UP: Point = Point { x: 0, y: -1 }; DEL pub const DOWN: Point = Point { x: 0, y: 1 }; DEL pub const LEFT: Point = Point { x: -1, y: 0 }; DEL pub const RIGHT: Point = Point { x: 1, y: 0 }; DEL DEL DEL /// A simple two-dimensional Point structure. DEL #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] DEL pub struct Point { DEL pub x: i32, DEL pub y: i32 ADD trait Point<T> { ADD fn new(x: T, y: T) -> Point<T>; ADD fn x() -> T; ADD fn y() -> T; CON } DEL DEL impl Point { DEL /// Creates a new point with the given `x` and `y` coordinates. DEL pub fn new(x: i32, y: i32) -> Point { DEL Point { x: x, y: y } DEL } DEL DEL /// Creates a rect with `self` as the top-left point and `other` as the bottom-right point. DEL pub fn rect(&self, other: Point) -> Rect { DEL Rect::from_points(*self, other) DEL } DEL } DEL DEL DEL impl Add for Point { DEL type Output = Point; DEL fn add(self, other: Point) -> Point { DEL Point { x: self.x + other.x, y: self.y + other.y } DEL } DEL } DEL DEL /// Adds an `i32` value to both the `x` and `y` values of a point. DEL impl Add<i32> for Point { DEL type Output = Point; DEL fn add(self, other: i32) -> Point { DEL Point { x: self.x + other, y: self.y + other } DEL } DEL } DEL DEL impl Sub for Point { DEL type Output = Point; DEL fn sub(self, other: Point) -> Point { DEL Point { x: self.x - other.x, y: self.y - other.y } DEL } DEL } DEL DEL /// Subtracts an `i32` value from both the `x` and `y` values of a point. DEL impl Sub<i32> for Point { DEL type Output = Point; DEL fn sub(self, other: i32) -> Point { DEL Point { x: self.x - other, y: self.y - other } DEL } DEL } DEL
<<<<<<< SEARCH use std::ops::{Add, Sub}; pub const ZERO: Point = Point { x: 0, y: 0 }; pub const UP: Point = Point { x: 0, y: -1 }; pub const DOWN: Point = Point { x: 0, y: 1 }; pub const LEFT: Point = Point { x: -1, y: 0 }; pub const RIGHT: Point = Point { x: 1, y: 0 }; /// A simple two-dimensional Point structure. #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] pub struct Point { pub x: i32, pub y: i32 } impl Point { /// Creates a new point with the given `x` and `y` coordinates. pub fn new(x: i32, y: i32) -> Point { Point { x: x, y: y } } /// Creates a rect with `self` as the top-left point and `other` as the bottom-right point. pub fn rect(&self, other: Point) -> Rect { Rect::from_points(*self, other) } } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } /// Adds an `i32` value to both the `x` and `y` values of a point. impl Add<i32> for Point { type Output = Point; fn add(self, other: i32) -> Point { Point { x: self.x + other, y: self.y + other } } } impl Sub for Point { type Output = Point; fn sub(self, other: Point) -> Point { Point { x: self.x - other.x, y: self.y - other.y } } } /// Subtracts an `i32` value from both the `x` and `y` values of a point. impl Sub<i32> for Point { type Output = Point; fn sub(self, other: i32) -> Point { Point { x: self.x - other, y: self.y - other } } } ======= use std::ops::{Add, Sub}; trait Point<T> { fn new(x: T, y: T) -> Point<T>; fn x() -> T; fn y() -> T; } >>>>>>> REPLACE
hzsweers/CatchUp
46dd3a2d6a206be7d76d950f9bf0438fdd57bfc3
app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt
kotlin
apache-2.0
Fix missing okhttp builder in release variant
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.app import android.app.Application import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.support.AndroidSupportInjectionModule import io.sweers.catchup.data.DataModule import io.sweers.catchup.ui.activity.ActivityBindingModule import javax.inject.Singleton @Singleton @Component(modules = [ ActivityBindingModule::class, AndroidSupportInjectionModule::class, AndroidInjectionModule::class, ApplicationModule::class, DataModule::class, ReleaseApplicationModule::class ]) interface ApplicationComponent { fun inject(application: CatchUpApplication) @Component.Factory interface Builder { fun create(@BindsInstance application: Application): ApplicationComponent } }
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.app import android.app.Application import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.support.AndroidSupportInjectionModule import io.sweers.catchup.data.DataModule import io.sweers.catchup.data.InstanceBasedOkHttpLibraryGlideModule import io.sweers.catchup.ui.activity.ActivityBindingModule import javax.inject.Singleton @Singleton @Component(modules = [ ActivityBindingModule::class, AndroidSupportInjectionModule::class, AndroidInjectionModule::class, ApplicationModule::class, DataModule::class, ReleaseApplicationModule::class ]) interface ApplicationComponent { fun okhttpGlideComponentBuilder(): InstanceBasedOkHttpLibraryGlideModule.Component.Builder fun inject(application: CatchUpApplication) @Component.Factory interface Builder { fun create(@BindsInstance application: Application): ApplicationComponent } }
3
0
2
add_only
--- a/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt +++ b/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt @@ -23,2 +23,3 @@ import io.sweers.catchup.data.DataModule +import io.sweers.catchup.data.InstanceBasedOkHttpLibraryGlideModule import io.sweers.catchup.ui.activity.ActivityBindingModule @@ -37,2 +38,4 @@ + fun okhttpGlideComponentBuilder(): InstanceBasedOkHttpLibraryGlideModule.Component.Builder + fun inject(application: CatchUpApplication)
--- a/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt +++ b/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt @@ ... @@ import io.sweers.catchup.data.DataModule +import io.sweers.catchup.data.InstanceBasedOkHttpLibraryGlideModule import io.sweers.catchup.ui.activity.ActivityBindingModule @@ ... @@ + fun okhttpGlideComponentBuilder(): InstanceBasedOkHttpLibraryGlideModule.Component.Builder + fun inject(application: CatchUpApplication)
--- a/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt +++ b/app/src/release/kotlin/io/sweers/catchup/app/ApplicationComponent.kt @@ -23,2 +23,3 @@ CON import io.sweers.catchup.data.DataModule ADD import io.sweers.catchup.data.InstanceBasedOkHttpLibraryGlideModule CON import io.sweers.catchup.ui.activity.ActivityBindingModule @@ -37,2 +38,4 @@ CON ADD fun okhttpGlideComponentBuilder(): InstanceBasedOkHttpLibraryGlideModule.Component.Builder ADD CON fun inject(application: CatchUpApplication)
<<<<<<< SEARCH import dagger.android.support.AndroidSupportInjectionModule import io.sweers.catchup.data.DataModule import io.sweers.catchup.ui.activity.ActivityBindingModule import javax.inject.Singleton ======= import dagger.android.support.AndroidSupportInjectionModule import io.sweers.catchup.data.DataModule import io.sweers.catchup.data.InstanceBasedOkHttpLibraryGlideModule import io.sweers.catchup.ui.activity.ActivityBindingModule import javax.inject.Singleton >>>>>>> REPLACE
influxdb/influxdb
b3e712daae55ede6e176ec3b115406790a3bf0ff
ui/src/shared/components/FancyScrollbar.js
javascript
mit
Add autoHide prop to pass down
import React, {Component, PropTypes} from 'react' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } render() { const {children, className} = this.props return ( <Scrollbars className={`fancy-scroll--container ${className}`} autoHide={true} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string.isRequired, } export default FancyScrollbox
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, } render() { const {autoHide, children, className} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', {[className]: className})} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {bool, node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string, autoHide: bool, } export default FancyScrollbox
11
5
5
mixed
--- a/ui/src/shared/components/FancyScrollbar.js +++ b/ui/src/shared/components/FancyScrollbar.js @@ -1,2 +1,3 @@ import React, {Component, PropTypes} from 'react' +import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' @@ -8,4 +9,8 @@ + static defaultProps = { + autoHide: true, + } + render() { - const {children, className} = this.props + const {autoHide, children, className} = this.props @@ -13,4 +18,4 @@ <Scrollbars - className={`fancy-scroll--container ${className}`} - autoHide={true} + className={classnames('fancy-scroll--container', {[className]: className})} + autoHide={autoHide} autoHideTimeout={1000} @@ -28,3 +33,3 @@ -const {node, string} = PropTypes +const {bool, node, string} = PropTypes @@ -32,3 +37,4 @@ children: node.isRequired, - className: string.isRequired, + className: string, + autoHide: bool, }
--- a/ui/src/shared/components/FancyScrollbar.js +++ b/ui/src/shared/components/FancyScrollbar.js @@ ... @@ import React, {Component, PropTypes} from 'react' +import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' @@ ... @@ + static defaultProps = { + autoHide: true, + } + render() { - const {children, className} = this.props + const {autoHide, children, className} = this.props @@ ... @@ <Scrollbars - className={`fancy-scroll--container ${className}`} - autoHide={true} + className={classnames('fancy-scroll--container', {[className]: className})} + autoHide={autoHide} autoHideTimeout={1000} @@ ... @@ -const {node, string} = PropTypes +const {bool, node, string} = PropTypes @@ ... @@ children: node.isRequired, - className: string.isRequired, + className: string, + autoHide: bool, }
--- a/ui/src/shared/components/FancyScrollbar.js +++ b/ui/src/shared/components/FancyScrollbar.js @@ -1,2 +1,3 @@ CON import React, {Component, PropTypes} from 'react' ADD import classnames from 'classnames' CON import {Scrollbars} from 'react-custom-scrollbars' @@ -8,4 +9,8 @@ CON ADD static defaultProps = { ADD autoHide: true, ADD } ADD CON render() { DEL const {children, className} = this.props ADD const {autoHide, children, className} = this.props CON @@ -13,4 +18,4 @@ CON <Scrollbars DEL className={`fancy-scroll--container ${className}`} DEL autoHide={true} ADD className={classnames('fancy-scroll--container', {[className]: className})} ADD autoHide={autoHide} CON autoHideTimeout={1000} @@ -28,3 +33,3 @@ CON DEL const {node, string} = PropTypes ADD const {bool, node, string} = PropTypes CON @@ -32,3 +37,4 @@ CON children: node.isRequired, DEL className: string.isRequired, ADD className: string, ADD autoHide: bool, CON }
<<<<<<< SEARCH import React, {Component, PropTypes} from 'react' import {Scrollbars} from 'react-custom-scrollbars' ======= import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' >>>>>>> REPLACE
jbmusso/zer
3bbf44c804f66ff5d09d09629f3fdd3ea2643b6a
src/chain.js
javascript
mit
Clean up old STRATEGY object
import _ from 'lodash'; class ChainStart { constructor(name) { this.name = name; this.type = 'CHAIN_START'; } } class Step { constructor(name) { this.name = name; this.type = 'STEP'; } } class Arguments { constructor(params = []) { this.params = params; this.type = 'ARGUMENTS' } } export class Chain { constructor() { this.members = []; } startWith(identifierName) { this.members.push(new ChainStart(identifierName)); return this; } addStep(name) { this.members.push(new Step(name)); return this; } addArguments(...args) { this.members.push(new Arguments(args)); return this; } __repr__(...args) { return this.members; } } export function createChain() { return new Chain(); } export const STRATEGY = { init(name) { return createChain(name); }, addStep(chain, name) { chain.addStep(name) }, addArguments(chain, ...args) { chain.addArguments(...args) } }
import _ from 'lodash'; class ChainStart { constructor(name) { this.name = name; this.type = 'CHAIN_START'; } } class Step { constructor(name) { this.name = name; this.type = 'STEP'; } } class Arguments { constructor(params = []) { this.params = params; this.type = 'ARGUMENTS' } } export class Chain { constructor() { this.members = []; } startWith(identifierName) { this.members.push(new ChainStart(identifierName)); return this; } addStep(name) { this.members.push(new Step(name)); return this; } addArguments(...args) { this.members.push(new Arguments(args)); return this; } __repr__(...args) { return this.members; } } // TODO: missing name argument here? export function createChain() { return new Chain(); }
1
14
2
mixed
--- a/src/chain.js +++ b/src/chain.js @@ -49,2 +49,3 @@ +// TODO: missing name argument here? export function createChain() { @@ -52,15 +53 @@ } - -export const STRATEGY = { - init(name) { - return createChain(name); - }, - - addStep(chain, name) { - chain.addStep(name) - }, - - addArguments(chain, ...args) { - chain.addArguments(...args) - } -}
--- a/src/chain.js +++ b/src/chain.js @@ ... @@ +// TODO: missing name argument here? export function createChain() { @@ ... @@ } - -export const STRATEGY = { - init(name) { - return createChain(name); - }, - - addStep(chain, name) { - chain.addStep(name) - }, - - addArguments(chain, ...args) { - chain.addArguments(...args) - } -}
--- a/src/chain.js +++ b/src/chain.js @@ -49,2 +49,3 @@ CON ADD // TODO: missing name argument here? CON export function createChain() { @@ -52,15 +53 @@ CON } DEL DEL export const STRATEGY = { DEL init(name) { DEL return createChain(name); DEL }, DEL DEL addStep(chain, name) { DEL chain.addStep(name) DEL }, DEL DEL addArguments(chain, ...args) { DEL chain.addArguments(...args) DEL } DEL }
<<<<<<< SEARCH } export function createChain() { return new Chain(); } export const STRATEGY = { init(name) { return createChain(name); }, addStep(chain, name) { chain.addStep(name) }, addArguments(chain, ...args) { chain.addArguments(...args) } } ======= } // TODO: missing name argument here? export function createChain() { return new Chain(); } >>>>>>> REPLACE
miguelcobain/ember-css-transitions
795765887dfc29fbe7a6f88ae44afcec8fa8d21e
tests/dummy/config/environment.js
javascript
mit
Use hash based location type for now to support IE9 / ember bug
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-css-transitions' } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-css-transitions' } return ENV; };
1
1
1
mixed
--- a/tests/dummy/config/environment.js +++ b/tests/dummy/config/environment.js @@ -7,3 +7,3 @@ baseURL: '/', - locationType: 'auto', + locationType: 'hash', EmberENV: {
--- a/tests/dummy/config/environment.js +++ b/tests/dummy/config/environment.js @@ ... @@ baseURL: '/', - locationType: 'auto', + locationType: 'hash', EmberENV: {
--- a/tests/dummy/config/environment.js +++ b/tests/dummy/config/environment.js @@ -7,3 +7,3 @@ CON baseURL: '/', DEL locationType: 'auto', ADD locationType: 'hash', CON EmberENV: {
<<<<<<< SEARCH environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { ======= environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { >>>>>>> REPLACE
NUBIC/psc-mirror
8a0672676c6bf5978e18962a71485a9082457c1b
test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java
java
bsd-3-clause
Extend CoreTestCase for access to assertPositve/Negative, others git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@136 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.testing; import junit.framework.TestCase; import java.lang.reflect.Method; import java.util.Set; import java.util.HashSet; import org.easymock.classextension.EasyMock; /** * @author Rhett Sutphin */ public abstract class StudyCalendarTestCase extends TestCase { protected Set<Object> mocks = new HashSet<Object>(); ////// MOCK REGISTRATION AND HANDLING protected <T> T registerMockFor(Class<T> forClass) { return registered(EasyMock.createMock(forClass)); } protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) { return registered(EasyMock.createMock(forClass, methodsToMock)); } protected void replayMocks() { for (Object mock : mocks) EasyMock.replay(mock); } protected void verifyMocks() { for (Object mock : mocks) EasyMock.verify(mock); } protected void resetMocks() { for (Object mock : mocks) EasyMock.reset(mock); } private <T> T registered(T mock) { mocks.add(mock); return mock; } }
package edu.northwestern.bioinformatics.studycalendar.testing; import edu.nwu.bioinformatics.commons.testing.CoreTestCase; import junit.framework.TestCase; import java.lang.reflect.Method; import java.util.Set; import java.util.HashSet; import org.easymock.classextension.EasyMock; /** * @author Rhett Sutphin */ public abstract class StudyCalendarTestCase extends CoreTestCase { protected Set<Object> mocks = new HashSet<Object>(); ////// MOCK REGISTRATION AND HANDLING protected <T> T registerMockFor(Class<T> forClass) { return registered(EasyMock.createMock(forClass)); } protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) { return registered(EasyMock.createMock(forClass, methodsToMock)); } protected void replayMocks() { for (Object mock : mocks) EasyMock.replay(mock); } protected void verifyMocks() { for (Object mock : mocks) EasyMock.verify(mock); } protected void resetMocks() { for (Object mock : mocks) EasyMock.reset(mock); } private <T> T registered(T mock) { mocks.add(mock); return mock; } }
3
1
2
mixed
--- a/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java +++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java @@ -1,2 +1,4 @@ package edu.northwestern.bioinformatics.studycalendar.testing; + +import edu.nwu.bioinformatics.commons.testing.CoreTestCase; @@ -13,3 +15,3 @@ */ -public abstract class StudyCalendarTestCase extends TestCase { +public abstract class StudyCalendarTestCase extends CoreTestCase { protected Set<Object> mocks = new HashSet<Object>();
--- a/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java +++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java @@ ... @@ package edu.northwestern.bioinformatics.studycalendar.testing; + +import edu.nwu.bioinformatics.commons.testing.CoreTestCase; @@ ... @@ */ -public abstract class StudyCalendarTestCase extends TestCase { +public abstract class StudyCalendarTestCase extends CoreTestCase { protected Set<Object> mocks = new HashSet<Object>();
--- a/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java +++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/testing/StudyCalendarTestCase.java @@ -1,2 +1,4 @@ CON package edu.northwestern.bioinformatics.studycalendar.testing; ADD ADD import edu.nwu.bioinformatics.commons.testing.CoreTestCase; CON @@ -13,3 +15,3 @@ CON */ DEL public abstract class StudyCalendarTestCase extends TestCase { ADD public abstract class StudyCalendarTestCase extends CoreTestCase { CON protected Set<Object> mocks = new HashSet<Object>();
<<<<<<< SEARCH package edu.northwestern.bioinformatics.studycalendar.testing; import junit.framework.TestCase; ======= package edu.northwestern.bioinformatics.studycalendar.testing; import edu.nwu.bioinformatics.commons.testing.CoreTestCase; import junit.framework.TestCase; >>>>>>> REPLACE
juanriaza/django-rest-framework-msgpack
62cee7d5a625bb3515eddaddbe940239a41ba31c
rest_framework_msgpack/parsers.py
python
bsd-3-clause
Use six.text_type for python3 compat
import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc))
import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
3
1
2
mixed
--- a/rest_framework_msgpack/parsers.py +++ b/rest_framework_msgpack/parsers.py @@ -3,2 +3,4 @@ from dateutil.parser import parse +from django.utils.six import text_type + @@ -43,2 +45,2 @@ except Exception as exc: - raise ParseError('MessagePack parse error - %s' % unicode(exc)) + raise ParseError('MessagePack parse error - %s' % text_type(exc))
--- a/rest_framework_msgpack/parsers.py +++ b/rest_framework_msgpack/parsers.py @@ ... @@ from dateutil.parser import parse +from django.utils.six import text_type + @@ ... @@ except Exception as exc: - raise ParseError('MessagePack parse error - %s' % unicode(exc)) + raise ParseError('MessagePack parse error - %s' % text_type(exc))
--- a/rest_framework_msgpack/parsers.py +++ b/rest_framework_msgpack/parsers.py @@ -3,2 +3,4 @@ CON from dateutil.parser import parse ADD from django.utils.six import text_type ADD CON @@ -43,2 +45,2 @@ CON except Exception as exc: DEL raise ParseError('MessagePack parse error - %s' % unicode(exc)) ADD raise ParseError('MessagePack parse error - %s' % text_type(exc))
<<<<<<< SEARCH import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser ======= import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser >>>>>>> REPLACE
alphagov/backdrop-transactions-explorer-collector
2efe1364a1e37f06dc26f1a3a122c544437d914e
collector/classes/service.py
python
mit
Add log message if data we can't parse appears If the datum isn't numeric and doesn't match the 'no data' pattern, something has gone horribly wrong.
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def attribute_exists(self, key): return key in self.detailed_data def get_datum(self, key): datum = self.handle_bad_data(self.get(key)) return datum def get(self, key): return self.detailed_data[key] def identifier(self): """Return a unique identifier for the service""" return self.get('Slug') def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr') def handle_bad_data(self, datum): # TODO: Should we be more explicit about non-requested (***) data? if datum == '' or datum == '-' or datum == '***': return None elif not isinstance(datum, (int, long, float, complex)): # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point return None else: return datum
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def attribute_exists(self, key): return key in self.detailed_data def get_datum(self, key): datum = self.handle_bad_data(self.get(key)) return datum def get(self, key): return self.detailed_data[key] def identifier(self): """Return a unique identifier for the service""" return self.get('Slug') def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr') def handle_bad_data(self, datum): # TODO: Should we be more explicit about non-requested (***) data? if datum == '' or datum == '-' or datum == '***': return None elif not isinstance(datum, (int, long, float, complex)): # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None else: return datum
1
0
1
add_only
--- a/collector/classes/service.py +++ b/collector/classes/service.py @@ -42,2 +42,3 @@ # that to Backdrop as a null data point + print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None
--- a/collector/classes/service.py +++ b/collector/classes/service.py @@ ... @@ # that to Backdrop as a null data point + print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None
--- a/collector/classes/service.py +++ b/collector/classes/service.py @@ -42,2 +42,3 @@ CON # that to Backdrop as a null data point ADD print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) CON return None
<<<<<<< SEARCH # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point return None else: ======= # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None else: >>>>>>> REPLACE
kamatama41/embulk-test-helpers
ba5d5a08d3cb7a2e34487761b7e4d2a06441903d
src/main/kotlin/org/embulk/test/Recorder.kt
kotlin
mit
Use hamcrest's assertThat instead of Junit 4's one
package org.embulk.test import org.embulk.spi.Column import org.embulk.spi.PageReader import org.embulk.spi.Schema import org.embulk.spi.util.Pages import org.hamcrest.Matchers.`is` import org.junit.Assert.assertThat /** * Repository of [Record] */ internal class Recorder { private val records = mutableListOf<Record>() private var schema: Schema? = null @Synchronized fun addRecord(reader: PageReader) { val values: MutableList<Any?> = arrayListOf() reader.schema.visitColumns(object : Pages.ObjectColumnVisitor(reader) { override fun visit(column: Column, value: Any?) { values.add(value) } }) this.records.add(Record(values)) } @Synchronized fun setSchema(schema: Schema) { this.schema = schema } @Synchronized fun clear() { this.records.clear() this.schema = null } fun assertRecords(vararg records: Record) { assertThat(this.records.toHashSet(), `is`(records.toHashSet())) } fun assertSchema(vararg columns: Column) { val builder = columns.fold(Schema.builder()) { builder, column -> builder.add(column.name, column.type) } assertThat(builder.build(), `is`(this.schema)) } }
package org.embulk.test import org.embulk.spi.Column import org.embulk.spi.PageReader import org.embulk.spi.Schema import org.embulk.spi.util.Pages import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` /** * Repository of [Record] */ internal class Recorder { private val records = mutableListOf<Record>() private var schema: Schema? = null @Synchronized fun addRecord(reader: PageReader) { val values: MutableList<Any?> = arrayListOf() reader.schema.visitColumns(object : Pages.ObjectColumnVisitor(reader) { override fun visit(column: Column, value: Any?) { values.add(value) } }) this.records.add(Record(values)) } @Synchronized fun setSchema(schema: Schema) { this.schema = schema } @Synchronized fun clear() { this.records.clear() this.schema = null } fun assertRecords(vararg records: Record) { assertThat(this.records.toHashSet(), `is`(records.toHashSet())) } fun assertSchema(vararg columns: Column) { val builder = columns.fold(Schema.builder()) { builder, column -> builder.add(column.name, column.type) } assertThat(builder.build(), `is`(this.schema)) } }
1
2
1
mixed
--- a/src/main/kotlin/org/embulk/test/Recorder.kt +++ b/src/main/kotlin/org/embulk/test/Recorder.kt @@ -6,5 +6,4 @@ import org.embulk.spi.util.Pages - +import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` -import org.junit.Assert.assertThat
--- a/src/main/kotlin/org/embulk/test/Recorder.kt +++ b/src/main/kotlin/org/embulk/test/Recorder.kt @@ ... @@ import org.embulk.spi.util.Pages - +import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` -import org.junit.Assert.assertThat
--- a/src/main/kotlin/org/embulk/test/Recorder.kt +++ b/src/main/kotlin/org/embulk/test/Recorder.kt @@ -6,5 +6,4 @@ CON import org.embulk.spi.util.Pages DEL ADD import org.hamcrest.MatcherAssert.assertThat CON import org.hamcrest.Matchers.`is` DEL import org.junit.Assert.assertThat CON
<<<<<<< SEARCH import org.embulk.spi.Schema import org.embulk.spi.util.Pages import org.hamcrest.Matchers.`is` import org.junit.Assert.assertThat /** ======= import org.embulk.spi.Schema import org.embulk.spi.util.Pages import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` /** >>>>>>> REPLACE
seattletimes/newsapp-template
932999494a4e543c3b7969375194bd1840a7f4b0
root/tasks/connect.js
javascript
mit
Add a filter for case sensitivity @audreycarlsen Let me know if you see this screw anything up for you. It should be relatively stable, but you never know.
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { dev: { options: { livereload: true, base: "./build" } } } }) };
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ var fs = require("fs"); var path = require("path"); module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { dev: { options: { livereload: true, base: "./build", //middleware to protect against case-insensitive file systems middleware: function(connect, options, ware) { var base = options.base.pop(); ware.unshift(function(req, response, next) { var location = path.join(base, req.url); var filename = path.basename(req.url); if (!filename) return next(); var dir = path.dirname(location); fs.readdir(dir, function(err, list) { if (list.indexOf(filename) == -1) { response.statusCode = 404; response.end(); } else { next(); } }) }); return ware; } } } } }) };
23
1
2
mixed
--- a/root/tasks/connect.js +++ b/root/tasks/connect.js @@ -6,2 +6,5 @@ */ + +var fs = require("fs"); +var path = require("path"); @@ -16,3 +19,22 @@ livereload: true, - base: "./build" + base: "./build", + //middleware to protect against case-insensitive file systems + middleware: function(connect, options, ware) { + var base = options.base.pop(); + ware.unshift(function(req, response, next) { + var location = path.join(base, req.url); + var filename = path.basename(req.url); + if (!filename) return next(); + var dir = path.dirname(location); + fs.readdir(dir, function(err, list) { + if (list.indexOf(filename) == -1) { + response.statusCode = 404; + response.end(); + } else { + next(); + } + }) + }); + return ware; + } }
--- a/root/tasks/connect.js +++ b/root/tasks/connect.js @@ ... @@ */ + +var fs = require("fs"); +var path = require("path"); @@ ... @@ livereload: true, - base: "./build" + base: "./build", + //middleware to protect against case-insensitive file systems + middleware: function(connect, options, ware) { + var base = options.base.pop(); + ware.unshift(function(req, response, next) { + var location = path.join(base, req.url); + var filename = path.basename(req.url); + if (!filename) return next(); + var dir = path.dirname(location); + fs.readdir(dir, function(err, list) { + if (list.indexOf(filename) == -1) { + response.statusCode = 404; + response.end(); + } else { + next(); + } + }) + }); + return ware; + } }
--- a/root/tasks/connect.js +++ b/root/tasks/connect.js @@ -6,2 +6,5 @@ CON */ ADD ADD var fs = require("fs"); ADD var path = require("path"); CON @@ -16,3 +19,22 @@ CON livereload: true, DEL base: "./build" ADD base: "./build", ADD //middleware to protect against case-insensitive file systems ADD middleware: function(connect, options, ware) { ADD var base = options.base.pop(); ADD ware.unshift(function(req, response, next) { ADD var location = path.join(base, req.url); ADD var filename = path.basename(req.url); ADD if (!filename) return next(); ADD var dir = path.dirname(location); ADD fs.readdir(dir, function(err, list) { ADD if (list.indexOf(filename) == -1) { ADD response.statusCode = 404; ADD response.end(); ADD } else { ADD next(); ADD } ADD }) ADD }); ADD return ware; ADD } CON }
<<<<<<< SEARCH */ module.exports = function(grunt) { ======= */ var fs = require("fs"); var path = require("path"); module.exports = function(grunt) { >>>>>>> REPLACE
Smile-SA/npmjs-enterprise
fbeaecf0604209e1e2f0eaa722faf83ac53fa7fe
app.js
javascript
apache-2.0
Add trace logs for response duration
'use strict'; var http = require('http'); var config = require('./lib/configLoader'); var urlUtils = require('./lib/urlUtils'); var api = require('./lib/api'); var logger = config.logger; process.on('uncaughtException', function(err) { logger.error('Uncaught exception: %s', JSON.stringify(err, null, 4)); }); api.initChangesSync(); http.createServer(function(req, resp) { try { var isGet = req.method === 'GET'; var module = urlUtils.module(req.url); var tarball = urlUtils.tarball(req.url); if (isGet && tarball) { api.manageAttachment(req, resp, tarball); } else if (isGet && module) { api.manageModule(req, resp, module); } else { api.proxyToCentralRepository(req, resp); } } catch (error) { logger.error(error); } }).listen(config.port, function() { logger.info('Server running at http://localhost:%s with config:\n%s', config.port, JSON.stringify(config, null, 4)); });
'use strict'; var http = require('http'); var config = require('./lib/configLoader'); var urlUtils = require('./lib/urlUtils'); var api = require('./lib/api'); var logger = config.logger; process.on('uncaughtException', function(err) { logger.error('Uncaught exception: %s', JSON.stringify(err, null, 4)); }); api.initChangesSync(); http.createServer(function(req, resp) { try { var startDate = Date.now(); var isGet = req.method === 'GET'; var module = urlUtils.module(req.url); var tarball = urlUtils.tarball(req.url); if (isGet && tarball) { api.manageAttachment(req, resp, tarball); } else if (isGet && module) { api.manageModule(req, resp, module); } else { api.proxyToCentralRepository(req, resp); } resp.on('finish', function() { logger.trace('%s: response in %sms', req.url, Date.now() - startDate); }); } catch (error) { logger.error(error); } }).listen(config.port, function() { logger.info('Server running at http://localhost:%s with config:\n%s', config.port, JSON.stringify(config, null, 4)); });
6
0
2
add_only
--- a/app.js +++ b/app.js @@ -18,2 +18,4 @@ try { + var startDate = Date.now(); + var isGet = req.method === 'GET'; @@ -30,2 +32,6 @@ } + + resp.on('finish', function() { + logger.trace('%s: response in %sms', req.url, Date.now() - startDate); + }); } catch (error) {
--- a/app.js +++ b/app.js @@ ... @@ try { + var startDate = Date.now(); + var isGet = req.method === 'GET'; @@ ... @@ } + + resp.on('finish', function() { + logger.trace('%s: response in %sms', req.url, Date.now() - startDate); + }); } catch (error) {
--- a/app.js +++ b/app.js @@ -18,2 +18,4 @@ CON try { ADD var startDate = Date.now(); ADD CON var isGet = req.method === 'GET'; @@ -30,2 +32,6 @@ CON } ADD ADD resp.on('finish', function() { ADD logger.trace('%s: response in %sms', req.url, Date.now() - startDate); ADD }); CON } catch (error) {
<<<<<<< SEARCH http.createServer(function(req, resp) { try { var isGet = req.method === 'GET'; ======= http.createServer(function(req, resp) { try { var startDate = Date.now(); var isGet = req.method === 'GET'; >>>>>>> REPLACE
Kiskae/DiscordKt
b2413ef564d5b9e8abd5fa75930778830b128b06
api/src/main/kotlin/net/serverpeon/discord/model/Region.kt
kotlin
mit
Add current regions as a static resource
package net.serverpeon.discord.model /** * Represents one of the regions in which a [Guild] may be hosted. */ interface Region { /** * Alphanumeric (with dashes) id representing this region. */ val id: String /** * Approximate continent on which this region exists. */ val continent: Continent enum class Continent { NORTH_AMERICA, SOUTH_AMERICA, // Currently unused EUROPE, ASIA, AUSTRALIA, AFRICA, // Currently unused UNKNOWN } }
package net.serverpeon.discord.model /** * Represents one of the regions in which a [Guild] may be hosted. */ interface Region { /** * Alphanumeric (with dashes) id representing this region. */ val id: String /** * Approximate continent on which this region exists. */ val continent: Continent enum class Continent { NORTH_AMERICA, SOUTH_AMERICA, // Currently unused EUROPE, ASIA, AUSTRALIA, AFRICA, // Currently unused UNKNOWN } /** * Known regions, might change at some point in the future. * * Use [ClientModel.getAvailableServerRegions] to get an up-to-date list. */ enum class KnownRegions(override val id: String, override val continent: Continent) : Region { AMSTERDAM("amsterdam", Continent.EUROPE), LONDON("london", Continent.EUROPE), SINGAPORE("singapore", Continent.ASIA), FRANKFURT("frankfurt", Continent.EUROPE), US_EAST("us-east", Continent.NORTH_AMERICA), US_CENTRAL("us-central", Continent.NORTH_AMERICA), US_SOUTH("us-south", Continent.NORTH_AMERICA), US_WEST("us-west", Continent.NORTH_AMERICA), SYDNEY("sydney", Continent.AUSTRALIA) } }
17
0
1
add_only
--- a/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt +++ b/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt @@ -25,2 +25,19 @@ } + + /** + * Known regions, might change at some point in the future. + * + * Use [ClientModel.getAvailableServerRegions] to get an up-to-date list. + */ + enum class KnownRegions(override val id: String, override val continent: Continent) : Region { + AMSTERDAM("amsterdam", Continent.EUROPE), + LONDON("london", Continent.EUROPE), + SINGAPORE("singapore", Continent.ASIA), + FRANKFURT("frankfurt", Continent.EUROPE), + US_EAST("us-east", Continent.NORTH_AMERICA), + US_CENTRAL("us-central", Continent.NORTH_AMERICA), + US_SOUTH("us-south", Continent.NORTH_AMERICA), + US_WEST("us-west", Continent.NORTH_AMERICA), + SYDNEY("sydney", Continent.AUSTRALIA) + } }
--- a/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt +++ b/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt @@ ... @@ } + + /** + * Known regions, might change at some point in the future. + * + * Use [ClientModel.getAvailableServerRegions] to get an up-to-date list. + */ + enum class KnownRegions(override val id: String, override val continent: Continent) : Region { + AMSTERDAM("amsterdam", Continent.EUROPE), + LONDON("london", Continent.EUROPE), + SINGAPORE("singapore", Continent.ASIA), + FRANKFURT("frankfurt", Continent.EUROPE), + US_EAST("us-east", Continent.NORTH_AMERICA), + US_CENTRAL("us-central", Continent.NORTH_AMERICA), + US_SOUTH("us-south", Continent.NORTH_AMERICA), + US_WEST("us-west", Continent.NORTH_AMERICA), + SYDNEY("sydney", Continent.AUSTRALIA) + } }
--- a/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt +++ b/api/src/main/kotlin/net/serverpeon/discord/model/Region.kt @@ -25,2 +25,19 @@ CON } ADD ADD /** ADD * Known regions, might change at some point in the future. ADD * ADD * Use [ClientModel.getAvailableServerRegions] to get an up-to-date list. ADD */ ADD enum class KnownRegions(override val id: String, override val continent: Continent) : Region { ADD AMSTERDAM("amsterdam", Continent.EUROPE), ADD LONDON("london", Continent.EUROPE), ADD SINGAPORE("singapore", Continent.ASIA), ADD FRANKFURT("frankfurt", Continent.EUROPE), ADD US_EAST("us-east", Continent.NORTH_AMERICA), ADD US_CENTRAL("us-central", Continent.NORTH_AMERICA), ADD US_SOUTH("us-south", Continent.NORTH_AMERICA), ADD US_WEST("us-west", Continent.NORTH_AMERICA), ADD SYDNEY("sydney", Continent.AUSTRALIA) ADD } CON }
<<<<<<< SEARCH UNKNOWN } } ======= UNKNOWN } /** * Known regions, might change at some point in the future. * * Use [ClientModel.getAvailableServerRegions] to get an up-to-date list. */ enum class KnownRegions(override val id: String, override val continent: Continent) : Region { AMSTERDAM("amsterdam", Continent.EUROPE), LONDON("london", Continent.EUROPE), SINGAPORE("singapore", Continent.ASIA), FRANKFURT("frankfurt", Continent.EUROPE), US_EAST("us-east", Continent.NORTH_AMERICA), US_CENTRAL("us-central", Continent.NORTH_AMERICA), US_SOUTH("us-south", Continent.NORTH_AMERICA), US_WEST("us-west", Continent.NORTH_AMERICA), SYDNEY("sydney", Continent.AUSTRALIA) } } >>>>>>> REPLACE
Kotlin/dokka
31d6374cc7101d7dea24defcd1c03e909420ccb6
plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt
kotlin
apache-2.0
Fix junit imports in tests
package locationProvider import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.base.resolvers.local.DefaultLocationProvider import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest import org.junit.Assert.assertNotEquals import org.junit.Test class DefaultLocationProviderTest: AbstractCoreTest() { @Test fun `#644 same directory for module and package`() { val configuration = dokkaConfiguration { passes { pass { sourceRoots = listOf("src/") } } } testInline( """ |/src/main/kotlin/basic/Test.kt | |class Test { | val x = 1 |} """.trimMargin(), configuration ) { var context: DokkaContext? = null pluginsSetupStage = { context = it } pagesGenerationStage = { module -> val lp = DefaultLocationProvider(module, context!!) assertNotEquals(lp.resolve(module.children.single()).removePrefix("/"), lp.resolve(module)) } } } }
package locationProvider import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.base.resolvers.local.DefaultLocationProvider import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test class DefaultLocationProviderTest: AbstractCoreTest() { @Test fun `#644 same directory for module and package`() { val configuration = dokkaConfiguration { passes { pass { sourceRoots = listOf("src/") } } } testInline( """ |/src/main/kotlin/basic/Test.kt | |class Test { | val x = 1 |} """.trimMargin(), configuration ) { var context: DokkaContext? = null pluginsSetupStage = { context = it } pagesGenerationStage = { module -> val lp = DefaultLocationProvider(module, context!!) assertNotEquals(lp.resolve(module.children.single()).removePrefix("/"), lp.resolve(module)) } } } }
2
2
1
mixed
--- a/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt +++ b/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt @@ -5,4 +5,4 @@ import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest -import org.junit.Assert.assertNotEquals -import org.junit.Test +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Test
--- a/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt +++ b/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt @@ ... @@ import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest -import org.junit.Assert.assertNotEquals -import org.junit.Test +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Test
--- a/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt +++ b/plugins/base/src/test/kotlin/locationProvider/DefaultLocationProviderTest.kt @@ -5,4 +5,4 @@ CON import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest DEL import org.junit.Assert.assertNotEquals DEL import org.junit.Test ADD import org.junit.jupiter.api.Assertions.assertNotEquals ADD import org.junit.jupiter.api.Test CON
<<<<<<< SEARCH import org.jetbrains.dokka.base.resolvers.local.DefaultLocationProvider import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest import org.junit.Assert.assertNotEquals import org.junit.Test class DefaultLocationProviderTest: AbstractCoreTest() { ======= import org.jetbrains.dokka.base.resolvers.local.DefaultLocationProvider import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test class DefaultLocationProviderTest: AbstractCoreTest() { >>>>>>> REPLACE
rustoscript/french-press
2d99255b87e36ad057cc94011f1e34ee3f107f59
src/js_types/js_type.rs
rust
mit
Create new enum of all standard JS types
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use uuid::Uuid; pub trait JsTrait {} pub struct JsT { uid: Uuid, t: Box<JsTrait>, } impl JsT { pub fn new(t: Box<JsTrait>) -> JsT { JsT { uid: Uuid::new_v4(), t: t, } } } impl PartialEq for JsT { fn eq(&self, other: &Self) -> bool { self.uid == other.uid } fn ne(&self, other: &Self) -> bool { !self.eq(other) } } impl Eq for JsT {} impl Hash for JsT { fn hash<H>(&self, state: &mut H) where H: Hasher { self.uid.hash(state); } fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher { for ref d in data { d.uid.hash(state); } } }
use std::string::String; use js_types::js_obj::JsObjStruct; use js_types::js_str::JsStrStruct; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use uuid::Uuid; pub struct JsT { pub uuid: Uuid, pub t: JsType, } impl JsT { pub fn new(t: JsType) -> JsT { JsT { uuid: Uuid::new_v4(), t: t, } } } impl PartialEq for JsT { fn eq(&self, other: &Self) -> bool { self.uuid == other.uuid } fn ne(&self, other: &Self) -> bool { !self.eq(other) } } impl Eq for JsT {} impl Hash for JsT { fn hash<H>(&self, state: &mut H) where H: Hasher { self.uuid.hash(state); } fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher { for ref d in data { d.uuid.hash(state); } } } pub enum JsType { JsUndef, JsNull, JsNum(f64), JsSym(String), JsStr(JsStrStruct), JsObj(JsObjStruct), } // `array` pub type JsArr = Vec<JsType>;
21
9
7
mixed
--- a/src/js_types/js_type.rs +++ b/src/js_types/js_type.rs @@ -1 +1,4 @@ +use std::string::String; +use js_types::js_obj::JsObjStruct; +use js_types::js_str::JsStrStruct; use std::cmp::Ordering; @@ -4,7 +7,5 @@ -pub trait JsTrait {} - pub struct JsT { - uid: Uuid, - t: Box<JsTrait>, + pub uuid: Uuid, + pub t: JsType, } @@ -12,5 +13,5 @@ impl JsT { - pub fn new(t: Box<JsTrait>) -> JsT { + pub fn new(t: JsType) -> JsT { JsT { - uid: Uuid::new_v4(), + uuid: Uuid::new_v4(), t: t, @@ -22,3 +23,3 @@ fn eq(&self, other: &Self) -> bool { - self.uid == other.uid + self.uuid == other.uuid } @@ -34,3 +35,3 @@ fn hash<H>(&self, state: &mut H) where H: Hasher { - self.uid.hash(state); + self.uuid.hash(state); } @@ -39,3 +40,3 @@ for ref d in data { - d.uid.hash(state); + d.uuid.hash(state); } @@ -44 +45,12 @@ +pub enum JsType { + JsUndef, + JsNull, + JsNum(f64), + JsSym(String), + JsStr(JsStrStruct), + JsObj(JsObjStruct), +} + +// `array` +pub type JsArr = Vec<JsType>;
--- a/src/js_types/js_type.rs +++ b/src/js_types/js_type.rs @@ ... @@ +use std::string::String; +use js_types::js_obj::JsObjStruct; +use js_types::js_str::JsStrStruct; use std::cmp::Ordering; @@ ... @@ -pub trait JsTrait {} - pub struct JsT { - uid: Uuid, - t: Box<JsTrait>, + pub uuid: Uuid, + pub t: JsType, } @@ ... @@ impl JsT { - pub fn new(t: Box<JsTrait>) -> JsT { + pub fn new(t: JsType) -> JsT { JsT { - uid: Uuid::new_v4(), + uuid: Uuid::new_v4(), t: t, @@ ... @@ fn eq(&self, other: &Self) -> bool { - self.uid == other.uid + self.uuid == other.uuid } @@ ... @@ fn hash<H>(&self, state: &mut H) where H: Hasher { - self.uid.hash(state); + self.uuid.hash(state); } @@ ... @@ for ref d in data { - d.uid.hash(state); + d.uuid.hash(state); } @@ ... @@ +pub enum JsType { + JsUndef, + JsNull, + JsNum(f64), + JsSym(String), + JsStr(JsStrStruct), + JsObj(JsObjStruct), +} + +// `array` +pub type JsArr = Vec<JsType>;
--- a/src/js_types/js_type.rs +++ b/src/js_types/js_type.rs @@ -1 +1,4 @@ ADD use std::string::String; ADD use js_types::js_obj::JsObjStruct; ADD use js_types::js_str::JsStrStruct; CON use std::cmp::Ordering; @@ -4,7 +7,5 @@ CON DEL pub trait JsTrait {} DEL CON pub struct JsT { DEL uid: Uuid, DEL t: Box<JsTrait>, ADD pub uuid: Uuid, ADD pub t: JsType, CON } @@ -12,5 +13,5 @@ CON impl JsT { DEL pub fn new(t: Box<JsTrait>) -> JsT { ADD pub fn new(t: JsType) -> JsT { CON JsT { DEL uid: Uuid::new_v4(), ADD uuid: Uuid::new_v4(), CON t: t, @@ -22,3 +23,3 @@ CON fn eq(&self, other: &Self) -> bool { DEL self.uid == other.uid ADD self.uuid == other.uuid CON } @@ -34,3 +35,3 @@ CON fn hash<H>(&self, state: &mut H) where H: Hasher { DEL self.uid.hash(state); ADD self.uuid.hash(state); CON } @@ -39,3 +40,3 @@ CON for ref d in data { DEL d.uid.hash(state); ADD d.uuid.hash(state); CON } @@ -44 +45,12 @@ CON ADD pub enum JsType { ADD JsUndef, ADD JsNull, ADD JsNum(f64), ADD JsSym(String), ADD JsStr(JsStrStruct), ADD JsObj(JsObjStruct), ADD } ADD ADD // `array` ADD pub type JsArr = Vec<JsType>;
<<<<<<< SEARCH use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use uuid::Uuid; pub trait JsTrait {} pub struct JsT { uid: Uuid, t: Box<JsTrait>, } impl JsT { pub fn new(t: Box<JsTrait>) -> JsT { JsT { uid: Uuid::new_v4(), t: t, } ======= use std::string::String; use js_types::js_obj::JsObjStruct; use js_types::js_str::JsStrStruct; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use uuid::Uuid; pub struct JsT { pub uuid: Uuid, pub t: JsType, } impl JsT { pub fn new(t: JsType) -> JsT { JsT { uuid: Uuid::new_v4(), t: t, } >>>>>>> REPLACE
charlieegan3/graph_match
e6a8f2ce3a6ce3f46b59422f5c942a21d90bd56e
src/edge.rs
rust
mit
Add basic total equality matcher for Edge Fuzzy matcher to come later, which will be more useful.
use std::collections::HashMap; use node; pub type Index = usize; pub struct Edge { pub identifier: String, pub target: node::Index, pub attributes: Option<HashMap<String, String>>, pub next_outgoing_edge: Option<Index>, }
use std::collections::HashMap; use node; pub type Index = usize; pub struct Edge { pub identifier: String, pub target: node::Index, pub attributes: Option<HashMap<String, String>>, pub next_outgoing_edge: Option<Index>, } impl Edge { pub fn equal(&self, edge: Edge) -> bool { self.identifier == edge.identifier && self.attributes == edge.attributes } } #[cfg(test)] mod tests { use std::collections::HashMap; use super::*; #[test] fn edge_equality() { let mut attributes = HashMap::new(); attributes.insert("key".to_string(), "value".to_string()); let mut attributes2 = HashMap::new(); attributes.insert("core".to_string(), "worth".to_string()); let edge0 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes.clone()), next_outgoing_edge: None, target: 0, }; let edge1 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes.clone()), next_outgoing_edge: None, target: 0, }; let edge2 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes2.clone()), next_outgoing_edge: None, target: 0, }; assert!(edge0.equal(edge1)); assert_eq!(edge0.equal(edge2), false); } }
41
0
1
add_only
--- a/src/edge.rs +++ b/src/edge.rs @@ -11 +11,42 @@ } + +impl Edge { + pub fn equal(&self, edge: Edge) -> bool { + self.identifier == edge.identifier && + self.attributes == edge.attributes + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use super::*; + #[test] + fn edge_equality() { + let mut attributes = HashMap::new(); + attributes.insert("key".to_string(), "value".to_string()); + let mut attributes2 = HashMap::new(); + attributes.insert("core".to_string(), "worth".to_string()); + + let edge0 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes.clone()), + next_outgoing_edge: None, + target: 0, + }; + let edge1 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes.clone()), + next_outgoing_edge: None, + target: 0, + }; + let edge2 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes2.clone()), + next_outgoing_edge: None, + target: 0, + }; + assert!(edge0.equal(edge1)); + assert_eq!(edge0.equal(edge2), false); + } +}
--- a/src/edge.rs +++ b/src/edge.rs @@ ... @@ } + +impl Edge { + pub fn equal(&self, edge: Edge) -> bool { + self.identifier == edge.identifier && + self.attributes == edge.attributes + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use super::*; + #[test] + fn edge_equality() { + let mut attributes = HashMap::new(); + attributes.insert("key".to_string(), "value".to_string()); + let mut attributes2 = HashMap::new(); + attributes.insert("core".to_string(), "worth".to_string()); + + let edge0 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes.clone()), + next_outgoing_edge: None, + target: 0, + }; + let edge1 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes.clone()), + next_outgoing_edge: None, + target: 0, + }; + let edge2 = Edge { + identifier: "edgeid".to_string(), + attributes: Some(attributes2.clone()), + next_outgoing_edge: None, + target: 0, + }; + assert!(edge0.equal(edge1)); + assert_eq!(edge0.equal(edge2), false); + } +}
--- a/src/edge.rs +++ b/src/edge.rs @@ -11 +11,42 @@ CON } ADD ADD impl Edge { ADD pub fn equal(&self, edge: Edge) -> bool { ADD self.identifier == edge.identifier && ADD self.attributes == edge.attributes ADD } ADD } ADD ADD #[cfg(test)] ADD mod tests { ADD use std::collections::HashMap; ADD use super::*; ADD #[test] ADD fn edge_equality() { ADD let mut attributes = HashMap::new(); ADD attributes.insert("key".to_string(), "value".to_string()); ADD let mut attributes2 = HashMap::new(); ADD attributes.insert("core".to_string(), "worth".to_string()); ADD ADD let edge0 = Edge { ADD identifier: "edgeid".to_string(), ADD attributes: Some(attributes.clone()), ADD next_outgoing_edge: None, ADD target: 0, ADD }; ADD let edge1 = Edge { ADD identifier: "edgeid".to_string(), ADD attributes: Some(attributes.clone()), ADD next_outgoing_edge: None, ADD target: 0, ADD }; ADD let edge2 = Edge { ADD identifier: "edgeid".to_string(), ADD attributes: Some(attributes2.clone()), ADD next_outgoing_edge: None, ADD target: 0, ADD }; ADD assert!(edge0.equal(edge1)); ADD assert_eq!(edge0.equal(edge2), false); ADD } ADD }
<<<<<<< SEARCH pub next_outgoing_edge: Option<Index>, } ======= pub next_outgoing_edge: Option<Index>, } impl Edge { pub fn equal(&self, edge: Edge) -> bool { self.identifier == edge.identifier && self.attributes == edge.attributes } } #[cfg(test)] mod tests { use std::collections::HashMap; use super::*; #[test] fn edge_equality() { let mut attributes = HashMap::new(); attributes.insert("key".to_string(), "value".to_string()); let mut attributes2 = HashMap::new(); attributes.insert("core".to_string(), "worth".to_string()); let edge0 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes.clone()), next_outgoing_edge: None, target: 0, }; let edge1 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes.clone()), next_outgoing_edge: None, target: 0, }; let edge2 = Edge { identifier: "edgeid".to_string(), attributes: Some(attributes2.clone()), next_outgoing_edge: None, target: 0, }; assert!(edge0.equal(edge1)); assert_eq!(edge0.equal(edge2), false); } } >>>>>>> REPLACE
electerious/Ackee
a65e20f4dc92e9230341fbd65c3bcbdf837881ec
src/database/records.js
javascript
mit
Remove unused fields during anonymization instead of storing null
'use strict' const Record = require('../schemas/Record') const runUpdate = require('../utils/runUpdate') const add = async (data) => { return Record.create(data) } const update = async (id) => { return runUpdate(Record, id) } const anonymize = async (clientId, ignoreId) => { return Record.updateMany({ $and: [ { clientId }, { id: { $ne: ignoreId } } ] }, { clientId: null, siteLanguage: null, screenWidth: null, screenHeight: null, screenColorDepth: null, deviceName: null, deviceManufacturer: null, osName: null, osVersion: null, browserName: null, browserVersion: null, browserWidth: null, browserHeight: null }) } const del = async (domainId) => { return Record.deleteMany({ domainId }) } module.exports = { add, update, anonymize, del }
'use strict' const Record = require('../schemas/Record') const runUpdate = require('../utils/runUpdate') const add = async (data) => { return Record.create(data) } const update = async (id) => { return runUpdate(Record, id) } const anonymize = async (clientId, ignoreId) => { return Record.updateMany({ $and: [ { clientId }, { id: { $ne: ignoreId } } ] }, { clientId: undefined, siteLanguage: undefined, screenWidth: undefined, screenHeight: undefined, screenColorDepth: undefined, deviceName: undefined, deviceManufacturer: undefined, osName: undefined, osVersion: undefined, browserName: undefined, browserVersion: undefined, browserWidth: undefined, browserHeight: undefined }) } const del = async (domainId) => { return Record.deleteMany({ domainId }) } module.exports = { add, update, anonymize, del }
13
13
1
mixed
--- a/src/database/records.js +++ b/src/database/records.js @@ -29,15 +29,15 @@ }, { - clientId: null, - siteLanguage: null, - screenWidth: null, - screenHeight: null, - screenColorDepth: null, - deviceName: null, - deviceManufacturer: null, - osName: null, - osVersion: null, - browserName: null, - browserVersion: null, - browserWidth: null, - browserHeight: null + clientId: undefined, + siteLanguage: undefined, + screenWidth: undefined, + screenHeight: undefined, + screenColorDepth: undefined, + deviceName: undefined, + deviceManufacturer: undefined, + osName: undefined, + osVersion: undefined, + browserName: undefined, + browserVersion: undefined, + browserWidth: undefined, + browserHeight: undefined })
--- a/src/database/records.js +++ b/src/database/records.js @@ ... @@ }, { - clientId: null, - siteLanguage: null, - screenWidth: null, - screenHeight: null, - screenColorDepth: null, - deviceName: null, - deviceManufacturer: null, - osName: null, - osVersion: null, - browserName: null, - browserVersion: null, - browserWidth: null, - browserHeight: null + clientId: undefined, + siteLanguage: undefined, + screenWidth: undefined, + screenHeight: undefined, + screenColorDepth: undefined, + deviceName: undefined, + deviceManufacturer: undefined, + osName: undefined, + osVersion: undefined, + browserName: undefined, + browserVersion: undefined, + browserWidth: undefined, + browserHeight: undefined })
--- a/src/database/records.js +++ b/src/database/records.js @@ -29,15 +29,15 @@ CON }, { DEL clientId: null, DEL siteLanguage: null, DEL screenWidth: null, DEL screenHeight: null, DEL screenColorDepth: null, DEL deviceName: null, DEL deviceManufacturer: null, DEL osName: null, DEL osVersion: null, DEL browserName: null, DEL browserVersion: null, DEL browserWidth: null, DEL browserHeight: null ADD clientId: undefined, ADD siteLanguage: undefined, ADD screenWidth: undefined, ADD screenHeight: undefined, ADD screenColorDepth: undefined, ADD deviceName: undefined, ADD deviceManufacturer: undefined, ADD osName: undefined, ADD osVersion: undefined, ADD browserName: undefined, ADD browserVersion: undefined, ADD browserWidth: undefined, ADD browserHeight: undefined CON })
<<<<<<< SEARCH ] }, { clientId: null, siteLanguage: null, screenWidth: null, screenHeight: null, screenColorDepth: null, deviceName: null, deviceManufacturer: null, osName: null, osVersion: null, browserName: null, browserVersion: null, browserWidth: null, browserHeight: null }) ======= ] }, { clientId: undefined, siteLanguage: undefined, screenWidth: undefined, screenHeight: undefined, screenColorDepth: undefined, deviceName: undefined, deviceManufacturer: undefined, osName: undefined, osVersion: undefined, browserName: undefined, browserVersion: undefined, browserWidth: undefined, browserHeight: undefined }) >>>>>>> REPLACE
moschlar/SAUCE
34e17142f565cfc27c15522212c4240944cb4001
sauce/lib/helpers.py
python
agpl-3.0
Replace my own helper functions with webhelper ones
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from tg import url as tgurl from webhelpers import date, feedgenerator, html, number, misc, text import re, textwrap #log = logging.getLogger(__name__) # shortcut for links link_to = html.tags.link_to def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): '''Return a string representing the timedelta element. Possible format codes are: %D days %h hours %hh hours with leading zero %m minutes %mm minutes with leading zero %s seconds %ss seconds with leading zero ''' totalSeconds = delta.seconds hours, remainder = divmod(totalSeconds, 3600) minutes, seconds = divmod(remainder, 60) result = format.replace('%D', str(delta.days)).\ replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ replace('%ss', '%02d' % seconds).\ replace('%h', str(hours)).replace('%m', str(minutes)).\ replace('%s', str(seconds)) return result def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip() def cut(text, max=200): if len(text) < max: return text else: return textwrap.wrap(text, max)[0] + ' ...'
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from datetime import datetime from tg import url as tgurl #from webhelpers import date, feedgenerator, html, number, misc, text import webhelpers as w from webhelpers.html.tags import link_to from webhelpers.text import truncate from webhelpers.date import distance_of_time_in_words import re #log = logging.getLogger(__name__) cut = lambda text, max=200: truncate(text, max, whole_word=True) strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip()
12
33
4
mixed
--- a/sauce/lib/helpers.py +++ b/sauce/lib/helpers.py @@ -6,6 +6,14 @@ +from datetime import datetime + from tg import url as tgurl -from webhelpers import date, feedgenerator, html, number, misc, text +#from webhelpers import date, feedgenerator, html, number, misc, text -import re, textwrap +import webhelpers as w + +from webhelpers.html.tags import link_to +from webhelpers.text import truncate +from webhelpers.date import distance_of_time_in_words + +import re @@ -13,4 +21,4 @@ -# shortcut for links -link_to = html.tags.link_to +cut = lambda text, max=200: truncate(text, max, whole_word=True) +strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) @@ -19,25 +27,2 @@ -def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): - '''Return a string representing the timedelta element. - - Possible format codes are: - %D days - %h hours - %hh hours with leading zero - %m minutes - %mm minutes with leading zero - %s seconds - %ss seconds with leading zero - ''' - totalSeconds = delta.seconds - hours, remainder = divmod(totalSeconds, 3600) - minutes, seconds = divmod(remainder, 60) - - result = format.replace('%D', str(delta.days)).\ - replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ - replace('%ss', '%02d' % seconds).\ - replace('%h', str(hours)).replace('%m', str(minutes)).\ - replace('%s', str(seconds)) - return result - def striphtml(text): @@ -45,7 +30 @@ -def cut(text, max=200): - if len(text) < max: - return text - else: - return textwrap.wrap(text, max)[0] + ' ...' -
--- a/sauce/lib/helpers.py +++ b/sauce/lib/helpers.py @@ ... @@ +from datetime import datetime + from tg import url as tgurl -from webhelpers import date, feedgenerator, html, number, misc, text +#from webhelpers import date, feedgenerator, html, number, misc, text -import re, textwrap +import webhelpers as w + +from webhelpers.html.tags import link_to +from webhelpers.text import truncate +from webhelpers.date import distance_of_time_in_words + +import re @@ ... @@ -# shortcut for links -link_to = html.tags.link_to +cut = lambda text, max=200: truncate(text, max, whole_word=True) +strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) @@ ... @@ -def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): - '''Return a string representing the timedelta element. - - Possible format codes are: - %D days - %h hours - %hh hours with leading zero - %m minutes - %mm minutes with leading zero - %s seconds - %ss seconds with leading zero - ''' - totalSeconds = delta.seconds - hours, remainder = divmod(totalSeconds, 3600) - minutes, seconds = divmod(remainder, 60) - - result = format.replace('%D', str(delta.days)).\ - replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ - replace('%ss', '%02d' % seconds).\ - replace('%h', str(hours)).replace('%m', str(minutes)).\ - replace('%s', str(seconds)) - return result - def striphtml(text): @@ ... @@ -def cut(text, max=200): - if len(text) < max: - return text - else: - return textwrap.wrap(text, max)[0] + ' ...' -
--- a/sauce/lib/helpers.py +++ b/sauce/lib/helpers.py @@ -6,6 +6,14 @@ CON ADD from datetime import datetime ADD CON from tg import url as tgurl DEL from webhelpers import date, feedgenerator, html, number, misc, text ADD #from webhelpers import date, feedgenerator, html, number, misc, text CON DEL import re, textwrap ADD import webhelpers as w ADD ADD from webhelpers.html.tags import link_to ADD from webhelpers.text import truncate ADD from webhelpers.date import distance_of_time_in_words ADD ADD import re CON @@ -13,4 +21,4 @@ CON DEL # shortcut for links DEL link_to = html.tags.link_to ADD cut = lambda text, max=200: truncate(text, max, whole_word=True) ADD strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) CON @@ -19,25 +27,2 @@ CON DEL def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): DEL '''Return a string representing the timedelta element. DEL DEL Possible format codes are: DEL %D days DEL %h hours DEL %hh hours with leading zero DEL %m minutes DEL %mm minutes with leading zero DEL %s seconds DEL %ss seconds with leading zero DEL ''' DEL totalSeconds = delta.seconds DEL hours, remainder = divmod(totalSeconds, 3600) DEL minutes, seconds = divmod(remainder, 60) DEL DEL result = format.replace('%D', str(delta.days)).\ DEL replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ DEL replace('%ss', '%02d' % seconds).\ DEL replace('%h', str(hours)).replace('%m', str(minutes)).\ DEL replace('%s', str(seconds)) DEL return result DEL CON def striphtml(text): @@ -45,7 +30 @@ CON DEL def cut(text, max=200): DEL if len(text) < max: DEL return text DEL else: DEL return textwrap.wrap(text, max)[0] + ' ...' DEL
<<<<<<< SEARCH """ from tg import url as tgurl from webhelpers import date, feedgenerator, html, number, misc, text import re, textwrap #log = logging.getLogger(__name__) # shortcut for links link_to = html.tags.link_to def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): '''Return a string representing the timedelta element. Possible format codes are: %D days %h hours %hh hours with leading zero %m minutes %mm minutes with leading zero %s seconds %ss seconds with leading zero ''' totalSeconds = delta.seconds hours, remainder = divmod(totalSeconds, 3600) minutes, seconds = divmod(remainder, 60) result = format.replace('%D', str(delta.days)).\ replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ replace('%ss', '%02d' % seconds).\ replace('%h', str(hours)).replace('%m', str(minutes)).\ replace('%s', str(seconds)) return result def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip() def cut(text, max=200): if len(text) < max: return text else: return textwrap.wrap(text, max)[0] + ' ...' ======= """ from datetime import datetime from tg import url as tgurl #from webhelpers import date, feedgenerator, html, number, misc, text import webhelpers as w from webhelpers.html.tags import link_to from webhelpers.text import truncate from webhelpers.date import distance_of_time_in_words import re #log = logging.getLogger(__name__) cut = lambda text, max=200: truncate(text, max, whole_word=True) strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip() >>>>>>> REPLACE
hackclub/api
a89048f681406a4c3f3507118b73eee129d8e8b3
frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js
javascript
mit
Fix workshop loading spinner not showing properly
import React, { Component } from 'react' import Radium from 'radium' import Helmet from 'react-helmet' import Axios from 'axios' import { NavBar, LoadingSpinner } from '../../components' import { NotFound } from '../../containers' const baseUrl = 'https://api.hackclub.com/v1/workshops/' class WorkshopWrapper extends Component { constructor(props) { super(props) Axios.get(baseUrl + (props.routeParams.splat || '')) .then(resp => { this.setState({ workshopContent: resp.data, }) }) .catch(e => { console.log(e) this.setState({ notFound: true }) }) } getInitialState() { return { notFound: false, } } createWorkshop() { return {__html: this.state.workshopContent} } content() { if (this.state.notFound === undefined) { return <LoadingSpinner /> } else if(this.state.notFound === false) { return <div dangerouslySetInnerHTML={this.createWorkshop()} /> } else { return <NotFound /> } } render() { return( <div> <Helmet title={this.state.path || 'Workshops'} /> <NavBar /> {this.content()} </div> ) } } export default Radium(WorkshopWrapper)
import React, { Component } from 'react' import Radium from 'radium' import Helmet from 'react-helmet' import Axios from 'axios' import { NavBar, LoadingSpinner } from '../../components' import { NotFound } from '../../containers' const baseUrl = 'https://api.hackclub.com/v1/workshops/' class WorkshopWrapper extends Component { constructor(props) { super(props) Axios.get(baseUrl + (props.routeParams.splat || '')) .then(resp => { this.setState({ notFound: false, workshopContent: resp.data }) }) .catch(e => { console.log(e) this.setState({ notFound: true }) }) } getInitialState() { return { notFound: null } } createWorkshop() { return {__html: this.state.workshopContent} } content() { if (this.state.notFound === null) { return <LoadingSpinner /> } else if(this.state.notFound === false) { return <div dangerouslySetInnerHTML={this.createWorkshop()} /> } else { return <NotFound /> } } render() { return( <div> <Helmet title={this.state.path || 'Workshops'} /> <NavBar /> {this.content()} </div> ) } } export default Radium(WorkshopWrapper)
5
4
3
mixed
--- a/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js +++ b/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js @@ -15,3 +15,4 @@ this.setState({ - workshopContent: resp.data, + notFound: false, + workshopContent: resp.data }) @@ -28,5 +29,5 @@ return { - notFound: false, + notFound: null } - } + } @@ -37,3 +38,3 @@ content() { - if (this.state.notFound === undefined) { + if (this.state.notFound === null) { return <LoadingSpinner />
--- a/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js +++ b/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js @@ ... @@ this.setState({ - workshopContent: resp.data, + notFound: false, + workshopContent: resp.data }) @@ ... @@ return { - notFound: false, + notFound: null } - } + } @@ ... @@ content() { - if (this.state.notFound === undefined) { + if (this.state.notFound === null) { return <LoadingSpinner />
--- a/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js +++ b/frontend/src/containers/WorkshopWrapper/WorkshopWrapper.js @@ -15,3 +15,4 @@ CON this.setState({ DEL workshopContent: resp.data, ADD notFound: false, ADD workshopContent: resp.data CON }) @@ -28,5 +29,5 @@ CON return { DEL notFound: false, ADD notFound: null CON } DEL } ADD } CON @@ -37,3 +38,3 @@ CON content() { DEL if (this.state.notFound === undefined) { ADD if (this.state.notFound === null) { CON return <LoadingSpinner />
<<<<<<< SEARCH .then(resp => { this.setState({ workshopContent: resp.data, }) }) ======= .then(resp => { this.setState({ notFound: false, workshopContent: resp.data }) }) >>>>>>> REPLACE
edaubert/jongo
cc117347141410dbf569d6b8b3be6eec379301f6
src/main/java/org/jongo/bson/RelaxedLazyDBObject.java
java
apache-2.0
Remove the use of a protected deprecated field
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jongo.bson; import com.mongodb.DBObject; import com.mongodb.LazyDBObject; import org.bson.LazyBSONCallback; class RelaxedLazyDBObject extends LazyDBObject implements BsonDocument { public RelaxedLazyDBObject(byte[] data, LazyBSONCallback cbk) { super(data, cbk); } public byte[] toByteArray() { return _input.array(); } public DBObject toDBObject() { return this; } public int getSize() { return getBSONSize(); } }
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jongo.bson; import com.mongodb.DBObject; import com.mongodb.LazyDBObject; import org.bson.LazyBSONCallback; class RelaxedLazyDBObject extends LazyDBObject implements BsonDocument { public RelaxedLazyDBObject(byte[] data, LazyBSONCallback cbk) { super(data, cbk); } public byte[] toByteArray() { return getBytes(); } public DBObject toDBObject() { return this; } public int getSize() { return getBSONSize(); } }
1
1
1
mixed
--- a/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java +++ b/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java @@ -29,3 +29,3 @@ public byte[] toByteArray() { - return _input.array(); + return getBytes(); }
--- a/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java +++ b/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java @@ ... @@ public byte[] toByteArray() { - return _input.array(); + return getBytes(); }
--- a/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java +++ b/src/main/java/org/jongo/bson/RelaxedLazyDBObject.java @@ -29,3 +29,3 @@ CON public byte[] toByteArray() { DEL return _input.array(); ADD return getBytes(); CON }
<<<<<<< SEARCH public byte[] toByteArray() { return _input.array(); } ======= public byte[] toByteArray() { return getBytes(); } >>>>>>> REPLACE
hoangpham95/react-native
2dc559d1fbab7434d61df62936be11434d6f7f91
babel-preset/lib/resolvePlugins.js
javascript
bsd-3-clause
Add possibility to add custom plugin prefix Summary: The problem with a fixed prefix is that babel 7 uses a scoped packages and every (standard) plugin is now part of that scope so the prefix is no longer `babel-plugin-` but instead `babel/plugin-`. There are more changes. This one will at least fix most of them. Reviewed By: davidaurelio Differential Revision: D7085102 fbshipit-source-id: b927998c611b71b3265e1cb3f6df537b14f9cb25
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /** * Manually resolve all default Babel plugins. * `babel.transform` will attempt to resolve all base plugins relative to * the file it's compiling. This makes sure that we're using the plugins * installed in the react-native package. */ function resolvePlugins(plugins) { return plugins.map(resolvePlugin); } /** * Manually resolve a single Babel plugin. */ function resolvePlugin(plugin) { // Normalise plugin to an array. if (!Array.isArray(plugin)) { plugin = [plugin]; } // Only resolve the plugin if it's a string reference. if (typeof plugin[0] === 'string') { plugin[0] = require('babel-plugin-' + plugin[0]); plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0]; } return plugin; } module.exports = resolvePlugins; module.exports.resolvePlugin = resolvePlugin;
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ 'use strict'; /** * Manually resolve all default Babel plugins. * `babel.transform` will attempt to resolve all base plugins relative to * the file it's compiling. This makes sure that we're using the plugins * installed in the react-native package. */ function resolvePlugins(plugins, prefix) { return plugins.map(plugin => resolvePlugin(plugin, prefix)); } /** * Manually resolve a single Babel plugin. */ function resolvePlugin(plugin, prefix = 'babel-plugin-') { // Normalise plugin to an array. if (!Array.isArray(plugin)) { plugin = [plugin]; } // Only resolve the plugin if it's a string reference. if (typeof plugin[0] === 'string') { plugin[0] = require(prefix + plugin[0]); plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0]; } return plugin; } module.exports = resolvePlugins; module.exports.resolvePlugin = resolvePlugin; module.exports.resolvePluginAs = (prefix, plugin) => resolvePlugin(plugin, prefix); module.exports.resolvePluginsAs = (prefix, plugins) => resolvePlugins(plugins, prefix);
10
4
5
mixed
--- a/babel-preset/lib/resolvePlugins.js +++ b/babel-preset/lib/resolvePlugins.js @@ -5,2 +5,4 @@ * LICENSE file in the root directory of this source tree. + * + * @format */ @@ -14,4 +16,4 @@ */ -function resolvePlugins(plugins) { - return plugins.map(resolvePlugin); +function resolvePlugins(plugins, prefix) { + return plugins.map(plugin => resolvePlugin(plugin, prefix)); } @@ -21,3 +23,3 @@ */ -function resolvePlugin(plugin) { +function resolvePlugin(plugin, prefix = 'babel-plugin-') { // Normalise plugin to an array. @@ -28,3 +30,3 @@ if (typeof plugin[0] === 'string') { - plugin[0] = require('babel-plugin-' + plugin[0]); + plugin[0] = require(prefix + plugin[0]); plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0]; @@ -36 +38,5 @@ module.exports.resolvePlugin = resolvePlugin; +module.exports.resolvePluginAs = (prefix, plugin) => + resolvePlugin(plugin, prefix); +module.exports.resolvePluginsAs = (prefix, plugins) => + resolvePlugins(plugins, prefix);
--- a/babel-preset/lib/resolvePlugins.js +++ b/babel-preset/lib/resolvePlugins.js @@ ... @@ * LICENSE file in the root directory of this source tree. + * + * @format */ @@ ... @@ */ -function resolvePlugins(plugins) { - return plugins.map(resolvePlugin); +function resolvePlugins(plugins, prefix) { + return plugins.map(plugin => resolvePlugin(plugin, prefix)); } @@ ... @@ */ -function resolvePlugin(plugin) { +function resolvePlugin(plugin, prefix = 'babel-plugin-') { // Normalise plugin to an array. @@ ... @@ if (typeof plugin[0] === 'string') { - plugin[0] = require('babel-plugin-' + plugin[0]); + plugin[0] = require(prefix + plugin[0]); plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0]; @@ ... @@ module.exports.resolvePlugin = resolvePlugin; +module.exports.resolvePluginAs = (prefix, plugin) => + resolvePlugin(plugin, prefix); +module.exports.resolvePluginsAs = (prefix, plugins) => + resolvePlugins(plugins, prefix);
--- a/babel-preset/lib/resolvePlugins.js +++ b/babel-preset/lib/resolvePlugins.js @@ -5,2 +5,4 @@ CON * LICENSE file in the root directory of this source tree. ADD * ADD * @format CON */ @@ -14,4 +16,4 @@ CON */ DEL function resolvePlugins(plugins) { DEL return plugins.map(resolvePlugin); ADD function resolvePlugins(plugins, prefix) { ADD return plugins.map(plugin => resolvePlugin(plugin, prefix)); CON } @@ -21,3 +23,3 @@ CON */ DEL function resolvePlugin(plugin) { ADD function resolvePlugin(plugin, prefix = 'babel-plugin-') { CON // Normalise plugin to an array. @@ -28,3 +30,3 @@ CON if (typeof plugin[0] === 'string') { DEL plugin[0] = require('babel-plugin-' + plugin[0]); ADD plugin[0] = require(prefix + plugin[0]); CON plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0]; @@ -36 +38,5 @@ CON module.exports.resolvePlugin = resolvePlugin; ADD module.exports.resolvePluginAs = (prefix, plugin) => ADD resolvePlugin(plugin, prefix); ADD module.exports.resolvePluginsAs = (prefix, plugins) => ADD resolvePlugins(plugins, prefix);
<<<<<<< SEARCH * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; ======= * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ 'use strict'; >>>>>>> REPLACE
esofthead/mycollab
ffd9dd315370e2a084a902f050dfa9061a43ded9
mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt
kotlin
agpl-3.0
Update the correct reset password servlet
/** * Copyright © MyCollab * * * 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:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.billing.servlet import org.springframework.boot.web.servlet.ServletRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration /** * @author MyCollab Ltd * @since 5.5.0 */ @Configuration class BillingSpringServletRegistrator { @Bean("confirmEmailServlet") fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*") @Bean("resetPasswordServlet") fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordServlet") fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") }
/** * Copyright © MyCollab * * * 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:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.billing.servlet import org.springframework.boot.web.servlet.ServletRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration /** * @author MyCollab Ltd * @since 5.5.0 */ @Configuration class BillingSpringServletRegistrator { @Bean("confirmEmailServlet") fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*") @Bean("resetPasswordServlet") fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordPageServlet") fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*") }
2
2
1
mixed
--- a/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt +++ b/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt @@ -39,4 +39,4 @@ - @Bean("resetPasswordServlet") - fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") + @Bean("resetPasswordPageServlet") + fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*") }
--- a/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt +++ b/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt @@ ... @@ - @Bean("resetPasswordServlet") - fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") + @Bean("resetPasswordPageServlet") + fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*") }
--- a/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt +++ b/mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt @@ -39,4 +39,4 @@ CON DEL @Bean("resetPasswordServlet") DEL fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") ADD @Bean("resetPasswordPageServlet") ADD fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*") CON }
<<<<<<< SEARCH fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordServlet") fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") } ======= fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordPageServlet") fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*") } >>>>>>> REPLACE
corbt/react-native-keep-awake
94e543fae61f6380360279383010da0f5ac806a3
android/src/main/java/com/corbt/keepawake/KCKeepAwake.java
java
mit
Check is activity is null
// Adapted from // https://github.com/gijoehosaphat/react-native-keep-screen-on package com.corbt.keepawake; import android.app.Activity; import android.view.WindowManager; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; public class KCKeepAwake extends ReactContextBaseJavaModule { public KCKeepAwake(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "KCKeepAwake"; } @ReactMethod public void activate() { final Activity activity = getCurrentActivity(); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } @ReactMethod public void deactivate() { final Activity activity = getCurrentActivity(); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } }
// Adapted from // https://github.com/gijoehosaphat/react-native-keep-screen-on package com.corbt.keepawake; import android.app.Activity; import android.view.WindowManager; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; public class KCKeepAwake extends ReactContextBaseJavaModule { public KCKeepAwake(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "KCKeepAwake"; } @ReactMethod public void activate() { final Activity activity = getCurrentActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } @ReactMethod public void deactivate() { final Activity activity = getCurrentActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } }
18
12
2
mixed
--- a/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java +++ b/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java @@ -26,8 +26,11 @@ final Activity activity = getCurrentActivity(); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - }); + + if (activity != null) { + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + }); + } } @@ -37,8 +40,11 @@ final Activity activity = getCurrentActivity(); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - }); + + if (activity != null) { + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + }); + } }
--- a/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java +++ b/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java @@ ... @@ final Activity activity = getCurrentActivity(); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - }); + + if (activity != null) { + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + }); + } } @@ ... @@ final Activity activity = getCurrentActivity(); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - }); + + if (activity != null) { + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + }); + } }
--- a/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java +++ b/android/src/main/java/com/corbt/keepawake/KCKeepAwake.java @@ -26,8 +26,11 @@ CON final Activity activity = getCurrentActivity(); DEL activity.runOnUiThread(new Runnable() { DEL @Override DEL public void run() { DEL activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); DEL } DEL }); ADD ADD if (activity != null) { ADD activity.runOnUiThread(new Runnable() { ADD @Override ADD public void run() { ADD activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ADD } ADD }); ADD } CON } @@ -37,8 +40,11 @@ CON final Activity activity = getCurrentActivity(); DEL activity.runOnUiThread(new Runnable() { DEL @Override DEL public void run() { DEL activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); DEL } DEL }); ADD ADD if (activity != null) { ADD activity.runOnUiThread(new Runnable() { ADD @Override ADD public void run() { ADD activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ADD } ADD }); ADD } CON }
<<<<<<< SEARCH public void activate() { final Activity activity = getCurrentActivity(); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } @ReactMethod public void deactivate() { final Activity activity = getCurrentActivity(); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } ======= public void activate() { final Activity activity = getCurrentActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } @ReactMethod public void deactivate() { final Activity activity = getCurrentActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } } >>>>>>> REPLACE
Haehnchen/idea-php-laravel-plugin
ad38b2042a6b9035162ee029be6d46e6132bd8e2
src/main/java/de/espend/idea/laravel/LaravelSettings.java
java
mit
Remove removed id property from storage annotation
package de.espend.idea.laravel; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.util.xmlb.XmlSerializerUtil; import de.espend.idea.laravel.view.dict.TemplatePath; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * @author Daniel Espendiller <[email protected]> */ @State( name = "LaravelPluginSettings", storages = { @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) public class LaravelSettings implements PersistentStateComponent<LaravelSettings> { public boolean pluginEnabled = false; public boolean useAutoPopup = false; public String routerNamespace; public String mainLanguage; @Nullable public List<TemplatePath> templatePaths = new ArrayList<>(); public boolean dismissEnableNotification = false; public static LaravelSettings getInstance(Project project) { return ServiceManager.getService(project, LaravelSettings.class); } public String getMainLanguage() { return !StringUtils.isBlank(mainLanguage) ? mainLanguage : "en"; } @Nullable @Override public LaravelSettings getState() { return this; } @Override public void loadState(LaravelSettings settings) { XmlSerializerUtil.copyBean(settings, this); } }
package de.espend.idea.laravel; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.util.xmlb.XmlSerializerUtil; import de.espend.idea.laravel.view.dict.TemplatePath; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * @author Daniel Espendiller <[email protected]> */ @State( name = "LaravelPluginSettings", storages = { @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) public class LaravelSettings implements PersistentStateComponent<LaravelSettings> { public boolean pluginEnabled = false; public boolean useAutoPopup = false; public String routerNamespace; public String mainLanguage; @Nullable public List<TemplatePath> templatePaths = new ArrayList<>(); public boolean dismissEnableNotification = false; public static LaravelSettings getInstance(Project project) { return ServiceManager.getService(project, LaravelSettings.class); } public String getMainLanguage() { return !StringUtils.isBlank(mainLanguage) ? mainLanguage : "en"; } @Nullable @Override public LaravelSettings getState() { return this; } @Override public void loadState(LaravelSettings settings) { XmlSerializerUtil.copyBean(settings, this); } }
2
2
1
mixed
--- a/src/main/java/de/espend/idea/laravel/LaravelSettings.java +++ b/src/main/java/de/espend/idea/laravel/LaravelSettings.java @@ -18,4 +18,4 @@ storages = { - @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), - @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) + @Storage(file = StoragePathMacros.PROJECT_FILE), + @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) }
--- a/src/main/java/de/espend/idea/laravel/LaravelSettings.java +++ b/src/main/java/de/espend/idea/laravel/LaravelSettings.java @@ ... @@ storages = { - @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), - @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) + @Storage(file = StoragePathMacros.PROJECT_FILE), + @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) }
--- a/src/main/java/de/espend/idea/laravel/LaravelSettings.java +++ b/src/main/java/de/espend/idea/laravel/LaravelSettings.java @@ -18,4 +18,4 @@ CON storages = { DEL @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), DEL @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) ADD @Storage(file = StoragePathMacros.PROJECT_FILE), ADD @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) CON }
<<<<<<< SEARCH name = "LaravelPluginSettings", storages = { @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) ======= name = "LaravelPluginSettings", storages = { @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/laravel-plugin.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) >>>>>>> REPLACE
jillix/captcha
2a6d98dd0f760c658f85c1895c6897459e163d34
server/operations.js
javascript
mit
Set the number in sessions and correclty compare the values
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer === sessions[sid]); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); if (!link.session || !link.session._sid) { sessions[link.session._sid] = number; } var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); cap.color(0, 100, 0, 0); cap.color(80, 80, 80, 255); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer.toString() === sessions[sid].toString()); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); var sid = link.session && link.session._sid; sessions[sid] = number; var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); cap.color(0, 100, 0, 0); cap.color(80, 80, 80, 255); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
3
4
2
mixed
--- a/server/operations.js +++ b/server/operations.js @@ -20,3 +20,3 @@ var sid = link.session && link.session._sid; - callback(answer === sessions[sid]); + callback(answer.toString() === sessions[sid].toString()); }); @@ -38,5 +38,4 @@ var number = parseInt(Math.random() * 9000 + 1000); - if (!link.session || !link.session._sid) { - sessions[link.session._sid] = number; - } + var sid = link.session && link.session._sid; + sessions[sid] = number;
--- a/server/operations.js +++ b/server/operations.js @@ ... @@ var sid = link.session && link.session._sid; - callback(answer === sessions[sid]); + callback(answer.toString() === sessions[sid].toString()); }); @@ ... @@ var number = parseInt(Math.random() * 9000 + 1000); - if (!link.session || !link.session._sid) { - sessions[link.session._sid] = number; - } + var sid = link.session && link.session._sid; + sessions[sid] = number;
--- a/server/operations.js +++ b/server/operations.js @@ -20,3 +20,3 @@ CON var sid = link.session && link.session._sid; DEL callback(answer === sessions[sid]); ADD callback(answer.toString() === sessions[sid].toString()); CON }); @@ -38,5 +38,4 @@ CON var number = parseInt(Math.random() * 9000 + 1000); DEL if (!link.session || !link.session._sid) { DEL sessions[link.session._sid] = number; DEL } ADD var sid = link.session && link.session._sid; ADD sessions[sid] = number; CON
<<<<<<< SEARCH M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer === sessions[sid]); }); ======= M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer.toString() === sessions[sid].toString()); }); >>>>>>> REPLACE
z-------------/cumulonimbus
de50ca7233167afbbdf0c6d01fab90b2d771e4f4
test/ui.js
javascript
apache-2.0
Make the tab nav test actually test something
const { expect } = require("chai") const path = require("path") const Application = require("spectron").Application describe("ui", function () { this.timeout(10000) console.log(require("electron"), __dirname, path.join(__dirname, "..", "main.js")) beforeEach(function () { this.app = new Application({ path: require("electron"), args: [path.join(__dirname, "..", "main.js")] }) return this.app.start() }) afterEach(function () { if (this.app && this.app.isRunning()) { return this.app.stop() } }) it("shows an initial window", function() { return this.app.client.getWindowCount().then(function(windowCount) { expect(windowCount).to.equal(1) }) }) it("tab navigation works", function() { this.app.webContents.on("did-finish-load", function(event) { let client = this.app.client client.element(".header_nav a:nth-child(2)").click() let classesFirst = client.getAttribute(".content-container .content:nth-of-type(1)", "class").split(" ") let classesSecond = client.getAttribute(".content-container .content:nth-of-type(2)", "class").split(" ") expect(classesFirst).to.not.include("current") expect(classesFirst).to.include("left") expect(classesSecond).to.not.include("right") expect(classesSecond).to.include("current") }) }) })
const { expect } = require("chai") const path = require("path") const Application = require("spectron").Application describe("ui", function() { this.timeout(10000) console.log(require("electron"), __dirname, path.join(__dirname, "..", "main.js")) beforeEach(function() { this.app = new Application({ path: require("electron"), args: [path.join(__dirname, "..", "main.js")] }) return this.app.start() }) afterEach(function() { if (this.app && this.app.isRunning()) { return this.app.stop() } }) it("should show an initial window", function() { return this.app.client.getWindowCount().then(function(windowCount) { expect(windowCount).to.equal(1) }) }) it("tab navigation should work", function(done) { let client = this.app.client; client.element(".header_nav a:nth-child(2)").click() client.getAttribute(".content-container .content:nth-of-type(1)", "class").then(classesFirstStr => { var classesFirst = classesFirstStr.split(" ") client.getAttribute(".content-container .content:nth-of-type(2)", "class").then(classesSecondStr => { var classesSecond = classesSecondStr.split(" ") expect(classesFirst).to.not.include("current") expect(classesFirst).to.include("left") expect(classesSecond).to.not.include("right") expect(classesSecond).to.include("current") done() }) }) }) })
20
14
5
mixed
--- a/test/ui.js +++ b/test/ui.js @@ -5,3 +5,3 @@ -describe("ui", function () { +describe("ui", function() { this.timeout(10000) @@ -10,3 +10,3 @@ - beforeEach(function () { + beforeEach(function() { this.app = new Application({ @@ -18,3 +18,3 @@ - afterEach(function () { + afterEach(function() { if (this.app && this.app.isRunning()) { @@ -24,3 +24,3 @@ - it("shows an initial window", function() { + it("should show an initial window", function() { return this.app.client.getWindowCount().then(function(windowCount) { @@ -30,13 +30,19 @@ - it("tab navigation works", function() { - this.app.webContents.on("did-finish-load", function(event) { - let client = this.app.client - client.element(".header_nav a:nth-child(2)").click() - let classesFirst = client.getAttribute(".content-container .content:nth-of-type(1)", "class").split(" ") - let classesSecond = client.getAttribute(".content-container .content:nth-of-type(2)", "class").split(" ") - expect(classesFirst).to.not.include("current") - expect(classesFirst).to.include("left") - expect(classesSecond).to.not.include("right") - expect(classesSecond).to.include("current") + it("tab navigation should work", function(done) { + let client = this.app.client; + + client.element(".header_nav a:nth-child(2)").click() + client.getAttribute(".content-container .content:nth-of-type(1)", "class").then(classesFirstStr => { + var classesFirst = classesFirstStr.split(" ") + client.getAttribute(".content-container .content:nth-of-type(2)", "class").then(classesSecondStr => { + var classesSecond = classesSecondStr.split(" ") + + expect(classesFirst).to.not.include("current") + expect(classesFirst).to.include("left") + expect(classesSecond).to.not.include("right") + expect(classesSecond).to.include("current") + done() + }) }) + })
--- a/test/ui.js +++ b/test/ui.js @@ ... @@ -describe("ui", function () { +describe("ui", function() { this.timeout(10000) @@ ... @@ - beforeEach(function () { + beforeEach(function() { this.app = new Application({ @@ ... @@ - afterEach(function () { + afterEach(function() { if (this.app && this.app.isRunning()) { @@ ... @@ - it("shows an initial window", function() { + it("should show an initial window", function() { return this.app.client.getWindowCount().then(function(windowCount) { @@ ... @@ - it("tab navigation works", function() { - this.app.webContents.on("did-finish-load", function(event) { - let client = this.app.client - client.element(".header_nav a:nth-child(2)").click() - let classesFirst = client.getAttribute(".content-container .content:nth-of-type(1)", "class").split(" ") - let classesSecond = client.getAttribute(".content-container .content:nth-of-type(2)", "class").split(" ") - expect(classesFirst).to.not.include("current") - expect(classesFirst).to.include("left") - expect(classesSecond).to.not.include("right") - expect(classesSecond).to.include("current") + it("tab navigation should work", function(done) { + let client = this.app.client; + + client.element(".header_nav a:nth-child(2)").click() + client.getAttribute(".content-container .content:nth-of-type(1)", "class").then(classesFirstStr => { + var classesFirst = classesFirstStr.split(" ") + client.getAttribute(".content-container .content:nth-of-type(2)", "class").then(classesSecondStr => { + var classesSecond = classesSecondStr.split(" ") + + expect(classesFirst).to.not.include("current") + expect(classesFirst).to.include("left") + expect(classesSecond).to.not.include("right") + expect(classesSecond).to.include("current") + done() + }) }) + })
--- a/test/ui.js +++ b/test/ui.js @@ -5,3 +5,3 @@ CON DEL describe("ui", function () { ADD describe("ui", function() { CON this.timeout(10000) @@ -10,3 +10,3 @@ CON DEL beforeEach(function () { ADD beforeEach(function() { CON this.app = new Application({ @@ -18,3 +18,3 @@ CON DEL afterEach(function () { ADD afterEach(function() { CON if (this.app && this.app.isRunning()) { @@ -24,3 +24,3 @@ CON DEL it("shows an initial window", function() { ADD it("should show an initial window", function() { CON return this.app.client.getWindowCount().then(function(windowCount) { @@ -30,13 +30,19 @@ CON DEL it("tab navigation works", function() { DEL this.app.webContents.on("did-finish-load", function(event) { DEL let client = this.app.client DEL client.element(".header_nav a:nth-child(2)").click() DEL let classesFirst = client.getAttribute(".content-container .content:nth-of-type(1)", "class").split(" ") DEL let classesSecond = client.getAttribute(".content-container .content:nth-of-type(2)", "class").split(" ") DEL expect(classesFirst).to.not.include("current") DEL expect(classesFirst).to.include("left") DEL expect(classesSecond).to.not.include("right") DEL expect(classesSecond).to.include("current") ADD it("tab navigation should work", function(done) { ADD let client = this.app.client; ADD ADD client.element(".header_nav a:nth-child(2)").click() ADD client.getAttribute(".content-container .content:nth-of-type(1)", "class").then(classesFirstStr => { ADD var classesFirst = classesFirstStr.split(" ") ADD client.getAttribute(".content-container .content:nth-of-type(2)", "class").then(classesSecondStr => { ADD var classesSecond = classesSecondStr.split(" ") ADD ADD expect(classesFirst).to.not.include("current") ADD expect(classesFirst).to.include("left") ADD expect(classesSecond).to.not.include("right") ADD expect(classesSecond).to.include("current") ADD done() ADD }) CON }) ADD CON })
<<<<<<< SEARCH const Application = require("spectron").Application describe("ui", function () { this.timeout(10000) console.log(require("electron"), __dirname, path.join(__dirname, "..", "main.js")) beforeEach(function () { this.app = new Application({ path: require("electron"), ======= const Application = require("spectron").Application describe("ui", function() { this.timeout(10000) console.log(require("electron"), __dirname, path.join(__dirname, "..", "main.js")) beforeEach(function() { this.app = new Application({ path: require("electron"), >>>>>>> REPLACE
Rostifar/WordsWithBytes
1a24c2518d1b3865da8cc5ec1de7db3feb4bb57f
src/handlers/ScrabbleGameHandler.java
java
mit
Join existing game using a game code is now working. Next...fix socket issues.
package handlers; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.AtmosphereHandler; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEvent; import java.io.IOException; /** * Created by rostifar on 6/14/16. */ @AtmosphereHandlerService public class ScrabbleGameHandler implements AtmosphereHandler { //action when connection is made to the backend @Override public void onRequest(AtmosphereResource atmosphereResource) throws IOException { AtmosphereRequest request = atmosphereResource.getRequest(); System.out.println("hi"); } //called when Broadcaster broadcasts an event @Override public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException { } @Override public void destroy() { } }
package handlers; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.*; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import java.io.IOException; /** * Created by rostifar on 6/14/16. */ @AtmosphereHandlerService public class ScrabbleGameHandler implements AtmosphereHandler { //action when connection is made to the backend @Override public void onRequest(AtmosphereResource atmosphereResource) throws IOException { AtmosphereRequest request = atmosphereResource.getRequest(); AtmosphereResponse response = atmosphereResource.getResponse(); System.out.println("Called:" + this.getClass().getName()); // request.get RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html"); try { reqDispatcher.forward(request, response); } catch (ServletException e) { e.printStackTrace(); } } //called when Broadcaster broadcasts an event @Override public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException { } @Override public void destroy() { } }
12
5
2
mixed
--- a/src/handlers/ScrabbleGameHandler.java +++ b/src/handlers/ScrabbleGameHandler.java @@ -3,7 +3,6 @@ import org.atmosphere.config.service.AtmosphereHandlerService; -import org.atmosphere.cpr.AtmosphereHandler; -import org.atmosphere.cpr.AtmosphereRequest; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.AtmosphereResourceEvent; +import org.atmosphere.cpr.*; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; import java.io.IOException; @@ -22,4 +21,12 @@ AtmosphereRequest request = atmosphereResource.getRequest(); + AtmosphereResponse response = atmosphereResource.getResponse(); - System.out.println("hi"); + System.out.println("Called:" + this.getClass().getName()); +// request.get + RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html"); + try { + reqDispatcher.forward(request, response); + } catch (ServletException e) { + e.printStackTrace(); + } }
--- a/src/handlers/ScrabbleGameHandler.java +++ b/src/handlers/ScrabbleGameHandler.java @@ ... @@ import org.atmosphere.config.service.AtmosphereHandlerService; -import org.atmosphere.cpr.AtmosphereHandler; -import org.atmosphere.cpr.AtmosphereRequest; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.AtmosphereResourceEvent; +import org.atmosphere.cpr.*; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; import java.io.IOException; @@ ... @@ AtmosphereRequest request = atmosphereResource.getRequest(); + AtmosphereResponse response = atmosphereResource.getResponse(); - System.out.println("hi"); + System.out.println("Called:" + this.getClass().getName()); +// request.get + RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html"); + try { + reqDispatcher.forward(request, response); + } catch (ServletException e) { + e.printStackTrace(); + } }
--- a/src/handlers/ScrabbleGameHandler.java +++ b/src/handlers/ScrabbleGameHandler.java @@ -3,7 +3,6 @@ CON import org.atmosphere.config.service.AtmosphereHandlerService; DEL import org.atmosphere.cpr.AtmosphereHandler; DEL import org.atmosphere.cpr.AtmosphereRequest; DEL import org.atmosphere.cpr.AtmosphereResource; DEL import org.atmosphere.cpr.AtmosphereResourceEvent; ADD import org.atmosphere.cpr.*; CON ADD import javax.servlet.RequestDispatcher; ADD import javax.servlet.ServletException; CON import java.io.IOException; @@ -22,4 +21,12 @@ CON AtmosphereRequest request = atmosphereResource.getRequest(); ADD AtmosphereResponse response = atmosphereResource.getResponse(); CON DEL System.out.println("hi"); ADD System.out.println("Called:" + this.getClass().getName()); ADD // request.get ADD RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html"); ADD try { ADD reqDispatcher.forward(request, response); ADD } catch (ServletException e) { ADD e.printStackTrace(); ADD } CON }
<<<<<<< SEARCH import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.AtmosphereHandler; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEvent; import java.io.IOException; ======= import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.*; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import java.io.IOException; >>>>>>> REPLACE
r24y/github-issues
976297be81149e588c8620bfb7d3db043ce4d453
src/gh-issues-view.js
javascript
mit
Use Atom's new Dock feature
/** @babel */ import React from 'react'; import ReactDOM from 'react-dom'; import IssuesList from './components/issues-list'; export default class GhIssuesView { constructor(serializedState) { // Create root element this.element = document.createElement('div'); this.element.classList.add('quick-issues'); ReactDOM.render(React.createElement(IssuesList), this.element); } // Returns an object that can be retrieved when package is activated serialize() {} // Tear down any state and detach destroy() { this.element.remove(); } getView() { return this.element; } getTitle() { return 'Quick Issues'; } getUri() { return 'quick-issues:///'; } } GhIssuesView.Provider = (view) => view.element;
/** @babel */ import React from 'react'; import ReactDOM from 'react-dom'; import IssuesList from './components/issues-list'; export default class GhIssuesView { constructor(serializedState) { // Create root element this.element = document.createElement('div'); this.element.classList.add('quick-issues'); ReactDOM.render(React.createElement(IssuesList), this.element); } // Returns an object that can be retrieved when package is activated serialize() {} // Tear down any state and detach destroy() { this.element.remove(); } getView() { return this.element; } getTitle() { return 'Quick Issues'; } getUri() { return 'quick-issues:///'; } getDefaultLocation() { return 'right'; } } GhIssuesView.Provider = (view) => view.element;
3
0
1
add_only
--- a/src/gh-issues-view.js +++ b/src/gh-issues-view.js @@ -34,2 +34,5 @@ + getDefaultLocation() { + return 'right'; + } }
--- a/src/gh-issues-view.js +++ b/src/gh-issues-view.js @@ ... @@ + getDefaultLocation() { + return 'right'; + } }
--- a/src/gh-issues-view.js +++ b/src/gh-issues-view.js @@ -34,2 +34,5 @@ CON ADD getDefaultLocation() { ADD return 'right'; ADD } CON }
<<<<<<< SEARCH } } ======= } getDefaultLocation() { return 'right'; } } >>>>>>> REPLACE
t-miyamae/teuthology
7153c2be456084dfdd7cc346d62a6eb0fcaa2a31
teuthology/config.py
python
mit
Add doc noting Inktank's lockserver URL Since I just removed it from lockstatus.py.
import os import yaml import logging CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml') log = logging.getLogger(__name__) class _Config(object): """ This class is intended to unify teuthology's many configuration files and objects. Currently it serves as a convenient interface to ~/.teuthology.yaml and nothing else. """ def __init__(self): if os.path.exists(CONF_FILE): self.__conf = yaml.safe_load(file(CONF_FILE)) else: log.debug("%s not found", CONF_FILE) self.__conf = {} # This property declaration exists mainly as an example; it is not # necessary unless you want to, say, define a set method and/or a # docstring. @property def lock_server(self): return self.__conf.get('lock_server') # This takes care of any and all of the rest. # If the parameter is defined, return it. Otherwise return None. def __getattr__(self, name): return self.__conf.get(name) config = _Config()
import os import yaml import logging CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml') log = logging.getLogger(__name__) class _Config(object): """ This class is intended to unify teuthology's many configuration files and objects. Currently it serves as a convenient interface to ~/.teuthology.yaml and nothing else. """ def __init__(self): if os.path.exists(CONF_FILE): self.__conf = yaml.safe_load(file(CONF_FILE)) else: log.debug("%s not found", CONF_FILE) self.__conf = {} # This property declaration exists mainly as an example; it is not # necessary unless you want to, say, define a set method and/or a # docstring. @property def lock_server(self): """ The URL to your lock server. For example, Inktank uses: http://teuthology.front.sepia.ceph.com/locker/lock """ return self.__conf.get('lock_server') # This takes care of any and all of the rest. # If the parameter is defined, return it. Otherwise return None. def __getattr__(self, name): return self.__conf.get(name) config = _Config()
5
0
1
add_only
--- a/teuthology/config.py +++ b/teuthology/config.py @@ -27,2 +27,7 @@ def lock_server(self): + """ + The URL to your lock server. For example, Inktank uses: + + http://teuthology.front.sepia.ceph.com/locker/lock + """ return self.__conf.get('lock_server')
--- a/teuthology/config.py +++ b/teuthology/config.py @@ ... @@ def lock_server(self): + """ + The URL to your lock server. For example, Inktank uses: + + http://teuthology.front.sepia.ceph.com/locker/lock + """ return self.__conf.get('lock_server')
--- a/teuthology/config.py +++ b/teuthology/config.py @@ -27,2 +27,7 @@ CON def lock_server(self): ADD """ ADD The URL to your lock server. For example, Inktank uses: ADD ADD http://teuthology.front.sepia.ceph.com/locker/lock ADD """ CON return self.__conf.get('lock_server')
<<<<<<< SEARCH @property def lock_server(self): return self.__conf.get('lock_server') ======= @property def lock_server(self): """ The URL to your lock server. For example, Inktank uses: http://teuthology.front.sepia.ceph.com/locker/lock """ return self.__conf.get('lock_server') >>>>>>> REPLACE
StefMa/AndroidArtifacts
0462563238c213151db47c367ff91860207aea79
src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt
kotlin
apache-2.0
Move creating of in afterEvalutaion listener
package guru.stefma.androidartifacts import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.publish.maven.MavenPublication class JavaArtifactsPlugin : Plugin<Project> { override fun apply(project: Project) { val extension = project.createJavaArtifactsExtension() project.applyMavenPublishPlugin() val publicationTasks = project.tasks.createListAvailablePublicationTask() val publicationName = "maven" project.tasks.createJavaArtifactsTask(publicationName) publicationTasks.publicationNames += publicationName createPublication(extension, project, publicationName, publicationTasks) } private fun Project.createJavaArtifactsExtension() = extensions.create("javaArtifact", ArtifactsExtension::class.java) private fun createPublication( extension: ArtifactsExtension, project: Project, publicationName: String, publicationTasks: ListGeneratedPublicationTasks ) { publicationTasks.publicationNames += publicationName project.publishingExtension.publications.create(publicationName, MavenPublication::class.java) { it.from(project.components.getByName("java")) // Publish sources only if set to true if (extension.sources) it.addJavaSourcesArtifact(project, "maven") // Publish javadoc only if set to true if (extension.javadoc) { it.addJavaJavadocArtifact(project, "maven") } it.setupMetadata(project, extension) } } }
package guru.stefma.androidartifacts import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.publish.maven.MavenPublication class JavaArtifactsPlugin : Plugin<Project> { override fun apply(project: Project) { val extension = project.createJavaArtifactsExtension() project.applyMavenPublishPlugin() val publicationTasks = project.tasks.createListAvailablePublicationTask() val publicationName = "maven" project.tasks.createJavaArtifactsTask(publicationName) publicationTasks.publicationNames += publicationName // TODO: Think if we can do that better lazy somehow // see https://docs.gradle.org/current/userguide/lazy_configuration.html project.afterEvaluate { createPublication(extension, project, publicationName, publicationTasks) } } private fun Project.createJavaArtifactsExtension() = extensions.create("javaArtifact", ArtifactsExtension::class.java) private fun createPublication( extension: ArtifactsExtension, project: Project, publicationName: String, publicationTasks: ListGeneratedPublicationTasks ) { publicationTasks.publicationNames += publicationName project.publishingExtension.publications.create(publicationName, MavenPublication::class.java) { it.from(project.components.getByName("java")) // Publish sources only if set to true if (extension.sources) it.addJavaSourcesArtifact(project, "maven") // Publish javadoc only if set to true if (extension.javadoc) { it.addJavaJavadocArtifact(project, "maven") } it.setupMetadata(project, extension) } } }
5
1
1
mixed
--- a/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt +++ b/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt @@ -15,3 +15,7 @@ publicationTasks.publicationNames += publicationName - createPublication(extension, project, publicationName, publicationTasks) + // TODO: Think if we can do that better lazy somehow + // see https://docs.gradle.org/current/userguide/lazy_configuration.html + project.afterEvaluate { + createPublication(extension, project, publicationName, publicationTasks) + } }
--- a/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt +++ b/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt @@ ... @@ publicationTasks.publicationNames += publicationName - createPublication(extension, project, publicationName, publicationTasks) + // TODO: Think if we can do that better lazy somehow + // see https://docs.gradle.org/current/userguide/lazy_configuration.html + project.afterEvaluate { + createPublication(extension, project, publicationName, publicationTasks) + } }
--- a/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt +++ b/src/main/kotlin/guru/stefma/androidartifacts/JavaArtifactsPlugin.kt @@ -15,3 +15,7 @@ CON publicationTasks.publicationNames += publicationName DEL createPublication(extension, project, publicationName, publicationTasks) ADD // TODO: Think if we can do that better lazy somehow ADD // see https://docs.gradle.org/current/userguide/lazy_configuration.html ADD project.afterEvaluate { ADD createPublication(extension, project, publicationName, publicationTasks) ADD } CON }
<<<<<<< SEARCH project.tasks.createJavaArtifactsTask(publicationName) publicationTasks.publicationNames += publicationName createPublication(extension, project, publicationName, publicationTasks) } ======= project.tasks.createJavaArtifactsTask(publicationName) publicationTasks.publicationNames += publicationName // TODO: Think if we can do that better lazy somehow // see https://docs.gradle.org/current/userguide/lazy_configuration.html project.afterEvaluate { createPublication(extension, project, publicationName, publicationTasks) } } >>>>>>> REPLACE
onepercentclub/onepercentclub-site
8460b1249d1140234798b8b7e482b13cde173a1e
bluebottle/settings/jenkins.py
python
bsd-3-clause
Disable django.contrib.sites tests in Jenkins.
# NOTE: local.py must be an empty file when using this configuration. from .defaults import * # Put jenkins environment specific overrides below. INSTALLED_APPS += ('django_jenkins',) SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } DEBUG = False TEMPLATE_DEBUG = False # Test all INSTALLED_APPS by default PROJECT_APPS = list(INSTALLED_APPS) # Some of these tests fail, and it's not our fault # https://code.djangoproject.com/ticket/17966 PROJECT_APPS.remove('django.contrib.auth') # https://github.com/django-extensions/django-extensions/issues/154 PROJECT_APPS.remove('django_extensions') PROJECT_APPS.remove('django_extensions.tests') # FIXME: We need to fix the django_polymorphic tests PROJECT_APPS.remove('polymorphic') # Disable pylint becasue it seems to be causing problems JENKINS_TASKS = ( # 'django_jenkins.tasks.run_pylint', 'django_jenkins.tasks.with_coverage', 'django_jenkins.tasks.django_tests', )
# NOTE: local.py must be an empty file when using this configuration. from .defaults import * # Put jenkins environment specific overrides below. INSTALLED_APPS += ('django_jenkins',) SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } DEBUG = False TEMPLATE_DEBUG = False # Test all INSTALLED_APPS by default PROJECT_APPS = list(INSTALLED_APPS) # Some of these tests fail, and it's not our fault # https://code.djangoproject.com/ticket/17966 PROJECT_APPS.remove('django.contrib.auth') # This app fails with a strange error: # DatabaseError: no such table: django_comments # Not sure what's going on so it's disabled for now. PROJECT_APPS.remove('django.contrib.sites') # https://github.com/django-extensions/django-extensions/issues/154 PROJECT_APPS.remove('django_extensions') PROJECT_APPS.remove('django_extensions.tests') # FIXME: We need to fix the django_polymorphic tests PROJECT_APPS.remove('polymorphic') # Disable pylint becasue it seems to be causing problems JENKINS_TASKS = ( # 'django_jenkins.tasks.run_pylint', 'django_jenkins.tasks.with_coverage', 'django_jenkins.tasks.django_tests', )
5
0
1
add_only
--- a/bluebottle/settings/jenkins.py +++ b/bluebottle/settings/jenkins.py @@ -27,2 +27,7 @@ +# This app fails with a strange error: +# DatabaseError: no such table: django_comments +# Not sure what's going on so it's disabled for now. +PROJECT_APPS.remove('django.contrib.sites') + # https://github.com/django-extensions/django-extensions/issues/154
--- a/bluebottle/settings/jenkins.py +++ b/bluebottle/settings/jenkins.py @@ ... @@ +# This app fails with a strange error: +# DatabaseError: no such table: django_comments +# Not sure what's going on so it's disabled for now. +PROJECT_APPS.remove('django.contrib.sites') + # https://github.com/django-extensions/django-extensions/issues/154
--- a/bluebottle/settings/jenkins.py +++ b/bluebottle/settings/jenkins.py @@ -27,2 +27,7 @@ CON ADD # This app fails with a strange error: ADD # DatabaseError: no such table: django_comments ADD # Not sure what's going on so it's disabled for now. ADD PROJECT_APPS.remove('django.contrib.sites') ADD CON # https://github.com/django-extensions/django-extensions/issues/154
<<<<<<< SEARCH PROJECT_APPS.remove('django.contrib.auth') # https://github.com/django-extensions/django-extensions/issues/154 PROJECT_APPS.remove('django_extensions') ======= PROJECT_APPS.remove('django.contrib.auth') # This app fails with a strange error: # DatabaseError: no such table: django_comments # Not sure what's going on so it's disabled for now. PROJECT_APPS.remove('django.contrib.sites') # https://github.com/django-extensions/django-extensions/issues/154 PROJECT_APPS.remove('django_extensions') >>>>>>> REPLACE
gradle/gradle
6311d15971bf01c1b9351fb0b48bc54ed94209a7
.teamcity/settings.kts
kotlin
apache-2.0
Upgrade TeamCity DSL version to 2022.04
import common.VersionedSettingsBranch import jetbrains.buildServer.configs.kotlin.v2019_2.project import jetbrains.buildServer.configs.kotlin.v2019_2.version import projects.GradleBuildToolRootProject version = "2021.2" /* Master (buildTypeId: Gradle_Master) |----- Check (buildTypeId: Gradle_Master_Check) | |---- QuickFeedbackLinux (buildTypeId: Gradle_Master_Check_QuickFeedbackLinux) | |---- QuickFeedback | |---- ... | |---- ReadyForRelease | |----- Promotion (buildTypeId: Gradle_Master_Promotion) | |----- Nightly Snapshot | |----- ... | |----- Util |----- WarmupEc2Agent |----- AdHocPerformanceTest Release (buildTypeId: Gradle_Release) |----- Check (buildTypeId: Gradle_Release_Check) | |---- QuickFeedbackLinux (buildTypeId: Gradle_Release_Check_QuickFeedbackLinux) | |---- QuickFeedback | |---- ... | |---- ReadyForRelease | |----- Promotion (buildTypeId: Gradle_Release_Promotion) | |----- Nightly Snapshot | |----- ... | |----- Util |----- WarmupEc2Agent |----- AdHocPerformanceTest */ project(GradleBuildToolRootProject(VersionedSettingsBranch.fromDslContext()))
import common.VersionedSettingsBranch import jetbrains.buildServer.configs.kotlin.v2019_2.project import jetbrains.buildServer.configs.kotlin.v2019_2.version import projects.GradleBuildToolRootProject version = "2022.04" /* Master (buildTypeId: Gradle_Master) |----- Check (buildTypeId: Gradle_Master_Check) | |---- QuickFeedbackLinux (buildTypeId: Gradle_Master_Check_QuickFeedbackLinux) | |---- QuickFeedback | |---- ... | |---- ReadyForRelease | |----- Promotion (buildTypeId: Gradle_Master_Promotion) | |----- Nightly Snapshot | |----- ... | |----- Util |----- WarmupEc2Agent |----- AdHocPerformanceTest Release (buildTypeId: Gradle_Release) |----- Check (buildTypeId: Gradle_Release_Check) | |---- QuickFeedbackLinux (buildTypeId: Gradle_Release_Check_QuickFeedbackLinux) | |---- QuickFeedback | |---- ... | |---- ReadyForRelease | |----- Promotion (buildTypeId: Gradle_Release_Promotion) | |----- Nightly Snapshot | |----- ... | |----- Util |----- WarmupEc2Agent |----- AdHocPerformanceTest */ project(GradleBuildToolRootProject(VersionedSettingsBranch.fromDslContext()))
1
1
1
mixed
--- a/.teamcity/settings.kts +++ b/.teamcity/settings.kts @@ -5,3 +5,3 @@ -version = "2021.2" +version = "2022.04"
--- a/.teamcity/settings.kts +++ b/.teamcity/settings.kts @@ ... @@ -version = "2021.2" +version = "2022.04"
--- a/.teamcity/settings.kts +++ b/.teamcity/settings.kts @@ -5,3 +5,3 @@ CON DEL version = "2021.2" ADD version = "2022.04" CON
<<<<<<< SEARCH import projects.GradleBuildToolRootProject version = "2021.2" /* ======= import projects.GradleBuildToolRootProject version = "2022.04" /* >>>>>>> REPLACE
seanrivera/rust
431cb9a3454fe19fe6987aebb3b3655dc9eca8ad
src/test/run-pass/anon-obj-overriding.rs
rust
apache-2.0
Test method overriding a little more.
//xfail-stage0 use std; fn main() { obj a() { fn foo() -> int { ret 2; } fn bar() -> int { ret self.foo(); } } auto my_a = a(); // An anonymous object that overloads the 'foo' method. auto my_b = obj() { fn foo() -> int { ret 3; } with my_a }; assert (my_b.foo() == 3); assert (my_b.bar() == 3); }
//xfail-stage0 use std; fn main() { obj a() { fn foo() -> int { ret 2; } fn bar() -> int { ret self.foo(); } } auto my_a = a(); // An anonymous object that overloads the 'foo' method. auto my_b = obj() { fn foo() -> int { ret 3; } with my_a }; assert (my_b.foo() == 3); assert (my_b.bar() == 3); auto my_c = obj() { fn baz(int x, int y) -> int { ret x + y + self.foo(); } with my_b }; auto my_d = obj() { fn baz(int x, int y) -> int { ret x + y + self.foo(); } with my_a }; assert (my_c.baz(1, 2) == 6); assert (my_d.baz(1, 2) == 5); }
17
0
1
add_only
--- a/src/test/run-pass/anon-obj-overriding.rs +++ b/src/test/run-pass/anon-obj-overriding.rs @@ -28,2 +28,19 @@ assert (my_b.bar() == 3); + + auto my_c = obj() { + fn baz(int x, int y) -> int { + ret x + y + self.foo(); + } + with my_b + }; + + auto my_d = obj() { + fn baz(int x, int y) -> int { + ret x + y + self.foo(); + } + with my_a + }; + + assert (my_c.baz(1, 2) == 6); + assert (my_d.baz(1, 2) == 5); }
--- a/src/test/run-pass/anon-obj-overriding.rs +++ b/src/test/run-pass/anon-obj-overriding.rs @@ ... @@ assert (my_b.bar() == 3); + + auto my_c = obj() { + fn baz(int x, int y) -> int { + ret x + y + self.foo(); + } + with my_b + }; + + auto my_d = obj() { + fn baz(int x, int y) -> int { + ret x + y + self.foo(); + } + with my_a + }; + + assert (my_c.baz(1, 2) == 6); + assert (my_d.baz(1, 2) == 5); }
--- a/src/test/run-pass/anon-obj-overriding.rs +++ b/src/test/run-pass/anon-obj-overriding.rs @@ -28,2 +28,19 @@ CON assert (my_b.bar() == 3); ADD ADD auto my_c = obj() { ADD fn baz(int x, int y) -> int { ADD ret x + y + self.foo(); ADD } ADD with my_b ADD }; ADD ADD auto my_d = obj() { ADD fn baz(int x, int y) -> int { ADD ret x + y + self.foo(); ADD } ADD with my_a ADD }; ADD ADD assert (my_c.baz(1, 2) == 6); ADD assert (my_d.baz(1, 2) == 5); CON }
<<<<<<< SEARCH assert (my_b.foo() == 3); assert (my_b.bar() == 3); } ======= assert (my_b.foo() == 3); assert (my_b.bar() == 3); auto my_c = obj() { fn baz(int x, int y) -> int { ret x + y + self.foo(); } with my_b }; auto my_d = obj() { fn baz(int x, int y) -> int { ret x + y + self.foo(); } with my_a }; assert (my_c.baz(1, 2) == 6); assert (my_d.baz(1, 2) == 5); } >>>>>>> REPLACE
bluss/arrayvec
9fc6737e1bb5048b26bf3478753cb1483017fa50
src/maybe_uninit_copy.rs
rust
apache-2.0
FIX: Use repr(C) MaybeUninitCopy after discussion with RalfJung We have a recommendation from the unsafe-wg (no rule yet), that repr(C) for unions should work this way, so that we can cast from the union type to one of its fields.
use array::Array; #[derive(Copy, Clone)] pub union MaybeUninitCopy<T> where T: Copy { empty: (), value: T, } impl<T> MaybeUninitCopy<T> where T: Copy { /// Create a new MaybeUninit with uninitialized interior pub unsafe fn uninitialized() -> Self { Self { empty: () } } /// Create a new MaybeUninit from the value `v`. pub fn from(value: T) -> Self { Self { value } } // Raw pointer casts written so that we don't reference or access the // uninitialized interior value /// Return a raw pointer to the start of the interior array pub fn ptr(&self) -> *const T::Item where T: Array { self as *const _ as *const T::Item } /// Return a mut raw pointer to the start of the interior array pub fn ptr_mut(&mut self) -> *mut T::Item where T: Array { self as *mut _ as *mut T::Item } }
use array::Array; #[derive(Copy, Clone)] #[repr(C)] // for cast from self ptr to value pub union MaybeUninitCopy<T> where T: Copy { empty: (), value: T, } impl<T> MaybeUninitCopy<T> where T: Copy { /// Create a new MaybeUninit with uninitialized interior pub unsafe fn uninitialized() -> Self { Self { empty: () } } /// Create a new MaybeUninit from the value `v`. pub fn from(value: T) -> Self { Self { value } } // Raw pointer casts written so that we don't reference or access the // uninitialized interior value /// Return a raw pointer to the start of the interior array pub fn ptr(&self) -> *const T::Item where T: Array { self as *const _ as *const T::Item } /// Return a mut raw pointer to the start of the interior array pub fn ptr_mut(&mut self) -> *mut T::Item where T: Array { self as *mut _ as *mut T::Item } }
1
0
1
add_only
--- a/src/maybe_uninit_copy.rs +++ b/src/maybe_uninit_copy.rs @@ -4,2 +4,3 @@ #[derive(Copy, Clone)] +#[repr(C)] // for cast from self ptr to value pub union MaybeUninitCopy<T>
--- a/src/maybe_uninit_copy.rs +++ b/src/maybe_uninit_copy.rs @@ ... @@ #[derive(Copy, Clone)] +#[repr(C)] // for cast from self ptr to value pub union MaybeUninitCopy<T>
--- a/src/maybe_uninit_copy.rs +++ b/src/maybe_uninit_copy.rs @@ -4,2 +4,3 @@ CON #[derive(Copy, Clone)] ADD #[repr(C)] // for cast from self ptr to value CON pub union MaybeUninitCopy<T>
<<<<<<< SEARCH #[derive(Copy, Clone)] pub union MaybeUninitCopy<T> where T: Copy ======= #[derive(Copy, Clone)] #[repr(C)] // for cast from self ptr to value pub union MaybeUninitCopy<T> where T: Copy >>>>>>> REPLACE
CesiumGS/cesium
a43aec98b677ea480df5e9c4cde344e4a8146ee8
Source/Core/getAbsoluteUri.js
javascript
apache-2.0
Deal with document in node
define([ '../ThirdParty/Uri', './defaultValue', './defined', './DeveloperError' ], function( Uri, defaultValue, defined, DeveloperError) { 'use strict'; /** * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri. * @exports getAbsoluteUri * * @param {String} relative The relative Uri. * @param {String} [base] The base Uri. * @returns {String} The absolute Uri of the given relative Uri. * * @example * //absolute Uri will be "https://test.com/awesome.png"; * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com'); */ function getAbsoluteUri(relative, base) { return getAbsoluteUri._implementation(relative, base, document); } getAbsoluteUri._implementation = function(relative, base, documentObject) { //>>includeStart('debug', pragmas.debug); if (!defined(relative)) { throw new DeveloperError('relative uri is required.'); } //>>includeEnd('debug'); base = defaultValue(base, defaultValue(documentObject.baseURI, documentObject.location.href)); var baseUri = new Uri(base); var relativeUri = new Uri(relative); return relativeUri.resolve(baseUri).toString(); }; return getAbsoluteUri; });
/*globals process, require*/ define([ '../ThirdParty/Uri', './defaultValue', './defined', './DeveloperError' ], function( Uri, defaultValue, defined, DeveloperError) { 'use strict'; /** * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri. * @exports getAbsoluteUri * * @param {String} relative The relative Uri. * @param {String} [base] The base Uri. * @returns {String} The absolute Uri of the given relative Uri. * * @example * //absolute Uri will be "https://test.com/awesome.png"; * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com'); */ function getAbsoluteUri(relative, base) { if (typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]') { // Running node return getAbsoluteUri._implementation(relative, base, {baseURI: 'http://localhost/', location: {href: ''}}) } else { return getAbsoluteUri._implementation(relative, base, document); } } getAbsoluteUri._implementation = function(relative, base, documentObject) { //>>includeStart('debug', pragmas.debug); if (!defined(relative)) { throw new DeveloperError('relative uri is required.'); } //>>includeEnd('debug'); base = defaultValue(base, defaultValue(documentObject.baseURI, documentObject.location.href)); var baseUri = new Uri(base); var relativeUri = new Uri(relative); return relativeUri.resolve(baseUri).toString(); }; return getAbsoluteUri; });
9
3
2
mixed
--- a/Source/Core/getAbsoluteUri.js +++ b/Source/Core/getAbsoluteUri.js @@ -1 +1,2 @@ +/*globals process, require*/ define([ @@ -24,5 +25,10 @@ */ - function getAbsoluteUri(relative, base) { - return getAbsoluteUri._implementation(relative, base, document); - } + function getAbsoluteUri(relative, base) { + if (typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]') { + // Running node + return getAbsoluteUri._implementation(relative, base, {baseURI: 'http://localhost/', location: {href: ''}}) + } else { + return getAbsoluteUri._implementation(relative, base, document); + } + }
--- a/Source/Core/getAbsoluteUri.js +++ b/Source/Core/getAbsoluteUri.js @@ ... @@ +/*globals process, require*/ define([ @@ ... @@ */ - function getAbsoluteUri(relative, base) { - return getAbsoluteUri._implementation(relative, base, document); - } + function getAbsoluteUri(relative, base) { + if (typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]') { + // Running node + return getAbsoluteUri._implementation(relative, base, {baseURI: 'http://localhost/', location: {href: ''}}) + } else { + return getAbsoluteUri._implementation(relative, base, document); + } + }
--- a/Source/Core/getAbsoluteUri.js +++ b/Source/Core/getAbsoluteUri.js @@ -1 +1,2 @@ ADD /*globals process, require*/ CON define([ @@ -24,5 +25,10 @@ CON */ DEL function getAbsoluteUri(relative, base) { DEL return getAbsoluteUri._implementation(relative, base, document); DEL } ADD function getAbsoluteUri(relative, base) { ADD if (typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]') { ADD // Running node ADD return getAbsoluteUri._implementation(relative, base, {baseURI: 'http://localhost/', location: {href: ''}}) ADD } else { ADD return getAbsoluteUri._implementation(relative, base, document); ADD } ADD } CON
<<<<<<< SEARCH define([ '../ThirdParty/Uri', ======= /*globals process, require*/ define([ '../ThirdParty/Uri', >>>>>>> REPLACE
nxnfufunezn/redox
2db84f95994e329cd591b78db88d1ca2d51177f8
filesystem/apps/example/main.rs
rust
mit
WIP: Implement tests for syscalls in example scheme
use std::fs::File; use std::io::{Read, Write}; use system::scheme::{Packet, Scheme}; extern crate system; struct ExampleScheme; impl Scheme for ExampleScheme { } fn main() { //In order to handle example:, we create :example let mut scheme = File::create(":example").unwrap(); loop { let mut packet = Packet::default(); if scheme.read(&mut packet).unwrap() == 0 { panic!("Unexpected EOF"); } println!("Received: {:?}", packet); packet.a = 0; scheme.write(&packet).unwrap(); } }
use std::fs::File; use std::io::{Read, Write}; use system::error::{Error, Result, ENOENT, EBADF}; use system::scheme::{Packet, Scheme}; extern crate system; struct ExampleScheme; impl Scheme for ExampleScheme { fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result { println!("open {:X} = {}, {:X}, {:X}", path.as_ptr() as usize, path, flags, mode); Ok(0) } #[allow(unused_variables)] fn unlink(&mut self, path: &str) -> Result { println!("unlink {}", path); Err(Error::new(ENOENT)) } #[allow(unused_variables)] fn mkdir(&mut self, path: &str, mode: usize) -> Result { println!("mkdir {}, {:X}", path, mode); Err(Error::new(ENOENT)) } /* Resource operations */ #[allow(unused_variables)] fn read(&mut self, id: usize, buf: &mut [u8]) -> Result { println!("read {}, {:X}, {}", id, buf.as_mut_ptr() as usize, buf.len()); Err(Error::new(EBADF)) } #[allow(unused_variables)] fn write(&mut self, id: usize, buf: &[u8]) -> Result { println!("write {}, {:X}, {}", id, buf.as_ptr() as usize, buf.len()); Err(Error::new(EBADF)) } #[allow(unused_variables)] fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result { println!("seek {}, {}, {}", id, pos, whence); Err(Error::new(EBADF)) } #[allow(unused_variables)] fn sync(&mut self, id: usize) -> Result { println!("sync {}", id); Err(Error::new(EBADF)) } #[allow(unused_variables)] fn truncate(&mut self, id: usize, len: usize) -> Result { println!("truncate {}, {}", id, len); Err(Error::new(EBADF)) } } fn main() { //In order to handle example:, we create :example let mut scheme = ExampleScheme; let mut socket = File::create(":example").unwrap(); loop { let mut packet = Packet::default(); if socket.read(&mut packet).unwrap() == 0 { panic!("Unexpected EOF"); } println!("Recv {:?}", packet); scheme.handle(&mut packet); socket.write(&packet).unwrap(); println!("Sent {:?}", packet); } }
55
5
3
mixed
--- a/filesystem/apps/example/main.rs +++ b/filesystem/apps/example/main.rs @@ -3,2 +3,3 @@ +use system::error::{Error, Result, ENOENT, EBADF}; use system::scheme::{Packet, Scheme}; @@ -10,3 +11,50 @@ impl Scheme for ExampleScheme { + fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result { + println!("open {:X} = {}, {:X}, {:X}", path.as_ptr() as usize, path, flags, mode); + Ok(0) + } + #[allow(unused_variables)] + fn unlink(&mut self, path: &str) -> Result { + println!("unlink {}", path); + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn mkdir(&mut self, path: &str, mode: usize) -> Result { + println!("mkdir {}, {:X}", path, mode); + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + + #[allow(unused_variables)] + fn read(&mut self, id: usize, buf: &mut [u8]) -> Result { + println!("read {}, {:X}, {}", id, buf.as_mut_ptr() as usize, buf.len()); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&mut self, id: usize, buf: &[u8]) -> Result { + println!("write {}, {:X}, {}", id, buf.as_ptr() as usize, buf.len()); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result { + println!("seek {}, {}, {}", id, pos, whence); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn sync(&mut self, id: usize) -> Result { + println!("sync {}", id); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn truncate(&mut self, id: usize, len: usize) -> Result { + println!("truncate {}, {}", id, len); + Err(Error::new(EBADF)) + } } @@ -15,13 +63,15 @@ //In order to handle example:, we create :example - let mut scheme = File::create(":example").unwrap(); + let mut scheme = ExampleScheme; + let mut socket = File::create(":example").unwrap(); loop { let mut packet = Packet::default(); - if scheme.read(&mut packet).unwrap() == 0 { + if socket.read(&mut packet).unwrap() == 0 { panic!("Unexpected EOF"); } + println!("Recv {:?}", packet); - println!("Received: {:?}", packet); + scheme.handle(&mut packet); - packet.a = 0; - scheme.write(&packet).unwrap(); + socket.write(&packet).unwrap(); + println!("Sent {:?}", packet); }
--- a/filesystem/apps/example/main.rs +++ b/filesystem/apps/example/main.rs @@ ... @@ +use system::error::{Error, Result, ENOENT, EBADF}; use system::scheme::{Packet, Scheme}; @@ ... @@ impl Scheme for ExampleScheme { + fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result { + println!("open {:X} = {}, {:X}, {:X}", path.as_ptr() as usize, path, flags, mode); + Ok(0) + } + #[allow(unused_variables)] + fn unlink(&mut self, path: &str) -> Result { + println!("unlink {}", path); + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn mkdir(&mut self, path: &str, mode: usize) -> Result { + println!("mkdir {}, {:X}", path, mode); + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + + #[allow(unused_variables)] + fn read(&mut self, id: usize, buf: &mut [u8]) -> Result { + println!("read {}, {:X}, {}", id, buf.as_mut_ptr() as usize, buf.len()); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&mut self, id: usize, buf: &[u8]) -> Result { + println!("write {}, {:X}, {}", id, buf.as_ptr() as usize, buf.len()); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result { + println!("seek {}, {}, {}", id, pos, whence); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn sync(&mut self, id: usize) -> Result { + println!("sync {}", id); + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn truncate(&mut self, id: usize, len: usize) -> Result { + println!("truncate {}, {}", id, len); + Err(Error::new(EBADF)) + } } @@ ... @@ //In order to handle example:, we create :example - let mut scheme = File::create(":example").unwrap(); + let mut scheme = ExampleScheme; + let mut socket = File::create(":example").unwrap(); loop { let mut packet = Packet::default(); - if scheme.read(&mut packet).unwrap() == 0 { + if socket.read(&mut packet).unwrap() == 0 { panic!("Unexpected EOF"); } + println!("Recv {:?}", packet); - println!("Received: {:?}", packet); + scheme.handle(&mut packet); - packet.a = 0; - scheme.write(&packet).unwrap(); + socket.write(&packet).unwrap(); + println!("Sent {:?}", packet); }
--- a/filesystem/apps/example/main.rs +++ b/filesystem/apps/example/main.rs @@ -3,2 +3,3 @@ CON ADD use system::error::{Error, Result, ENOENT, EBADF}; CON use system::scheme::{Packet, Scheme}; @@ -10,3 +11,50 @@ CON impl Scheme for ExampleScheme { ADD fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result { ADD println!("open {:X} = {}, {:X}, {:X}", path.as_ptr() as usize, path, flags, mode); ADD Ok(0) ADD } CON ADD #[allow(unused_variables)] ADD fn unlink(&mut self, path: &str) -> Result { ADD println!("unlink {}", path); ADD Err(Error::new(ENOENT)) ADD } ADD ADD #[allow(unused_variables)] ADD fn mkdir(&mut self, path: &str, mode: usize) -> Result { ADD println!("mkdir {}, {:X}", path, mode); ADD Err(Error::new(ENOENT)) ADD } ADD ADD /* Resource operations */ ADD ADD #[allow(unused_variables)] ADD fn read(&mut self, id: usize, buf: &mut [u8]) -> Result { ADD println!("read {}, {:X}, {}", id, buf.as_mut_ptr() as usize, buf.len()); ADD Err(Error::new(EBADF)) ADD } ADD ADD #[allow(unused_variables)] ADD fn write(&mut self, id: usize, buf: &[u8]) -> Result { ADD println!("write {}, {:X}, {}", id, buf.as_ptr() as usize, buf.len()); ADD Err(Error::new(EBADF)) ADD } ADD ADD #[allow(unused_variables)] ADD fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result { ADD println!("seek {}, {}, {}", id, pos, whence); ADD Err(Error::new(EBADF)) ADD } ADD ADD #[allow(unused_variables)] ADD fn sync(&mut self, id: usize) -> Result { ADD println!("sync {}", id); ADD Err(Error::new(EBADF)) ADD } ADD ADD #[allow(unused_variables)] ADD fn truncate(&mut self, id: usize, len: usize) -> Result { ADD println!("truncate {}, {}", id, len); ADD Err(Error::new(EBADF)) ADD } CON } @@ -15,13 +63,15 @@ CON //In order to handle example:, we create :example DEL let mut scheme = File::create(":example").unwrap(); ADD let mut scheme = ExampleScheme; ADD let mut socket = File::create(":example").unwrap(); CON loop { CON let mut packet = Packet::default(); DEL if scheme.read(&mut packet).unwrap() == 0 { ADD if socket.read(&mut packet).unwrap() == 0 { CON panic!("Unexpected EOF"); CON } ADD println!("Recv {:?}", packet); CON DEL println!("Received: {:?}", packet); ADD scheme.handle(&mut packet); CON DEL packet.a = 0; DEL scheme.write(&packet).unwrap(); ADD socket.write(&packet).unwrap(); ADD println!("Sent {:?}", packet); CON }
<<<<<<< SEARCH use std::io::{Read, Write}; use system::scheme::{Packet, Scheme}; ======= use std::io::{Read, Write}; use system::error::{Error, Result, ENOENT, EBADF}; use system::scheme::{Packet, Scheme}; >>>>>>> REPLACE
GaretJax/sphinx-autobuild
723d7410b48fd4fc42ed9afe470ba3b37381599a
noxfile.py
python
mit
Add docs-live to perform demo-runs
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs")
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") @nox.session(name="docs-live") def docs_live(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
6
0
1
add_only
--- a/noxfile.py +++ b/noxfile.py @@ -41 +41,7 @@ session.run("sphinx-build", "-b", "html", "docs/", "build/docs") + + [email protected](name="docs-live") +def docs_live(session): + _install_this_editable(session, extras=["docs"]) + session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
--- a/noxfile.py +++ b/noxfile.py @@ ... @@ session.run("sphinx-build", "-b", "html", "docs/", "build/docs") + + [email protected](name="docs-live") +def docs_live(session): + _install_this_editable(session, extras=["docs"]) + session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
--- a/noxfile.py +++ b/noxfile.py @@ -41 +41,7 @@ CON session.run("sphinx-build", "-b", "html", "docs/", "build/docs") ADD ADD ADD @nox.session(name="docs-live") ADD def docs_live(session): ADD _install_this_editable(session, extras=["docs"]) ADD session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
<<<<<<< SEARCH _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") ======= _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") @nox.session(name="docs-live") def docs_live(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs") >>>>>>> REPLACE
facebook/flipper
3829ac7d0302a1e7dcb354a15ce016fe7298157b
android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt
kotlin
mit
Enable Sections and Litho plugins Summary: Per title Reviewed By: jknoxville Differential Revision: D15166432 fbshipit-source-id: ec2a53ef2af920e4c9f8a8742b2b8fbff01320fe
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE file * in the root directory of this source tree. */ package com.facebook.flipper.sample.tutorial import android.app.Application import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.flipper.android.AndroidFlipperClient import com.facebook.flipper.core.FlipperClient import com.facebook.flipper.plugins.inspector.DescriptorMapping import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors import com.facebook.soloader.SoLoader class TutorialApplication : Application() { override fun onCreate() { super.onCreate() SoLoader.init(this, false) Fresco.initialize(this) val flipperClient = AndroidFlipperClient.getInstance(this) val descriptorMapping = DescriptorMapping.withDefaults() LithoFlipperDescriptors.addWithSections(descriptorMapping) flipperClient.addPlugin(InspectorFlipperPlugin(this, descriptorMapping)) flipperClient.start() } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE file * in the root directory of this source tree. */ package com.facebook.flipper.sample.tutorial import android.app.Application import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.flipper.android.AndroidFlipperClient import com.facebook.flipper.core.FlipperClient import com.facebook.flipper.plugins.inspector.DescriptorMapping import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors import com.facebook.litho.config.ComponentsConfiguration import com.facebook.litho.sections.config.SectionsConfiguration import com.facebook.litho.widget.SectionsDebug import com.facebook.soloader.SoLoader class TutorialApplication : Application() { override fun onCreate() { super.onCreate() SoLoader.init(this, false) Fresco.initialize(this) // Normally, you would want to make these dependent on BuildConfig.DEBUG. ComponentsConfiguration.isDebugModeEnabled = true ComponentsConfiguration.enableRenderInfoDebugging = true val flipperClient = AndroidFlipperClient.getInstance(this) val descriptorMapping = DescriptorMapping.withDefaults() LithoFlipperDescriptors.addWithSections(descriptorMapping) flipperClient.addPlugin(InspectorFlipperPlugin(this, descriptorMapping)) flipperClient.start() } }
8
0
2
add_only
--- a/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt +++ b/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt @@ -16,2 +16,5 @@ import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors +import com.facebook.litho.config.ComponentsConfiguration +import com.facebook.litho.sections.config.SectionsConfiguration +import com.facebook.litho.widget.SectionsDebug import com.facebook.soloader.SoLoader @@ -24,2 +27,7 @@ Fresco.initialize(this) + + // Normally, you would want to make these dependent on BuildConfig.DEBUG. + ComponentsConfiguration.isDebugModeEnabled = true + ComponentsConfiguration.enableRenderInfoDebugging = true + val flipperClient = AndroidFlipperClient.getInstance(this)
--- a/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt +++ b/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt @@ ... @@ import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors +import com.facebook.litho.config.ComponentsConfiguration +import com.facebook.litho.sections.config.SectionsConfiguration +import com.facebook.litho.widget.SectionsDebug import com.facebook.soloader.SoLoader @@ ... @@ Fresco.initialize(this) + + // Normally, you would want to make these dependent on BuildConfig.DEBUG. + ComponentsConfiguration.isDebugModeEnabled = true + ComponentsConfiguration.enableRenderInfoDebugging = true + val flipperClient = AndroidFlipperClient.getInstance(this)
--- a/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt +++ b/android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/TutorialApplication.kt @@ -16,2 +16,5 @@ CON import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors ADD import com.facebook.litho.config.ComponentsConfiguration ADD import com.facebook.litho.sections.config.SectionsConfiguration ADD import com.facebook.litho.widget.SectionsDebug CON import com.facebook.soloader.SoLoader @@ -24,2 +27,7 @@ CON Fresco.initialize(this) ADD ADD // Normally, you would want to make these dependent on BuildConfig.DEBUG. ADD ComponentsConfiguration.isDebugModeEnabled = true ADD ComponentsConfiguration.enableRenderInfoDebugging = true ADD CON val flipperClient = AndroidFlipperClient.getInstance(this)
<<<<<<< SEARCH import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors import com.facebook.soloader.SoLoader ======= import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin import com.facebook.flipper.plugins.litho.LithoFlipperDescriptors import com.facebook.litho.config.ComponentsConfiguration import com.facebook.litho.sections.config.SectionsConfiguration import com.facebook.litho.widget.SectionsDebug import com.facebook.soloader.SoLoader >>>>>>> REPLACE
wikimedia/apps-android-wikipedia
78624fea15357cfa45c420af0f5c1120da67effa
app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt
kotlin
apache-2.0
Handle MW error message and change pageId from Long to Int
package org.wikipedia.commons import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import java.util.* object ImageTagsProvider { fun getImageTagsObservable(pageId: Long, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) .flatMap { claims -> val depicts = claims.claims()["P180"] val ids = mutableListOf<String?>() depicts?.forEach { ids.add(it.mainSnak?.dataValue?.value?.id) } if (ids.isEmpty()) { Observable.empty() } else { ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabels(ids.joinToString(separator = "|"), langCode) } } .subscribeOn(Schedulers.io()) .map { entities -> val tags = HashMap<String, MutableList<String>>() entities.entities().forEach { it.value.labels().values.forEach { label -> if (tags[label.language()].isNullOrEmpty()) { tags[label.language()] = mutableListOf(label.value()) } else { tags[label.language()]!!.add(label.value()) } } } tags } } }
package org.wikipedia.commons import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.wikidata.Claims import org.wikipedia.dataclient.wikidata.Entities import org.wikipedia.util.log.L import java.util.* object ImageTagsProvider { fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) .onErrorReturnItem(Claims()) .flatMap { claims -> val depicts = claims.claims()["P180"] val ids = mutableListOf<String?>() depicts?.forEach { ids.add(it.mainSnak?.dataValue?.value?.id) } if (ids.isEmpty()) { Observable.just(Entities()) } else { ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabels(ids.joinToString(separator = "|"), langCode) } } .subscribeOn(Schedulers.io()) .map { entities -> val tags = HashMap<String, MutableList<String>>() entities.entities().forEach { it.value.labels().values.forEach { label -> if (tags[label.language()].isNullOrEmpty()) { tags[label.language()] = mutableListOf(label.value()) } else { tags[label.language()]!!.add(label.value()) } } } tags } } }
6
2
3
mixed
--- a/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt +++ b/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt @@ -7,2 +7,5 @@ import org.wikipedia.dataclient.WikiSite +import org.wikipedia.dataclient.wikidata.Claims +import org.wikipedia.dataclient.wikidata.Entities +import org.wikipedia.util.log.L import java.util.* @@ -10,5 +13,6 @@ object ImageTagsProvider { - fun getImageTagsObservable(pageId: Long, langCode: String): Observable<Map<String, List<String>>> { + fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) + .onErrorReturnItem(Claims()) .flatMap { claims -> @@ -20,3 +24,3 @@ if (ids.isEmpty()) { - Observable.empty() + Observable.just(Entities()) } else {
--- a/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt +++ b/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt @@ ... @@ import org.wikipedia.dataclient.WikiSite +import org.wikipedia.dataclient.wikidata.Claims +import org.wikipedia.dataclient.wikidata.Entities +import org.wikipedia.util.log.L import java.util.* @@ ... @@ object ImageTagsProvider { - fun getImageTagsObservable(pageId: Long, langCode: String): Observable<Map<String, List<String>>> { + fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) + .onErrorReturnItem(Claims()) .flatMap { claims -> @@ ... @@ if (ids.isEmpty()) { - Observable.empty() + Observable.just(Entities()) } else {
--- a/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt +++ b/app/src/main/java/org/wikipedia/commons/ImageTagsProvider.kt @@ -7,2 +7,5 @@ CON import org.wikipedia.dataclient.WikiSite ADD import org.wikipedia.dataclient.wikidata.Claims ADD import org.wikipedia.dataclient.wikidata.Entities ADD import org.wikipedia.util.log.L CON import java.util.* @@ -10,5 +13,6 @@ CON object ImageTagsProvider { DEL fun getImageTagsObservable(pageId: Long, langCode: String): Observable<Map<String, List<String>>> { ADD fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> { CON return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") CON .subscribeOn(Schedulers.io()) ADD .onErrorReturnItem(Claims()) CON .flatMap { claims -> @@ -20,3 +24,3 @@ CON if (ids.isEmpty()) { DEL Observable.empty() ADD Observable.just(Entities()) CON } else {
<<<<<<< SEARCH import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import java.util.* object ImageTagsProvider { fun getImageTagsObservable(pageId: Long, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) .flatMap { claims -> val depicts = claims.claims()["P180"] ======= import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.wikidata.Claims import org.wikipedia.dataclient.wikidata.Entities import org.wikipedia.util.log.L import java.util.* object ImageTagsProvider { fun getImageTagsObservable(pageId: Int, langCode: String): Observable<Map<String, List<String>>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId") .subscribeOn(Schedulers.io()) .onErrorReturnItem(Claims()) .flatMap { claims -> val depicts = claims.claims()["P180"] >>>>>>> REPLACE
apache/ddlutils
53e1461ab8b11651cf76801c938063b7e0f801d3
src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java
java
apache-2.0
Add call identity to hsqldb. git-svn-id: b9063b25153de5216c397e252c209c32bc9c47ff@330902 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.ddlutils.platform; /* * Copyright 1999-2005 The Apache Software Foundation. * * 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. */ import java.io.IOException; import org.apache.ddlutils.PlatformInfo; import org.apache.ddlutils.model.Table; /** * The SQL Builder for the HsqlDb database. * * @author James Strachan * @author Thomas Dudziak * @version $Revision$ */ public class HsqlDbBuilder extends SqlBuilder { /** * Creates a new builder instance. * * @param info The platform info */ public HsqlDbBuilder(PlatformInfo info) { super(info); } /** * {@inheritDoc} */ public void dropTable(Table table) throws IOException { print("DROP TABLE "); printIdentifier(getTableName(table)); print(" IF EXISTS"); printEndOfStatement(); } }
package org.apache.ddlutils.platform; /* * Copyright 1999-2005 The Apache Software Foundation. * * 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. */ import java.io.IOException; import org.apache.ddlutils.PlatformInfo; import org.apache.ddlutils.model.Table; /** * The SQL Builder for the HsqlDb database. * * @author James Strachan * @author Thomas Dudziak * @version $Revision$ */ public class HsqlDbBuilder extends SqlBuilder { /** * Creates a new builder instance. * * @param info The platform info */ public HsqlDbBuilder(PlatformInfo info) { super(info); } /** * {@inheritDoc} */ public void dropTable(Table table) throws IOException { print("DROP TABLE "); printIdentifier(getTableName(table)); print(" IF EXISTS"); printEndOfStatement(); } /** * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table) */ public String getSelectLastInsertId(Table table) { return "CALL IDENTITY()"; } }
10
0
1
add_only
--- a/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java +++ b/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java @@ -52,2 +52,12 @@ } + + /** + * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table) + */ + public String getSelectLastInsertId(Table table) + { + return "CALL IDENTITY()"; + } + + }
--- a/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java +++ b/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java @@ ... @@ } + + /** + * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table) + */ + public String getSelectLastInsertId(Table table) + { + return "CALL IDENTITY()"; + } + + }
--- a/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java +++ b/src/java/org/apache/ddlutils/platform/HsqlDbBuilder.java @@ -52,2 +52,12 @@ CON } ADD ADD /** ADD * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table) ADD */ ADD public String getSelectLastInsertId(Table table) ADD { ADD return "CALL IDENTITY()"; ADD } ADD ADD CON }
<<<<<<< SEARCH printEndOfStatement(); } } ======= printEndOfStatement(); } /** * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table) */ public String getSelectLastInsertId(Table table) { return "CALL IDENTITY()"; } } >>>>>>> REPLACE