repo
stringlengths
8
50
commit
stringlengths
40
40
path
stringlengths
5
171
lang
stringclasses
5 values
license
stringclasses
13 values
message
stringlengths
21
1.33k
old_code
stringlengths
15
2.4k
new_code
stringlengths
140
2.61k
n_added
int64
0
81
n_removed
int64
0
58
n_hunks
int64
1
8
change_kind
stringclasses
3 values
udiff
stringlengths
88
3.33k
udiff-h
stringlengths
85
3.32k
udiff-l
stringlengths
95
3.57k
search-replace
stringlengths
89
3.36k
myntra/react-native
254d4551036abbd61eb1b809d7640d5adb863ba3
Libraries/StyleSheet/splitLayoutProps.js
javascript
mit
Add type annotations to prevent issues with planned Flow changes Summary: We're planning a fix in Flow (D24112595) that uncovers some existing errors that were previously suppressed. Adding these annotations prevents them from surfacing during the deploy of the fix. Changelog: [Internal] Reviewed By: dsainati1 Differential Revision: D24147994 fbshipit-source-id: fef59a9427da6db79d4824e39768dd5ad0a8d1a3
/** * 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. * * @format * @flow strict-local */ 'use strict'; import type {DangerouslyImpreciseStyle} from './StyleSheet'; const OUTER_PROPS = Object.assign(Object.create(null), { margin: true, marginHorizontal: true, marginVertical: true, marginBottom: true, marginTop: true, marginLeft: true, marginRight: true, flex: true, flexGrow: true, flexShrink: true, flexBasis: true, alignSelf: true, height: true, minHeight: true, maxHeight: true, width: true, minWidth: true, maxWidth: true, position: true, left: true, right: true, bottom: true, top: true, transform: true, }); function splitLayoutProps( props: ?DangerouslyImpreciseStyle, ): { outer: DangerouslyImpreciseStyle, inner: DangerouslyImpreciseStyle, ... } { const inner = {}; const outer = {}; if (props) { Object.keys(props).forEach(k => { const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; } else { inner[k] = value; } }); } return {outer, inner}; } module.exports = splitLayoutProps;
/** * 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. * * @format * @flow strict-local */ 'use strict'; import type {DangerouslyImpreciseStyle} from './StyleSheet'; const OUTER_PROPS = Object.assign(Object.create(null), { margin: true, marginHorizontal: true, marginVertical: true, marginBottom: true, marginTop: true, marginLeft: true, marginRight: true, flex: true, flexGrow: true, flexShrink: true, flexBasis: true, alignSelf: true, height: true, minHeight: true, maxHeight: true, width: true, minWidth: true, maxWidth: true, position: true, left: true, right: true, bottom: true, top: true, transform: true, }); function splitLayoutProps( props: ?DangerouslyImpreciseStyle, ): { outer: DangerouslyImpreciseStyle, inner: DangerouslyImpreciseStyle, ... } { const inner = {}; const outer = {}; if (props) { Object.keys(props).forEach((k: string) => { const value = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; } else { inner[k] = value; } }); } return {outer, inner}; } module.exports = splitLayoutProps;
2
2
1
mixed
--- a/Libraries/StyleSheet/splitLayoutProps.js +++ b/Libraries/StyleSheet/splitLayoutProps.js @@ -51,4 +51,4 @@ if (props) { - Object.keys(props).forEach(k => { - const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; + Object.keys(props).forEach((k: string) => { + const value = props[k]; if (OUTER_PROPS[k]) {
--- a/Libraries/StyleSheet/splitLayoutProps.js +++ b/Libraries/StyleSheet/splitLayoutProps.js @@ ... @@ if (props) { - Object.keys(props).forEach(k => { - const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; + Object.keys(props).forEach((k: string) => { + const value = props[k]; if (OUTER_PROPS[k]) {
--- a/Libraries/StyleSheet/splitLayoutProps.js +++ b/Libraries/StyleSheet/splitLayoutProps.js @@ -51,4 +51,4 @@ CON if (props) { DEL Object.keys(props).forEach(k => { DEL const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; ADD Object.keys(props).forEach((k: string) => { ADD const value = props[k]; CON if (OUTER_PROPS[k]) {
<<<<<<< SEARCH const outer = {}; if (props) { Object.keys(props).forEach(k => { const value: $ElementType<DangerouslyImpreciseStyle, typeof k> = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; ======= const outer = {}; if (props) { Object.keys(props).forEach((k: string) => { const value = props[k]; if (OUTER_PROPS[k]) { outer[k] = value; >>>>>>> REPLACE
rhdunn/marklogic-intellij-plugin
19b2a8eef50ef2e4c786ed6b3c29e757b48ea5ba
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt
kotlin
apache-2.0
Implement access to the MarkLogicServer data from the table model.
package uk.co.reecedunn.intellij.plugin.marklogic.settings import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicBundle import javax.swing.table.AbstractTableModel private val COLUMN_NAMES = arrayOf( MarkLogicBundle.message("marklogic.settings.server.name"), MarkLogicBundle.message("marklogic.settings.server.hostname"), MarkLogicBundle.message("marklogic.settings.server.appserver-port"), MarkLogicBundle.message("marklogic.settings.server.admin-port"), MarkLogicBundle.message("marklogic.settings.server.username"), MarkLogicBundle.message("marklogic.settings.server.password")) class MarkLogicServerTableModel : AbstractTableModel() { override fun getRowCount(): Int = 0 override fun getColumnCount(): Int = COLUMN_NAMES.size override fun getColumnName(column: Int): String = COLUMN_NAMES[column] override fun getValueAt(rowIndex: Int, columnIndex: Int): Any = Any() }
/* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.settings import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicBundle import javax.swing.table.AbstractTableModel private val COLUMN_NAMES = arrayOf( MarkLogicBundle.message("marklogic.settings.server.name"), MarkLogicBundle.message("marklogic.settings.server.hostname"), MarkLogicBundle.message("marklogic.settings.server.appserver-port"), MarkLogicBundle.message("marklogic.settings.server.admin-port"), MarkLogicBundle.message("marklogic.settings.server.username"), MarkLogicBundle.message("marklogic.settings.server.password")) class MarkLogicServerTableModel : AbstractTableModel() { var servers: Array<MarkLogicServer> = arrayOf() override fun getRowCount(): Int = servers.size override fun getColumnCount(): Int = COLUMN_NAMES.size override fun getColumnName(column: Int): String = COLUMN_NAMES[column] override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { if (rowIndex < 0 || rowIndex >= servers.size) return Any() return when (columnIndex) { 0 -> servers[rowIndex].displayName ?: "" 1 -> servers[rowIndex].hostname 2 -> servers[rowIndex].appServerPort 3 -> servers[rowIndex].adminPort 4 -> servers[rowIndex].username ?: "" 5 -> servers[rowIndex].password ?: "" else -> Any() } } }
31
3
3
mixed
--- a/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt +++ b/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt @@ -1 +1,16 @@ +/* + * Copyright (C) 2017 Reece H. Dunn + * + * 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 uk.co.reecedunn.intellij.plugin.marklogic.settings @@ -14,4 +29,6 @@ class MarkLogicServerTableModel : AbstractTableModel() { + var servers: Array<MarkLogicServer> = arrayOf() + override fun getRowCount(): Int = - 0 + servers.size @@ -23,4 +40,15 @@ - override fun getValueAt(rowIndex: Int, columnIndex: Int): Any = - Any() + override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { + if (rowIndex < 0 || rowIndex >= servers.size) + return Any() + return when (columnIndex) { + 0 -> servers[rowIndex].displayName ?: "" + 1 -> servers[rowIndex].hostname + 2 -> servers[rowIndex].appServerPort + 3 -> servers[rowIndex].adminPort + 4 -> servers[rowIndex].username ?: "" + 5 -> servers[rowIndex].password ?: "" + else -> Any() + } + } }
--- a/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt +++ b/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt @@ ... @@ +/* + * Copyright (C) 2017 Reece H. Dunn + * + * 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 uk.co.reecedunn.intellij.plugin.marklogic.settings @@ ... @@ class MarkLogicServerTableModel : AbstractTableModel() { + var servers: Array<MarkLogicServer> = arrayOf() + override fun getRowCount(): Int = - 0 + servers.size @@ ... @@ - override fun getValueAt(rowIndex: Int, columnIndex: Int): Any = - Any() + override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { + if (rowIndex < 0 || rowIndex >= servers.size) + return Any() + return when (columnIndex) { + 0 -> servers[rowIndex].displayName ?: "" + 1 -> servers[rowIndex].hostname + 2 -> servers[rowIndex].appServerPort + 3 -> servers[rowIndex].adminPort + 4 -> servers[rowIndex].username ?: "" + 5 -> servers[rowIndex].password ?: "" + else -> Any() + } + } }
--- a/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt +++ b/src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/settings/MarkLogicServerTableModel.kt @@ -1 +1,16 @@ ADD /* ADD * Copyright (C) 2017 Reece H. Dunn ADD * ADD * Licensed under the Apache License, Version 2.0 (the "License"); ADD * you may not use this file except in compliance with the License. ADD * You may obtain a copy of the License at ADD * ADD * http://www.apache.org/licenses/LICENSE-2.0 ADD * ADD * Unless required by applicable law or agreed to in writing, software ADD * distributed under the License is distributed on an "AS IS" BASIS, ADD * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ADD * See the License for the specific language governing permissions and ADD * limitations under the License. ADD */ CON package uk.co.reecedunn.intellij.plugin.marklogic.settings @@ -14,4 +29,6 @@ CON class MarkLogicServerTableModel : AbstractTableModel() { ADD var servers: Array<MarkLogicServer> = arrayOf() ADD CON override fun getRowCount(): Int = DEL 0 ADD servers.size CON @@ -23,4 +40,15 @@ CON DEL override fun getValueAt(rowIndex: Int, columnIndex: Int): Any = DEL Any() ADD override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { ADD if (rowIndex < 0 || rowIndex >= servers.size) ADD return Any() ADD return when (columnIndex) { ADD 0 -> servers[rowIndex].displayName ?: "" ADD 1 -> servers[rowIndex].hostname ADD 2 -> servers[rowIndex].appServerPort ADD 3 -> servers[rowIndex].adminPort ADD 4 -> servers[rowIndex].username ?: "" ADD 5 -> servers[rowIndex].password ?: "" ADD else -> Any() ADD } ADD } CON }
<<<<<<< SEARCH package uk.co.reecedunn.intellij.plugin.marklogic.settings ======= /* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.settings >>>>>>> REPLACE <<<<<<< SEARCH class MarkLogicServerTableModel : AbstractTableModel() { override fun getRowCount(): Int = 0 override fun getColumnCount(): Int = ======= class MarkLogicServerTableModel : AbstractTableModel() { var servers: Array<MarkLogicServer> = arrayOf() override fun getRowCount(): Int = servers.size override fun getColumnCount(): Int = >>>>>>> REPLACE <<<<<<< SEARCH COLUMN_NAMES[column] override fun getValueAt(rowIndex: Int, columnIndex: Int): Any = Any() } ======= COLUMN_NAMES[column] override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { if (rowIndex < 0 || rowIndex >= servers.size) return Any() return when (columnIndex) { 0 -> servers[rowIndex].displayName ?: "" 1 -> servers[rowIndex].hostname 2 -> servers[rowIndex].appServerPort 3 -> servers[rowIndex].adminPort 4 -> servers[rowIndex].username ?: "" 5 -> servers[rowIndex].password ?: "" else -> Any() } } } >>>>>>> REPLACE
iotize/react-native-navigation
cc87b8513b2e334e8bfd3a725ea6bf48170ce5e8
android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java
java
mit
Add option to set custom splash layout
package com.reactnativenavigation.controllers; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.reactnativenavigation.NavigationApplication; public abstract class SplashActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); NavigationApplication.instance.startReactContext(); //TODO show fancy splash View view = new View(this); view.setBackgroundColor(Color.WHITE); setContentView(view); } }
package com.reactnativenavigation.controllers; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.reactnativenavigation.NavigationApplication; public abstract class SplashActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); NavigationApplication.instance.startReactContext(); setSplashLayout(); } private void setSplashLayout() { final int splashLayout = getSplashLayout(); if (splashLayout > 0) { setContentView(splashLayout); } else { setDefaultSplashLayout(); } } private void setDefaultSplashLayout() { View view = new View(this); view.setBackgroundColor(Color.WHITE); setContentView(view); } /** * * @return -1 if you don't need a splash layout */ public abstract @LayoutRes int getSplashLayout(); }
20
1
3
mixed
--- a/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java +++ b/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java @@ -4,2 +4,3 @@ import android.os.Bundle; +import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; @@ -16,3 +17,15 @@ NavigationApplication.instance.startReactContext(); - //TODO show fancy splash + setSplashLayout(); + } + + private void setSplashLayout() { + final int splashLayout = getSplashLayout(); + if (splashLayout > 0) { + setContentView(splashLayout); + } else { + setDefaultSplashLayout(); + } + } + + private void setDefaultSplashLayout() { View view = new View(this); @@ -21,2 +34,8 @@ } + + /** + * + * @return -1 if you don't need a splash layout + */ + public abstract @LayoutRes int getSplashLayout(); }
--- a/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java +++ b/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java @@ ... @@ import android.os.Bundle; +import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; @@ ... @@ NavigationApplication.instance.startReactContext(); - //TODO show fancy splash + setSplashLayout(); + } + + private void setSplashLayout() { + final int splashLayout = getSplashLayout(); + if (splashLayout > 0) { + setContentView(splashLayout); + } else { + setDefaultSplashLayout(); + } + } + + private void setDefaultSplashLayout() { View view = new View(this); @@ ... @@ } + + /** + * + * @return -1 if you don't need a splash layout + */ + public abstract @LayoutRes int getSplashLayout(); }
--- a/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java +++ b/android/app/src/main/java/com/reactnativenavigation/controllers/SplashActivity.java @@ -4,2 +4,3 @@ CON import android.os.Bundle; ADD import android.support.annotation.LayoutRes; CON import android.support.annotation.Nullable; @@ -16,3 +17,15 @@ CON NavigationApplication.instance.startReactContext(); DEL //TODO show fancy splash ADD setSplashLayout(); ADD } ADD ADD private void setSplashLayout() { ADD final int splashLayout = getSplashLayout(); ADD if (splashLayout > 0) { ADD setContentView(splashLayout); ADD } else { ADD setDefaultSplashLayout(); ADD } ADD } ADD ADD private void setDefaultSplashLayout() { CON View view = new View(this); @@ -21,2 +34,8 @@ CON } ADD ADD /** ADD * ADD * @return -1 if you don't need a splash layout ADD */ ADD public abstract @LayoutRes int getSplashLayout(); CON }
<<<<<<< SEARCH import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; ======= import android.graphics.Color; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; >>>>>>> REPLACE <<<<<<< SEARCH super.onCreate(savedInstanceState); NavigationApplication.instance.startReactContext(); //TODO show fancy splash View view = new View(this); view.setBackgroundColor(Color.WHITE); setContentView(view); } } ======= super.onCreate(savedInstanceState); NavigationApplication.instance.startReactContext(); setSplashLayout(); } private void setSplashLayout() { final int splashLayout = getSplashLayout(); if (splashLayout > 0) { setContentView(splashLayout); } else { setDefaultSplashLayout(); } } private void setDefaultSplashLayout() { View view = new View(this); view.setBackgroundColor(Color.WHITE); setContentView(view); } /** * * @return -1 if you don't need a splash layout */ public abstract @LayoutRes int getSplashLayout(); } >>>>>>> REPLACE
CS2103JAN2017-W09-B4/main
5c377c135fd84c25363c9b086a4fce061551c4bb
src/main/java/seedu/address/ui/TaskCard.java
java
mit
Fix junit - By removing retarded stuffs from taskcard class
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label date; @FXML private Label info; @FXML private Label priority; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText("Deadline: " + task.getDate().value); info.setText("Information : " + task.getInfo().value); priority.setText("Priority Level : " + task.getPriority().value); initTags(task); } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label date; @FXML private Label info; @FXML private Label priority; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText(task.getDate().value); info.setText(task.getInfo().value); priority.setText(task.getPriority().value); initTags(task); } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
3
3
1
mixed
--- a/src/main/java/seedu/address/ui/TaskCard.java +++ b/src/main/java/seedu/address/ui/TaskCard.java @@ -32,5 +32,5 @@ id.setText(displayedIndex + ". "); - date.setText("Deadline: " + task.getDate().value); - info.setText("Information : " + task.getInfo().value); - priority.setText("Priority Level : " + task.getPriority().value); + date.setText(task.getDate().value); + info.setText(task.getInfo().value); + priority.setText(task.getPriority().value); initTags(task);
--- a/src/main/java/seedu/address/ui/TaskCard.java +++ b/src/main/java/seedu/address/ui/TaskCard.java @@ ... @@ id.setText(displayedIndex + ". "); - date.setText("Deadline: " + task.getDate().value); - info.setText("Information : " + task.getInfo().value); - priority.setText("Priority Level : " + task.getPriority().value); + date.setText(task.getDate().value); + info.setText(task.getInfo().value); + priority.setText(task.getPriority().value); initTags(task);
--- a/src/main/java/seedu/address/ui/TaskCard.java +++ b/src/main/java/seedu/address/ui/TaskCard.java @@ -32,5 +32,5 @@ CON id.setText(displayedIndex + ". "); DEL date.setText("Deadline: " + task.getDate().value); DEL info.setText("Information : " + task.getInfo().value); DEL priority.setText("Priority Level : " + task.getPriority().value); ADD date.setText(task.getDate().value); ADD info.setText(task.getInfo().value); ADD priority.setText(task.getPriority().value); CON initTags(task);
<<<<<<< SEARCH name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText("Deadline: " + task.getDate().value); info.setText("Information : " + task.getInfo().value); priority.setText("Priority Level : " + task.getPriority().value); initTags(task); } ======= name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText(task.getDate().value); info.setText(task.getInfo().value); priority.setText(task.getPriority().value); initTags(task); } >>>>>>> REPLACE
hyoshizumi/hig
cb67c9c2edb1b0cc68729f68a887a38d52422117
src/implementations/react/src/playground/sections/CheckboxSection.js
javascript
apache-2.0
Add uncontrolled with default example
import React, { Component } from "react"; import PlaygroundSection from "../PlaygroundSection"; import { Checkbox } from "../../react-hig"; const checkboxStyle = { display: "flex", flexDirection: "row", justifyContent: "space-between" }; function logEvent(event) { let messageParts = [`Checkbox triggered a ${event.type} event`]; if (event.target.value !== undefined) { messageParts = messageParts.concat(`: ${event.target.value}`); } console.log(messageParts.join("")); } class CheckboxSection extends Component { constructor(props) { super(props); this.state = { controlledChecked: false } } setControlledChecked = event => { this.setState({ controlledChecked: event.target.checked }); }; render() { return ( <PlaygroundSection title="Checkbox"> <div style={checkboxStyle}> <Checkbox label="Required" required="You must check this box" /> <Checkbox label="Disabled" disabled={true} /> <Checkbox label="Controlled" checked={this.state.controlledChecked} onChange={this.setControlledChecked} /> <Checkbox label="Uncontrolled" /> <Checkbox label="With event logging" onHover={logEvent} onChange={logEvent} onFocus={logEvent} /> </div> </PlaygroundSection> ); } } export default CheckboxSection;
import React, { Component } from "react"; import PlaygroundSection from "../PlaygroundSection"; import { Checkbox } from "../../react-hig"; const checkboxStyle = { display: "flex", flexDirection: "row", justifyContent: "space-between" }; function logEvent(event) { let messageParts = [`Checkbox triggered a ${event.type} event`]; if (event.target.value !== undefined) { messageParts = messageParts.concat(`: ${event.target.value}`); } console.log(messageParts.join("")); } class CheckboxSection extends Component { constructor(props) { super(props); this.state = { controlledChecked: false } } setControlledChecked = event => { this.setState({ controlledChecked: event.target.checked }); }; render() { return ( <PlaygroundSection title="Checkbox"> <div style={checkboxStyle}> <Checkbox label="Required" required="You must check this box" /> <Checkbox label="Disabled" disabled={true} /> <Checkbox label="Controlled" checked={this.state.controlledChecked} onChange={this.setControlledChecked} /> <Checkbox label="Uncontrolled" /> <Checkbox label="Uncontrolled w/ default" defaultChecked={true} /> <Checkbox label="With event logging" onHover={logEvent} onChange={logEvent} onFocus={logEvent} /> </div> </PlaygroundSection> ); } } export default CheckboxSection;
4
0
1
add_only
--- a/src/implementations/react/src/playground/sections/CheckboxSection.js +++ b/src/implementations/react/src/playground/sections/CheckboxSection.js @@ -52,2 +52,6 @@ <Checkbox + label="Uncontrolled w/ default" + defaultChecked={true} + /> + <Checkbox label="With event logging"
--- a/src/implementations/react/src/playground/sections/CheckboxSection.js +++ b/src/implementations/react/src/playground/sections/CheckboxSection.js @@ ... @@ <Checkbox + label="Uncontrolled w/ default" + defaultChecked={true} + /> + <Checkbox label="With event logging"
--- a/src/implementations/react/src/playground/sections/CheckboxSection.js +++ b/src/implementations/react/src/playground/sections/CheckboxSection.js @@ -52,2 +52,6 @@ CON <Checkbox ADD label="Uncontrolled w/ default" ADD defaultChecked={true} ADD /> ADD <Checkbox CON label="With event logging"
<<<<<<< SEARCH /> <Checkbox label="With event logging" onHover={logEvent} ======= /> <Checkbox label="Uncontrolled w/ default" defaultChecked={true} /> <Checkbox label="With event logging" onHover={logEvent} >>>>>>> REPLACE
jaapverloop/massa
9b4333f25f22269f02f605579d4756da43701241
manage.py
python
mit
Add a reset task to drop and recreate the db tables with one command.
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_reloader = True, host = '0.0.0.0', port = 8080, )) @manager.command def db_create_tables(): """Create all the db tables.""" current_app.preprocess_request() db = g.sl('db') db.create_tables() @manager.command def db_drop_tables(): """Drop all the db tables.""" if prompt_bool('Are you sure you want to drop all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() if __name__ == '__main__': manager.run()
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_reloader = True, host = '0.0.0.0', port = 8080, )) @manager.command def db_create_tables(): """Create all the db tables.""" current_app.preprocess_request() db = g.sl('db') db.create_tables() @manager.command def db_drop_tables(): """Drop all the db tables.""" if prompt_bool('Are you sure you want to drop all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() @manager.command def db_reset_tables(): """Drop and (re)create all the db tables.""" if prompt_bool('Are you sure you want to reset all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() db.create_tables() if __name__ == '__main__': manager.run()
10
0
1
add_only
--- a/manage.py +++ b/manage.py @@ -35,2 +35,12 @@ [email protected] +def db_reset_tables(): + """Drop and (re)create all the db tables.""" + if prompt_bool('Are you sure you want to reset all the db tables?'): + current_app.preprocess_request() + db = g.sl('db') + db.drop_tables() + db.create_tables() + + if __name__ == '__main__':
--- a/manage.py +++ b/manage.py @@ ... @@ [email protected] +def db_reset_tables(): + """Drop and (re)create all the db tables.""" + if prompt_bool('Are you sure you want to reset all the db tables?'): + current_app.preprocess_request() + db = g.sl('db') + db.drop_tables() + db.create_tables() + + if __name__ == '__main__':
--- a/manage.py +++ b/manage.py @@ -35,2 +35,12 @@ CON ADD @manager.command ADD def db_reset_tables(): ADD """Drop and (re)create all the db tables.""" ADD if prompt_bool('Are you sure you want to reset all the db tables?'): ADD current_app.preprocess_request() ADD db = g.sl('db') ADD db.drop_tables() ADD db.create_tables() ADD ADD CON if __name__ == '__main__':
<<<<<<< SEARCH if __name__ == '__main__': manager.run() ======= @manager.command def db_reset_tables(): """Drop and (re)create all the db tables.""" if prompt_bool('Are you sure you want to reset all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() db.create_tables() if __name__ == '__main__': manager.run() >>>>>>> REPLACE
lowRISC/opentitan
ca635477fc02ac696f52962a1c80a40ed9099746
sw/host/opentitantool/src/command/update_usr_access.rs
rust
apache-2.0
[opentitantool] Add an optional parameter to update-usr-access command Signed-off-by: Alphan Ulusoy <[email protected]>
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use std::fs; use std::path::PathBuf; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; /// Update the USR_ACCESS value of an FPGA bitstream with the current timestamp. #[derive(Debug, StructOpt)] pub struct UpdateUsrAccess { #[structopt(name = "INPUT_FILE")] input: PathBuf, #[structopt(name = "OUTPUT_FILE")] output: PathBuf, } impl CommandDispatch for UpdateUsrAccess { fn run( &self, _context: &dyn Any, _transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { let mut bs = fs::read(&self.input)?; usr_access_set(&mut bs, usr_access_timestamp())?; fs::write(&self.output, bs)?; Ok(None) } }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use std::fs; use std::path::PathBuf; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::util::parse_int::ParseInt; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; /// Update the USR_ACCESS value of an FPGA bitstream with the current timestamp. #[derive(Debug, StructOpt)] pub struct UpdateUsrAccess { #[structopt(name = "INPUT_FILE")] input: PathBuf, #[structopt(name = "OUTPUT_FILE")] output: PathBuf, #[structopt(long, parse(try_from_str = u32::from_str), help="New USR_ACCESS value, default = timestamp")] usr_access: Option<u32>, } impl CommandDispatch for UpdateUsrAccess { fn run( &self, _context: &dyn Any, _transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { let mut bs = fs::read(&self.input)?; usr_access_set( &mut bs, self.usr_access.unwrap_or_else(|| usr_access_timestamp()), )?; fs::write(&self.output, bs)?; Ok(None) } }
10
1
3
mixed
--- a/sw/host/opentitantool/src/command/update_usr_access.rs +++ b/sw/host/opentitantool/src/command/update_usr_access.rs @@ -13,2 +13,3 @@ use opentitanlib::app::TransportWrapper; +use opentitanlib::util::parse_int::ParseInt; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; @@ -23,2 +24,7 @@ output: PathBuf, + + #[structopt(long, + parse(try_from_str = u32::from_str), + help="New USR_ACCESS value, default = timestamp")] + usr_access: Option<u32>, } @@ -32,3 +38,6 @@ let mut bs = fs::read(&self.input)?; - usr_access_set(&mut bs, usr_access_timestamp())?; + usr_access_set( + &mut bs, + self.usr_access.unwrap_or_else(|| usr_access_timestamp()), + )?; fs::write(&self.output, bs)?;
--- a/sw/host/opentitantool/src/command/update_usr_access.rs +++ b/sw/host/opentitantool/src/command/update_usr_access.rs @@ ... @@ use opentitanlib::app::TransportWrapper; +use opentitanlib::util::parse_int::ParseInt; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; @@ ... @@ output: PathBuf, + + #[structopt(long, + parse(try_from_str = u32::from_str), + help="New USR_ACCESS value, default = timestamp")] + usr_access: Option<u32>, } @@ ... @@ let mut bs = fs::read(&self.input)?; - usr_access_set(&mut bs, usr_access_timestamp())?; + usr_access_set( + &mut bs, + self.usr_access.unwrap_or_else(|| usr_access_timestamp()), + )?; fs::write(&self.output, bs)?;
--- a/sw/host/opentitantool/src/command/update_usr_access.rs +++ b/sw/host/opentitantool/src/command/update_usr_access.rs @@ -13,2 +13,3 @@ CON use opentitanlib::app::TransportWrapper; ADD use opentitanlib::util::parse_int::ParseInt; CON use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; @@ -23,2 +24,7 @@ CON output: PathBuf, ADD ADD #[structopt(long, ADD parse(try_from_str = u32::from_str), ADD help="New USR_ACCESS value, default = timestamp")] ADD usr_access: Option<u32>, CON } @@ -32,3 +38,6 @@ CON let mut bs = fs::read(&self.input)?; DEL usr_access_set(&mut bs, usr_access_timestamp())?; ADD usr_access_set( ADD &mut bs, ADD self.usr_access.unwrap_or_else(|| usr_access_timestamp()), ADD )?; CON fs::write(&self.output, bs)?;
<<<<<<< SEARCH use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; ======= use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::util::parse_int::ParseInt; use opentitanlib::util::usr_access::{usr_access_set, usr_access_timestamp}; >>>>>>> REPLACE <<<<<<< SEARCH #[structopt(name = "OUTPUT_FILE")] output: PathBuf, } ======= #[structopt(name = "OUTPUT_FILE")] output: PathBuf, #[structopt(long, parse(try_from_str = u32::from_str), help="New USR_ACCESS value, default = timestamp")] usr_access: Option<u32>, } >>>>>>> REPLACE <<<<<<< SEARCH ) -> Result<Option<Box<dyn Serialize>>> { let mut bs = fs::read(&self.input)?; usr_access_set(&mut bs, usr_access_timestamp())?; fs::write(&self.output, bs)?; Ok(None) ======= ) -> Result<Option<Box<dyn Serialize>>> { let mut bs = fs::read(&self.input)?; usr_access_set( &mut bs, self.usr_access.unwrap_or_else(|| usr_access_timestamp()), )?; fs::write(&self.output, bs)?; Ok(None) >>>>>>> REPLACE
iKevinY/ghoti.rs
5983884516d839d66d5b9f39cc0c0b0b470e1665
src/main.rs
rust
mit
Add initial implementation of CLI
fn main() { println!("Hello, world!"); }
extern crate getopts; use getopts::Options; use std::env; use std::fs::File; use std::path::Path; fn print_usage(program: &str, opts: Options) { let usage = format!("Usage: {} [options] <filename>", program); print!("{}", opts.usage(&usage)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("v", "version", "print version info"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("version") { println!("ghoti {}", env!("CARGO_PKG_VERSION")); return; } if matches.opt_present("help") || matches.free.is_empty() { print_usage(&program, opts); return; } let filename = matches.free[0].clone(); match File::open(Path::new(&filename)) { Ok(_) => println!("Hello, {}!", filename), Err(_) => panic!("Couldn't open {}.", filename), }; }
42
1
1
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,44 @@ +extern crate getopts; + +use getopts::Options; + +use std::env; +use std::fs::File; +use std::path::Path; + + +fn print_usage(program: &str, opts: Options) { + let usage = format!("Usage: {} [options] <filename>", program); + print!("{}", opts.usage(&usage)); +} + fn main() { - println!("Hello, world!"); + let args: Vec<String> = env::args().collect(); + let program = args[0].clone(); + + let mut opts = Options::new(); + opts.optflag("h", "help", "print this help menu"); + opts.optflag("v", "version", "print version info"); + + let matches = match opts.parse(&args[1..]) { + Ok(m) => m, + Err(f) => panic!(f.to_string()), + }; + + if matches.opt_present("version") { + println!("ghoti {}", env!("CARGO_PKG_VERSION")); + return; + } + + if matches.opt_present("help") || matches.free.is_empty() { + print_usage(&program, opts); + return; + } + + let filename = matches.free[0].clone(); + + match File::open(Path::new(&filename)) { + Ok(_) => println!("Hello, {}!", filename), + Err(_) => panic!("Couldn't open {}.", filename), + }; }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ +extern crate getopts; + +use getopts::Options; + +use std::env; +use std::fs::File; +use std::path::Path; + + +fn print_usage(program: &str, opts: Options) { + let usage = format!("Usage: {} [options] <filename>", program); + print!("{}", opts.usage(&usage)); +} + fn main() { - println!("Hello, world!"); + let args: Vec<String> = env::args().collect(); + let program = args[0].clone(); + + let mut opts = Options::new(); + opts.optflag("h", "help", "print this help menu"); + opts.optflag("v", "version", "print version info"); + + let matches = match opts.parse(&args[1..]) { + Ok(m) => m, + Err(f) => panic!(f.to_string()), + }; + + if matches.opt_present("version") { + println!("ghoti {}", env!("CARGO_PKG_VERSION")); + return; + } + + if matches.opt_present("help") || matches.free.is_empty() { + print_usage(&program, opts); + return; + } + + let filename = matches.free[0].clone(); + + match File::open(Path::new(&filename)) { + Ok(_) => println!("Hello, {}!", filename), + Err(_) => panic!("Couldn't open {}.", filename), + }; }
--- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,44 @@ ADD extern crate getopts; ADD ADD use getopts::Options; ADD ADD use std::env; ADD use std::fs::File; ADD use std::path::Path; ADD ADD ADD fn print_usage(program: &str, opts: Options) { ADD let usage = format!("Usage: {} [options] <filename>", program); ADD print!("{}", opts.usage(&usage)); ADD } ADD CON fn main() { DEL println!("Hello, world!"); ADD let args: Vec<String> = env::args().collect(); ADD let program = args[0].clone(); ADD ADD let mut opts = Options::new(); ADD opts.optflag("h", "help", "print this help menu"); ADD opts.optflag("v", "version", "print version info"); ADD ADD let matches = match opts.parse(&args[1..]) { ADD Ok(m) => m, ADD Err(f) => panic!(f.to_string()), ADD }; ADD ADD if matches.opt_present("version") { ADD println!("ghoti {}", env!("CARGO_PKG_VERSION")); ADD return; ADD } ADD ADD if matches.opt_present("help") || matches.free.is_empty() { ADD print_usage(&program, opts); ADD return; ADD } ADD ADD let filename = matches.free[0].clone(); ADD ADD match File::open(Path::new(&filename)) { ADD Ok(_) => println!("Hello, {}!", filename), ADD Err(_) => panic!("Couldn't open {}.", filename), ADD }; CON }
<<<<<<< SEARCH fn main() { println!("Hello, world!"); } ======= extern crate getopts; use getopts::Options; use std::env; use std::fs::File; use std::path::Path; fn print_usage(program: &str, opts: Options) { let usage = format!("Usage: {} [options] <filename>", program); print!("{}", opts.usage(&usage)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("v", "version", "print version info"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("version") { println!("ghoti {}", env!("CARGO_PKG_VERSION")); return; } if matches.opt_present("help") || matches.free.is_empty() { print_usage(&program, opts); return; } let filename = matches.free[0].clone(); match File::open(Path::new(&filename)) { Ok(_) => println!("Hello, {}!", filename), Err(_) => panic!("Couldn't open {}.", filename), }; } >>>>>>> REPLACE
pchen66/panolens.js
2a96b727c4ee83a6332e30753c6c9aec1e9d411d
src/interface/Reticle.js
javascript
mit
Fix reticle render order and depthTest
(function(){ /** * Reticle 3D Sprite * @param {THREE.Color} [color=0xfffff] - Color of the reticle sprite * @param {string} [url=PANOLENS.DataImage.Reticle] - Image asset url */ PANOLENS.Reticle = function ( color, url ) { var map, material; color = color || 0xffffff; url = url || PANOLENS.DataImage.Reticle; map = PANOLENS.Utils.TextureLoader.load( url ); material = new THREE.SpriteMaterial( { map: map, color: color } ); THREE.Sprite.call( this, material ); this.visible = false; } PANOLENS.Reticle.prototype = Object.create( THREE.Sprite.prototype ); PANOLENS.Reticle.prototype.constructor = PANOLENS.Reticle; PANOLENS.Reticle.prototype.show = function () { this.visible = true; }; PANOLENS.Reticle.prototype.hide = function () { this.visible = false; }; })();
(function(){ /** * Reticle 3D Sprite * @param {THREE.Color} [color=0xfffff] - Color of the reticle sprite * @param {string} [url=PANOLENS.DataImage.Reticle] - Image asset url */ PANOLENS.Reticle = function ( color, url ) { var map, material; color = color || 0xffffff; url = url || PANOLENS.DataImage.Reticle; map = PANOLENS.Utils.TextureLoader.load( url ); material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } ); THREE.Sprite.call( this, material ); this.visible = false; this.renderOrder = 10; } PANOLENS.Reticle.prototype = Object.create( THREE.Sprite.prototype ); PANOLENS.Reticle.prototype.constructor = PANOLENS.Reticle; PANOLENS.Reticle.prototype.show = function () { this.visible = true; }; PANOLENS.Reticle.prototype.hide = function () { this.visible = false; }; })();
3
2
2
mixed
--- a/src/interface/Reticle.js +++ b/src/interface/Reticle.js @@ -15,3 +15,3 @@ map = PANOLENS.Utils.TextureLoader.load( url ); - material = new THREE.SpriteMaterial( { map: map, color: color } ); + material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } ); @@ -19,3 +19,4 @@ - this.visible = false; + this.visible = false; + this.renderOrder = 10;
--- a/src/interface/Reticle.js +++ b/src/interface/Reticle.js @@ ... @@ map = PANOLENS.Utils.TextureLoader.load( url ); - material = new THREE.SpriteMaterial( { map: map, color: color } ); + material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } ); @@ ... @@ - this.visible = false; + this.visible = false; + this.renderOrder = 10;
--- a/src/interface/Reticle.js +++ b/src/interface/Reticle.js @@ -15,3 +15,3 @@ CON map = PANOLENS.Utils.TextureLoader.load( url ); DEL material = new THREE.SpriteMaterial( { map: map, color: color } ); ADD material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } ); CON @@ -19,3 +19,4 @@ CON DEL this.visible = false; ADD this.visible = false; ADD this.renderOrder = 10; CON
<<<<<<< SEARCH map = PANOLENS.Utils.TextureLoader.load( url ); material = new THREE.SpriteMaterial( { map: map, color: color } ); THREE.Sprite.call( this, material ); this.visible = false; } ======= map = PANOLENS.Utils.TextureLoader.load( url ); material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } ); THREE.Sprite.call( this, material ); this.visible = false; this.renderOrder = 10; } >>>>>>> REPLACE
andela-sadelokiki/InvertedIndex
26b87b8c25f1689f8c82ad846b49289b7d85a2be
jasmine/src/invertedIndex.js
javascript
mit
Create getIndex and Search functions
var data = [{ "title": "Alice in Wonderland", "text": "Alice falls into a rabbit hole and enters a world full of imagination." }, { "title": "The Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." } ]; var arr = []; var dict = {} for (var i in data) { for(var key in data[i]) { var words = data[i][key].split(" "); for(var j in words) { var word = words[j]; if(dict.hasOwnProperty(word)) { var posArr = dict[word]; if(parseInt(i)) { posArr.push(parseInt(i)); dict[word] = posArr } } else { dict[word] = [parseInt(i)]; } } } } dict;
var data = [{ "title": "Alice in Wonderland", "text": "Alice falls into a rabbit hole and enters a world full of imagination." }, { "title": "The Alice Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." } ]; var arr = []; var dict = {} var getIndex = function() { for (var i in data) { for (var key in data[i]) { var words = data[i][key].split(" "); for (var j in words) { var word = words[j].replace(/[:,.]/g, '') if (dict.hasOwnProperty(word)) { var posArr = dict[word]; if (parseInt(i)) { var position = parseInt(i) if (posArr.indexOf(position) < 0) { posArr.push(parseInt(i)); dict[word] = posArr } } } else { dict[word] = [parseInt(i)]; } } } } console.log(dict); return dict } getIndex(); var searchIndex = function(terms) { var check = {}; check[terms] = getIndex()[terms] console.log(check); return check; } searchIndex("man");
31
15
3
mixed
--- a/jasmine/src/invertedIndex.js +++ b/jasmine/src/invertedIndex.js @@ -6,3 +6,3 @@ { - "title": "The Lord of the Rings: The Fellowship of the Ring.", + "title": "The Alice Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." @@ -12,16 +12,21 @@ var dict = {} -for (var i in data) { - for(var key in data[i]) { - var words = data[i][key].split(" "); - for(var j in words) { - var word = words[j]; - if(dict.hasOwnProperty(word)) { - var posArr = dict[word]; - if(parseInt(i)) { - posArr.push(parseInt(i)); - dict[word] = posArr + +var getIndex = function() { + for (var i in data) { + for (var key in data[i]) { + var words = data[i][key].split(" "); + for (var j in words) { + var word = words[j].replace(/[:,.]/g, '') + if (dict.hasOwnProperty(word)) { + var posArr = dict[word]; + if (parseInt(i)) { + var position = parseInt(i) + if (posArr.indexOf(position) < 0) { + posArr.push(parseInt(i)); + dict[word] = posArr + } + } + } else { + dict[word] = [parseInt(i)]; } - } - else { - dict[word] = [parseInt(i)]; } @@ -29,3 +34,14 @@ } + console.log(dict); + return dict } -dict; + +getIndex(); + +var searchIndex = function(terms) { + var check = {}; + check[terms] = getIndex()[terms] + console.log(check); + return check; +} +searchIndex("man");
--- a/jasmine/src/invertedIndex.js +++ b/jasmine/src/invertedIndex.js @@ ... @@ { - "title": "The Lord of the Rings: The Fellowship of the Ring.", + "title": "The Alice Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." @@ ... @@ var dict = {} -for (var i in data) { - for(var key in data[i]) { - var words = data[i][key].split(" "); - for(var j in words) { - var word = words[j]; - if(dict.hasOwnProperty(word)) { - var posArr = dict[word]; - if(parseInt(i)) { - posArr.push(parseInt(i)); - dict[word] = posArr + +var getIndex = function() { + for (var i in data) { + for (var key in data[i]) { + var words = data[i][key].split(" "); + for (var j in words) { + var word = words[j].replace(/[:,.]/g, '') + if (dict.hasOwnProperty(word)) { + var posArr = dict[word]; + if (parseInt(i)) { + var position = parseInt(i) + if (posArr.indexOf(position) < 0) { + posArr.push(parseInt(i)); + dict[word] = posArr + } + } + } else { + dict[word] = [parseInt(i)]; } - } - else { - dict[word] = [parseInt(i)]; } @@ ... @@ } + console.log(dict); + return dict } -dict; + +getIndex(); + +var searchIndex = function(terms) { + var check = {}; + check[terms] = getIndex()[terms] + console.log(check); + return check; +} +searchIndex("man");
--- a/jasmine/src/invertedIndex.js +++ b/jasmine/src/invertedIndex.js @@ -6,3 +6,3 @@ CON { DEL "title": "The Lord of the Rings: The Fellowship of the Ring.", ADD "title": "The Alice Lord of the Rings: The Fellowship of the Ring.", CON "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." @@ -12,16 +12,21 @@ CON var dict = {} DEL for (var i in data) { DEL for(var key in data[i]) { DEL var words = data[i][key].split(" "); DEL for(var j in words) { DEL var word = words[j]; DEL if(dict.hasOwnProperty(word)) { DEL var posArr = dict[word]; DEL if(parseInt(i)) { DEL posArr.push(parseInt(i)); DEL dict[word] = posArr ADD ADD var getIndex = function() { ADD for (var i in data) { ADD for (var key in data[i]) { ADD var words = data[i][key].split(" "); ADD for (var j in words) { ADD var word = words[j].replace(/[:,.]/g, '') ADD if (dict.hasOwnProperty(word)) { ADD var posArr = dict[word]; ADD if (parseInt(i)) { ADD var position = parseInt(i) ADD if (posArr.indexOf(position) < 0) { ADD posArr.push(parseInt(i)); ADD dict[word] = posArr ADD } ADD } ADD } else { ADD dict[word] = [parseInt(i)]; CON } DEL } DEL else { DEL dict[word] = [parseInt(i)]; CON } @@ -29,3 +34,14 @@ CON } ADD console.log(dict); ADD return dict CON } DEL dict; ADD ADD getIndex(); ADD ADD var searchIndex = function(terms) { ADD var check = {}; ADD check[terms] = getIndex()[terms] ADD console.log(check); ADD return check; ADD } ADD searchIndex("man");
<<<<<<< SEARCH { "title": "The Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." } ]; var arr = []; var dict = {} for (var i in data) { for(var key in data[i]) { var words = data[i][key].split(" "); for(var j in words) { var word = words[j]; if(dict.hasOwnProperty(word)) { var posArr = dict[word]; if(parseInt(i)) { posArr.push(parseInt(i)); dict[word] = posArr } } else { dict[word] = [parseInt(i)]; } } } } dict; ======= { "title": "The Alice Lord of the Rings: The Fellowship of the Ring.", "text": "An unusual alliance of man, elf, dwarf, wizard and hobbit seek to destroy a powerful ring." } ]; var arr = []; var dict = {} var getIndex = function() { for (var i in data) { for (var key in data[i]) { var words = data[i][key].split(" "); for (var j in words) { var word = words[j].replace(/[:,.]/g, '') if (dict.hasOwnProperty(word)) { var posArr = dict[word]; if (parseInt(i)) { var position = parseInt(i) if (posArr.indexOf(position) < 0) { posArr.push(parseInt(i)); dict[word] = posArr } } } else { dict[word] = [parseInt(i)]; } } } } console.log(dict); return dict } getIndex(); var searchIndex = function(terms) { var check = {}; check[terms] = getIndex()[terms] console.log(check); return check; } searchIndex("man"); >>>>>>> REPLACE
soton-ecs-2014-gdp-12/videogular-questions-example
27d0089d1cc337a10ab6e597897c830aa7a3c33a
app/simple-example/simple-test.js
javascript
mit
Add questions having access to results
importScripts("/app/bower_components/videogular-questions/questions-worker.js"); loadAnnotations({ "first-question": { time: 8, questions: [ { id: "first-question", type: "single", question: "What is the moon made of?", options: [ { name: "cheese" }, { name: "cheeese" }, { name: "cheeeeeese" } ] }, { id: "check-question", type: "single", question: "Answer incorrect, do you want to review the video", options: [ { name: "Yes", action: function(video) { video.setTime(0); } }, { name: "No" } ], condition: function(questions) { // show if the answer to the previous question is not "cheese" return questions[0].answer !== "cheese"; } } ] } });
importScripts("/app/bower_components/videogular-questions/questions-worker.js"); loadAnnotations({ "first-question": { time: 4, questions: [ { id: "first-question", type: "single", question: "What is the moon made of?", options: [ { name: "cheese" }, { name: "cheeese" }, { name: "cheeeeeese" } ] }, { id: "check-question", type: "single", question: "Answer incorrect, do you want to review the video", options: [ { name: "Yes", action: function(video) { video.setTime(0); } }, { name: "No" } ], condition: function(questions, result) { // show if the answer to the previous question is not "cheese" return result !== "cheese"; } } ] } });
3
3
2
mixed
--- a/app/simple-example/simple-test.js +++ b/app/simple-example/simple-test.js @@ -5,3 +5,3 @@ "first-question": { - time: 8, + time: 4, questions: [ @@ -38,5 +38,5 @@ ], - condition: function(questions) { + condition: function(questions, result) { // show if the answer to the previous question is not "cheese" - return questions[0].answer !== "cheese"; + return result !== "cheese"; }
--- a/app/simple-example/simple-test.js +++ b/app/simple-example/simple-test.js @@ ... @@ "first-question": { - time: 8, + time: 4, questions: [ @@ ... @@ ], - condition: function(questions) { + condition: function(questions, result) { // show if the answer to the previous question is not "cheese" - return questions[0].answer !== "cheese"; + return result !== "cheese"; }
--- a/app/simple-example/simple-test.js +++ b/app/simple-example/simple-test.js @@ -5,3 +5,3 @@ CON "first-question": { DEL time: 8, ADD time: 4, CON questions: [ @@ -38,5 +38,5 @@ CON ], DEL condition: function(questions) { ADD condition: function(questions, result) { CON // show if the answer to the previous question is not "cheese" DEL return questions[0].answer !== "cheese"; ADD return result !== "cheese"; CON }
<<<<<<< SEARCH loadAnnotations({ "first-question": { time: 8, questions: [ { ======= loadAnnotations({ "first-question": { time: 4, questions: [ { >>>>>>> REPLACE <<<<<<< SEARCH } ], condition: function(questions) { // show if the answer to the previous question is not "cheese" return questions[0].answer !== "cheese"; } } ======= } ], condition: function(questions, result) { // show if the answer to the previous question is not "cheese" return result !== "cheese"; } } >>>>>>> REPLACE
alisaifee/flask-limiter
9a31799534c16d592aa34ba3c46bdc3f43309a87
setup.py
python
mit
Fix missing details in package info - Added extras for redis, memcached & mongodb - Add py.typed
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "[email protected]" __copyright__ = "Copyright 2022, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) setup( name="Flask-Limiter", author=__author__, author_email=__email__, license="MIT", url="https://flask-limiter.readthedocs.org", project_urls={ "Source": "https://github.com/alisaifee/flask-limiter", }, zip_safe=False, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), install_requires=list(REQUIREMENTS), classifiers=[k for k in open("CLASSIFIERS").read().split("\n") if k], description="Rate limiting for flask applications", long_description=open("README.rst").read(), packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", )
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "[email protected]" __copyright__ = "Copyright 2022, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) EXTRA_REQUIREMENTS = { "redis": ["limits[redis]"], "memcached": ["limits[memcached]"], "mongodb": ["limits[mongodb]"], } setup( name="Flask-Limiter", author=__author__, author_email=__email__, license="MIT", url="https://flask-limiter.readthedocs.org", project_urls={ "Source": "https://github.com/alisaifee/flask-limiter", }, zip_safe=False, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), install_requires=list(REQUIREMENTS), classifiers=[k for k in open("CLASSIFIERS").read().split("\n") if k], description="Rate limiting for flask applications", long_description=open("README.rst").read(), packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", extras_require=EXTRA_REQUIREMENTS, include_package_data=True, package_data={ "flask_limiter": ["py.typed"], }, )
10
1
2
mixed
--- a/setup.py +++ b/setup.py @@ -17,3 +17,7 @@ ) - +EXTRA_REQUIREMENTS = { + "redis": ["limits[redis]"], + "memcached": ["limits[memcached]"], + "mongodb": ["limits[mongodb]"], +} @@ -37,2 +41,7 @@ python_requires=">=3.7", + extras_require=EXTRA_REQUIREMENTS, + include_package_data=True, + package_data={ + "flask_limiter": ["py.typed"], + }, )
--- a/setup.py +++ b/setup.py @@ ... @@ ) - +EXTRA_REQUIREMENTS = { + "redis": ["limits[redis]"], + "memcached": ["limits[memcached]"], + "mongodb": ["limits[mongodb]"], +} @@ ... @@ python_requires=">=3.7", + extras_require=EXTRA_REQUIREMENTS, + include_package_data=True, + package_data={ + "flask_limiter": ["py.typed"], + }, )
--- a/setup.py +++ b/setup.py @@ -17,3 +17,7 @@ CON ) DEL ADD EXTRA_REQUIREMENTS = { ADD "redis": ["limits[redis]"], ADD "memcached": ["limits[memcached]"], ADD "mongodb": ["limits[mongodb]"], ADD } CON @@ -37,2 +41,7 @@ CON python_requires=">=3.7", ADD extras_require=EXTRA_REQUIREMENTS, ADD include_package_data=True, ADD package_data={ ADD "flask_limiter": ["py.typed"], ADD }, CON )
<<<<<<< SEARCH None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) setup( ======= None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) EXTRA_REQUIREMENTS = { "redis": ["limits[redis]"], "memcached": ["limits[memcached]"], "mongodb": ["limits[mongodb]"], } setup( >>>>>>> REPLACE <<<<<<< SEARCH packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", ) ======= packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", extras_require=EXTRA_REQUIREMENTS, include_package_data=True, package_data={ "flask_limiter": ["py.typed"], }, ) >>>>>>> REPLACE
digabi/math-editor
b9135c98f0a50f9f873d597b8a959ee63a10c6b6
test/tests.js
javascript
mit
Add test for clicking equation
describe('math editor', () => { before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) describe('initial state', () => { it('answer field is contenteditable', () => { const $answer = $('.answer') expect($answer).to.have.attr('contenteditable', 'true') expect($answer).to.have.attr('data-js-handle', 'answer') }) }) describe('focus state', () => { before(() => { $('.answer1').focus() $('.answer1').focus() // TODO why two calls is necessary? }) before(waitUntil(() => $('.toolbar').is(':visible'))) it('shows tools', () => { expect($('.toolbar')).to.be.visible expect($('.answer1').prev()).to.have.class('toolbar') }) }) describe('start math', () => { before(() => { }) it('shows tools', () => { }) }) }) function waitUntil(condition) { return done => _waitUntil(condition, done) } function _waitUntil(condition, done) { if (condition()) done() else setTimeout(() => _waitUntil(condition, done), 200) }
describe('math editor', () => { before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) describe('initial state', () => { it('answer field is contenteditable', () => { const $answer = $('.answer') expect($answer).to.have.attr('contenteditable', 'true') expect($answer).to.have.attr('data-js-handle', 'answer') }) }) describe('focus state', () => { before(() => { $('.answer1').focus() $('.answer1').focus() // TODO why two calls is necessary? }) before(waitUntil(() => $('.toolbar').is(':visible'))) it('shows tools', () => { expect($('.toolbar')).to.be.visible expect($('.answer1').prev()).to.have.class('toolbar') }) }) describe('start math', () => { before(() => { $('.newEquation').mousedown() }) it('shows tools', () => { expect($('.math')).to.be.visible }) }) }) function waitUntil(condition) { return done => _waitUntil(condition, done) } function _waitUntil(condition, done) { if (condition()) done() else setTimeout(() => _waitUntil(condition, done), 200) }
3
1
3
mixed
--- a/test/tests.js +++ b/test/tests.js @@ -1,2 +1,3 @@ describe('math editor', () => { + before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) @@ -26,2 +27,3 @@ before(() => { + $('.newEquation').mousedown() }) @@ -29,3 +31,3 @@ it('shows tools', () => { - + expect($('.math')).to.be.visible })
--- a/test/tests.js +++ b/test/tests.js @@ ... @@ describe('math editor', () => { + before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) @@ ... @@ before(() => { + $('.newEquation').mousedown() }) @@ ... @@ it('shows tools', () => { - + expect($('.math')).to.be.visible })
--- a/test/tests.js +++ b/test/tests.js @@ -1,2 +1,3 @@ CON describe('math editor', () => { ADD CON before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) @@ -26,2 +27,3 @@ CON before(() => { ADD $('.newEquation').mousedown() CON }) @@ -29,3 +31,3 @@ CON it('shows tools', () => { DEL ADD expect($('.math')).to.be.visible CON })
<<<<<<< SEARCH describe('math editor', () => { before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) ======= describe('math editor', () => { before(waitUntil(() => $('.toolbar').length > 0 && $('.toolbar').is(':hidden'))) >>>>>>> REPLACE <<<<<<< SEARCH describe('start math', () => { before(() => { }) it('shows tools', () => { }) }) ======= describe('start math', () => { before(() => { $('.newEquation').mousedown() }) it('shows tools', () => { expect($('.math')).to.be.visible }) }) >>>>>>> REPLACE
mitsuhiko/rust
4be086b7f6499fa7c0ff177eef6942b3ba1bb1b1
src/libstd/macros.rs
rust
apache-2.0
Remove rtdebug_! and make rtdebug! work properly. It now actually does logging, and is compiled out when `--cfg rtdebug` is not given to the libstd build, which it isn't by default. This makes the rt benchmarks 18-50% faster.
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[macro_escape]; macro_rules! rterrln ( ($( $arg:expr),+) => ( { ::rt::util::dumb_println(fmt!( $($arg),+ )); } ) ) // Some basic logging macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( { rterrln!( $($arg),+ ) } ) ) // An alternate version with no output, for turning off logging. An // earlier attempt that did not call the fmt! macro was insufficient, // as a case of the "let bind each variable" approach eventually // failed without an error message describing the invocation site. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { let _x = fmt!( $($arg),+ ); }) ) macro_rules! rtassert ( ( $arg:expr ) => ( { if !$arg { rtabort!("assertion failed: %s", stringify!($arg)); } } ) ) macro_rules! rtabort( ($( $msg:expr),+) => ( { ::rt::util::abort(fmt!($($msg),+)); } ) )
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[macro_escape]; macro_rules! rterrln ( ($( $arg:expr),+) => ( { ::rt::util::dumb_println(fmt!( $($arg),+ )); } ) ) // Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { if cfg!(rtdebug) { rterrln!( $($arg),+ ) } }) ) macro_rules! rtassert ( ( $arg:expr ) => ( { if !$arg { rtabort!("assertion failed: %s", stringify!($arg)); } } ) ) macro_rules! rtabort( ($( $msg:expr),+) => ( { ::rt::util::abort(fmt!($($msg),+)); } ) )
4
12
1
mixed
--- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -18,16 +18,8 @@ -// Some basic logging -macro_rules! rtdebug_ ( - ($( $arg:expr),+) => ( { - rterrln!( $($arg),+ ) - } ) -) - -// An alternate version with no output, for turning off logging. An -// earlier attempt that did not call the fmt! macro was insufficient, -// as a case of the "let bind each variable" approach eventually -// failed without an error message describing the invocation site. +// Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { - let _x = fmt!( $($arg),+ ); + if cfg!(rtdebug) { + rterrln!( $($arg),+ ) + } })
--- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ ... @@ -// Some basic logging -macro_rules! rtdebug_ ( - ($( $arg:expr),+) => ( { - rterrln!( $($arg),+ ) - } ) -) - -// An alternate version with no output, for turning off logging. An -// earlier attempt that did not call the fmt! macro was insufficient, -// as a case of the "let bind each variable" approach eventually -// failed without an error message describing the invocation site. +// Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { - let _x = fmt!( $($arg),+ ); + if cfg!(rtdebug) { + rterrln!( $($arg),+ ) + } })
--- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -18,16 +18,8 @@ CON DEL // Some basic logging DEL macro_rules! rtdebug_ ( DEL ($( $arg:expr),+) => ( { DEL rterrln!( $($arg),+ ) DEL } ) DEL ) DEL DEL // An alternate version with no output, for turning off logging. An DEL // earlier attempt that did not call the fmt! macro was insufficient, DEL // as a case of the "let bind each variable" approach eventually DEL // failed without an error message describing the invocation site. ADD // Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. CON macro_rules! rtdebug ( CON ($( $arg:expr),+) => ( { DEL let _x = fmt!( $($arg),+ ); ADD if cfg!(rtdebug) { ADD rterrln!( $($arg),+ ) ADD } CON })
<<<<<<< SEARCH ) // Some basic logging macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( { rterrln!( $($arg),+ ) } ) ) // An alternate version with no output, for turning off logging. An // earlier attempt that did not call the fmt! macro was insufficient, // as a case of the "let bind each variable" approach eventually // failed without an error message describing the invocation site. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { let _x = fmt!( $($arg),+ ); }) ) ======= ) // Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. macro_rules! rtdebug ( ($( $arg:expr),+) => ( { if cfg!(rtdebug) { rterrln!( $($arg),+ ) } }) ) >>>>>>> REPLACE
GuillaumeGomez/gir
b6ba5eac46f1604af46e9f0812713f3df4236dab
src/analysis/general.rs
rust
mit
Fix "no talking" panic on bad object names in Gir.toml
use gobjects::*; use library::*; pub struct StatusedTypeId{ pub type_id: TypeId, pub name: String, pub status: GStatus, } pub fn widget_tid(library: &Library) -> TypeId { library.find_type(0, "Gtk.Widget").unwrap_or_else(|| unreachable!()) } pub trait IsWidget { fn is_widget(&self, library: &Library) -> bool; } impl IsWidget for Class { fn is_widget(&self, library: &Library) -> bool { self.glib_type_name == "GtkWidget" || self.parents.contains(&widget_tid(&library)) } } impl IsWidget for Type { fn is_widget(&self, library: &Library) -> bool { match self { &Type::Class(ref klass) => klass.is_widget(&library), _ => false, } } } impl IsWidget for TypeId { fn is_widget(&self, library: &Library) -> bool { library.type_(*self).is_widget(&library) } } impl IsWidget for String { fn is_widget(&self, library: &Library) -> bool { library.find_type(0, self).unwrap().is_widget(library) } }
use gobjects::*; use library::*; pub struct StatusedTypeId{ pub type_id: TypeId, pub name: String, pub status: GStatus, } pub fn widget_tid(library: &Library) -> TypeId { library.find_type(0, "Gtk.Widget").unwrap_or_else(|| unreachable!()) } pub trait IsWidget { fn is_widget(&self, library: &Library) -> bool; } impl IsWidget for Class { fn is_widget(&self, library: &Library) -> bool { self.glib_type_name == "GtkWidget" || self.parents.contains(&widget_tid(&library)) } } impl IsWidget for Type { fn is_widget(&self, library: &Library) -> bool { match self { &Type::Class(ref klass) => klass.is_widget(&library), _ => false, } } } impl IsWidget for TypeId { fn is_widget(&self, library: &Library) -> bool { library.type_(*self).is_widget(&library) } } impl IsWidget for String { fn is_widget(&self, library: &Library) -> bool { library.find_type_unwrapped(0, self, "Type").is_widget(library) } }
1
1
1
mixed
--- a/src/analysis/general.rs +++ b/src/analysis/general.rs @@ -40,3 +40,3 @@ fn is_widget(&self, library: &Library) -> bool { - library.find_type(0, self).unwrap().is_widget(library) + library.find_type_unwrapped(0, self, "Type").is_widget(library) }
--- a/src/analysis/general.rs +++ b/src/analysis/general.rs @@ ... @@ fn is_widget(&self, library: &Library) -> bool { - library.find_type(0, self).unwrap().is_widget(library) + library.find_type_unwrapped(0, self, "Type").is_widget(library) }
--- a/src/analysis/general.rs +++ b/src/analysis/general.rs @@ -40,3 +40,3 @@ CON fn is_widget(&self, library: &Library) -> bool { DEL library.find_type(0, self).unwrap().is_widget(library) ADD library.find_type_unwrapped(0, self, "Type").is_widget(library) CON }
<<<<<<< SEARCH impl IsWidget for String { fn is_widget(&self, library: &Library) -> bool { library.find_type(0, self).unwrap().is_widget(library) } } ======= impl IsWidget for String { fn is_widget(&self, library: &Library) -> bool { library.find_type_unwrapped(0, self, "Type").is_widget(library) } } >>>>>>> REPLACE
eggeral/3d-playground
9c1291784a452f032f8578d5b3f4f5a44994c94d
src/main/kotlin/threed/main.kt
kotlin
apache-2.0
Set canvas HTML element height to 100% so it follows the height of the browser.
package threed import org.khronos.webgl.WebGLRenderingContext import org.w3c.dom.HTMLCanvasElement import org.w3c.dom.HTMLDivElement import kotlin.browser.document import kotlin.browser.window fun main(args: Array<String>) { val container = document.getElementById("container") as HTMLDivElement val canvas = document.createElement("canvas") as HTMLCanvasElement val webGlContext = canvas.getContext("webgl") if (webGlContext == null) { val text = document.createTextNode("WebGl not available in this browser!") container.appendChild(text) } else { container.appendChild(canvas) webGlContext as WebGLRenderingContext fun render() { webGlContext.viewport(0, 0, canvas.width, canvas.height) drawTriangle(webGlContext) window.requestAnimationFrame { render() } } render() } }
package threed import org.khronos.webgl.WebGLRenderingContext import org.w3c.dom.HTMLCanvasElement import org.w3c.dom.HTMLDivElement import kotlin.browser.document import kotlin.browser.window fun main(args: Array<String>) { val container = document.getElementById("container") as HTMLDivElement val canvas = document.createElement("canvas") as HTMLCanvasElement canvas.style.height = "100%" val webGlContext = canvas.getContext("webgl") if (webGlContext == null) { val text = document.createTextNode("WebGl not available in this browser!") container.appendChild(text) } else { container.appendChild(canvas) webGlContext as WebGLRenderingContext fun render() { webGlContext.viewport(0, 0, canvas.width, canvas.height) drawTriangle(webGlContext) window.requestAnimationFrame { render() } } render() } }
1
0
1
add_only
--- a/src/main/kotlin/threed/main.kt +++ b/src/main/kotlin/threed/main.kt @@ -13,2 +13,3 @@ val canvas = document.createElement("canvas") as HTMLCanvasElement + canvas.style.height = "100%"
--- a/src/main/kotlin/threed/main.kt +++ b/src/main/kotlin/threed/main.kt @@ ... @@ val canvas = document.createElement("canvas") as HTMLCanvasElement + canvas.style.height = "100%"
--- a/src/main/kotlin/threed/main.kt +++ b/src/main/kotlin/threed/main.kt @@ -13,2 +13,3 @@ CON val canvas = document.createElement("canvas") as HTMLCanvasElement ADD canvas.style.height = "100%" CON
<<<<<<< SEARCH val container = document.getElementById("container") as HTMLDivElement val canvas = document.createElement("canvas") as HTMLCanvasElement val webGlContext = canvas.getContext("webgl") ======= val container = document.getElementById("container") as HTMLDivElement val canvas = document.createElement("canvas") as HTMLCanvasElement canvas.style.height = "100%" val webGlContext = canvas.getContext("webgl") >>>>>>> REPLACE
opensource21/fuwesta
b185e91db7722451735079510d2d6edbf89facf4
fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java
java
apache-2.0
Create a separate entry for the EVENT_STORAGE.
package de.ppi.samples.fuwesta.selophane.base; import org.junit.rules.RuleChain; import de.ppi.selenium.junit.DelegatingWebServer; import de.ppi.selenium.junit.EventLogRule; import de.ppi.selenium.junit.ProtocolRule; import de.ppi.selenium.junit.WebDriverRule; import de.ppi.selenium.junit.WebServerRule; import de.ppi.webttest.util.TestWebServer; import de.ppi.selenium.logevent.backend.H2EventStorage; /** * Constants for webtest. * */ // CSOFFALL: public interface WebTestConstants { TestWebServer WEB_SERVER = new TestWebServer("/fuwesta"); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST_WITHOUT_AUTHENTICATION = RuleChain .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) .around(new EventLogRule(new H2EventStorage( "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""))).around(new WebDriverRule()) .around(new ProtocolRule("weblog")); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST = RuleChain.outerRule(WEBTEST_WITHOUT_AUTHENTICATION) .around(new AuthRule()); }
package de.ppi.samples.fuwesta.selophane.base; import org.junit.rules.RuleChain; import de.ppi.selenium.junit.DelegatingWebServer; import de.ppi.selenium.junit.EventLogRule; import de.ppi.selenium.junit.ProtocolRule; import de.ppi.selenium.junit.WebDriverRule; import de.ppi.selenium.junit.WebServerRule; import de.ppi.webttest.util.TestWebServer; import de.ppi.selenium.logevent.backend.H2EventStorage; /** * Constants for webtest. * */ // CSOFFALL: public interface WebTestConstants { TestWebServer WEB_SERVER = new TestWebServer("/fuwesta"); /** * The system to store the events. */ H2EventStorage EVENT_STORAGE = new H2EventStorage( "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST_WITHOUT_AUTHENTICATION = RuleChain .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) .around(new EventLogRule(EVENT_STORAGE)) .around(new WebDriverRule()).around(new ProtocolRule("weblog")); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST = RuleChain.outerRule(WEBTEST_WITHOUT_AUTHENTICATION) .around(new AuthRule()); }
9
4
3
mixed
--- a/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java +++ b/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java @@ -22,2 +22,8 @@ /** + * The system to store the events. + */ + H2EventStorage EVENT_STORAGE = new H2EventStorage( + "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""); + + /** * Standard_Rule for WebTests. @@ -26,6 +32,4 @@ .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) - .around(new EventLogRule(new H2EventStorage( - "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", - "sa", ""))).around(new WebDriverRule()) - .around(new ProtocolRule("weblog")); + .around(new EventLogRule(EVENT_STORAGE)) + .around(new WebDriverRule()).around(new ProtocolRule("weblog")); /** @@ -35,2 +39,3 @@ .around(new AuthRule()); + }
--- a/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java +++ b/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java @@ ... @@ /** + * The system to store the events. + */ + H2EventStorage EVENT_STORAGE = new H2EventStorage( + "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""); + + /** * Standard_Rule for WebTests. @@ ... @@ .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) - .around(new EventLogRule(new H2EventStorage( - "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", - "sa", ""))).around(new WebDriverRule()) - .around(new ProtocolRule("weblog")); + .around(new EventLogRule(EVENT_STORAGE)) + .around(new WebDriverRule()).around(new ProtocolRule("weblog")); /** @@ ... @@ .around(new AuthRule()); + }
--- a/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java +++ b/fuwesta-sample/src/test/java/de/ppi/samples/fuwesta/selophane/base/WebTestConstants.java @@ -22,2 +22,8 @@ CON /** ADD * The system to store the events. ADD */ ADD H2EventStorage EVENT_STORAGE = new H2EventStorage( ADD "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""); ADD ADD /** CON * Standard_Rule for WebTests. @@ -26,6 +32,4 @@ CON .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) DEL .around(new EventLogRule(new H2EventStorage( DEL "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", DEL "sa", ""))).around(new WebDriverRule()) DEL .around(new ProtocolRule("weblog")); ADD .around(new EventLogRule(EVENT_STORAGE)) ADD .around(new WebDriverRule()).around(new ProtocolRule("weblog")); CON /** @@ -35,2 +39,3 @@ CON .around(new AuthRule()); ADD CON }
<<<<<<< SEARCH /** * Standard_Rule for WebTests. */ RuleChain WEBTEST_WITHOUT_AUTHENTICATION = RuleChain .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) .around(new EventLogRule(new H2EventStorage( "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""))).around(new WebDriverRule()) .around(new ProtocolRule("weblog")); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST = RuleChain.outerRule(WEBTEST_WITHOUT_AUTHENTICATION) .around(new AuthRule()); } ======= /** * The system to store the events. */ H2EventStorage EVENT_STORAGE = new H2EventStorage( "jdbc:h2:./dbs/testlog;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", ""); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST_WITHOUT_AUTHENTICATION = RuleChain .outerRule(new WebServerRule(new DelegatingWebServer(WEB_SERVER))) .around(new EventLogRule(EVENT_STORAGE)) .around(new WebDriverRule()).around(new ProtocolRule("weblog")); /** * Standard_Rule for WebTests. */ RuleChain WEBTEST = RuleChain.outerRule(WEBTEST_WITHOUT_AUTHENTICATION) .around(new AuthRule()); } >>>>>>> REPLACE
wwsean08/WeatherReport
ebbaad6e414338837c64dec0194c2bf3a00f7a52
src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java
java
apache-2.0
Include a timestamp of when the data was requested from wunderground (roughly)
package com.wwsean08.WeatherReport.pojo; import com.google.gson.annotations.SerializedName; /** * Created by wwsea_000 on 12/30/2015. */ public class RabbitMQJson { @SerializedName("location") private String location; @SerializedName("temperature") private float temp; @SerializedName("icon") private String icon; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public float getTemp() { return temp; } public void setTemp(float temp) { this.temp = temp; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
package com.wwsean08.WeatherReport.pojo; import com.google.gson.annotations.SerializedName; import com.sun.glass.ui.SystemClipboard; /** * Created by wwsea_000 on 12/30/2015. */ public class RabbitMQJson { @SerializedName("location") private String location; @SerializedName("temperature") private float temp; @SerializedName("icon") private String icon; @SerializedName("timestamp") private long timestamp = System.currentTimeMillis(); public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public float getTemp() { return temp; } public void setTemp(float temp) { this.temp = temp; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
3
0
2
add_only
--- a/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java +++ b/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java @@ -3,2 +3,3 @@ import com.google.gson.annotations.SerializedName; +import com.sun.glass.ui.SystemClipboard; @@ -15,2 +16,4 @@ private String icon; + @SerializedName("timestamp") + private long timestamp = System.currentTimeMillis();
--- a/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java +++ b/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java @@ ... @@ import com.google.gson.annotations.SerializedName; +import com.sun.glass.ui.SystemClipboard; @@ ... @@ private String icon; + @SerializedName("timestamp") + private long timestamp = System.currentTimeMillis();
--- a/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java +++ b/src/main/java/com/wwsean08/WeatherReport/pojo/RabbitMQJson.java @@ -3,2 +3,3 @@ CON import com.google.gson.annotations.SerializedName; ADD import com.sun.glass.ui.SystemClipboard; CON @@ -15,2 +16,4 @@ CON private String icon; ADD @SerializedName("timestamp") ADD private long timestamp = System.currentTimeMillis(); CON
<<<<<<< SEARCH import com.google.gson.annotations.SerializedName; /** ======= import com.google.gson.annotations.SerializedName; import com.sun.glass.ui.SystemClipboard; /** >>>>>>> REPLACE <<<<<<< SEARCH @SerializedName("icon") private String icon; public String getLocation() ======= @SerializedName("icon") private String icon; @SerializedName("timestamp") private long timestamp = System.currentTimeMillis(); public String getLocation() >>>>>>> REPLACE
grayben/10K-item-extractor
4433659756e865d94ed1315502b3bfab5e25937b
src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java
java
mit
Make init throw exception when electees not subset of nominees
package com.grayben.riskExtractor.headingMarker.elector; import java.util.Collections; import java.util.List; import com.grayben.riskExtractor.headingMarker.nominator.NominatedText; public class ElectedText extends NominatedText implements ElecteesRetrievable { //TODO: make this a set: should not have repetitions List<Integer> electees; public ElectedText(List<String> textList, List<Integer> nominees, List<Integer> electees){ super(textList, nominees); if (electees == null) { throw new NullPointerException("Attempted to pass illegal null argument"); } this.electees = electees; } public ElectedText(NominatedText nominatedText, List<Integer> electees){ super(nominatedText); if (electees == null) { throw new NullPointerException("Attempted to pass illegal null argument"); } this.electees = electees; } public ElectedText(ElectedText electedText){ this(electedText, electedText.getElectees()); } @Override public List<Integer> getElectees() { return Collections.unmodifiableList(this.electees); } }
package com.grayben.riskExtractor.headingMarker.elector; import java.util.Collections; import java.util.List; import com.grayben.riskExtractor.headingMarker.nominator.NominatedText; public class ElectedText extends NominatedText implements ElecteesRetrievable { //TODO: make this a set: should not have repetitions List<Integer> electees; public ElectedText(List<String> textList, List<Integer> nominees, List<Integer> electees){ super(textList, nominees); if (electees == null) { throw new NullPointerException("Attempted to pass illegal null argument"); } if ( ! nominees.containsAll(electees)) throw new IllegalArgumentException( "The electees argument was not a subset " + "of the nominees argument" ); this.electees = electees; } public ElectedText(NominatedText nominatedText, List<Integer> electees){ this( nominatedText.getStringList(), nominatedText.getNominees(), electees ); } public ElectedText(ElectedText electedText){ this(electedText, electedText.getElectees()); } @Override public List<Integer> getElectees() { return Collections.unmodifiableList(this.electees); } }
10
5
2
mixed
--- a/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java +++ b/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java @@ -23,2 +23,7 @@ } + if ( ! nominees.containsAll(electees)) + throw new IllegalArgumentException( + "The electees argument was not a subset " + + "of the nominees argument" + ); this.electees = electees; @@ -27,7 +32,7 @@ public ElectedText(NominatedText nominatedText, List<Integer> electees){ - super(nominatedText); - if (electees == null) { - throw new NullPointerException("Attempted to pass illegal null argument"); - } - this.electees = electees; + this( + nominatedText.getStringList(), + nominatedText.getNominees(), + electees + ); }
--- a/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java +++ b/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java @@ ... @@ } + if ( ! nominees.containsAll(electees)) + throw new IllegalArgumentException( + "The electees argument was not a subset " + + "of the nominees argument" + ); this.electees = electees; @@ ... @@ public ElectedText(NominatedText nominatedText, List<Integer> electees){ - super(nominatedText); - if (electees == null) { - throw new NullPointerException("Attempted to pass illegal null argument"); - } - this.electees = electees; + this( + nominatedText.getStringList(), + nominatedText.getNominees(), + electees + ); }
--- a/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java +++ b/src/main/java/com/grayben/riskExtractor/headingMarker/elector/ElectedText.java @@ -23,2 +23,7 @@ CON } ADD if ( ! nominees.containsAll(electees)) ADD throw new IllegalArgumentException( ADD "The electees argument was not a subset " + ADD "of the nominees argument" ADD ); CON this.electees = electees; @@ -27,7 +32,7 @@ CON public ElectedText(NominatedText nominatedText, List<Integer> electees){ DEL super(nominatedText); DEL if (electees == null) { DEL throw new NullPointerException("Attempted to pass illegal null argument"); DEL } DEL this.electees = electees; ADD this( ADD nominatedText.getStringList(), ADD nominatedText.getNominees(), ADD electees ADD ); CON }
<<<<<<< SEARCH throw new NullPointerException("Attempted to pass illegal null argument"); } this.electees = electees; } public ElectedText(NominatedText nominatedText, List<Integer> electees){ super(nominatedText); if (electees == null) { throw new NullPointerException("Attempted to pass illegal null argument"); } this.electees = electees; } ======= throw new NullPointerException("Attempted to pass illegal null argument"); } if ( ! nominees.containsAll(electees)) throw new IllegalArgumentException( "The electees argument was not a subset " + "of the nominees argument" ); this.electees = electees; } public ElectedText(NominatedText nominatedText, List<Integer> electees){ this( nominatedText.getStringList(), nominatedText.getNominees(), electees ); } >>>>>>> REPLACE
antifuchs/ratelimit_meter
b0f186923e838c20cc9f4fd082e4db1ca8e96a15
tests/threadsafe.rs
rust
mit
Test that the threaded rate-limiter is actually doing its work (It does! \o/)
extern crate ratelimit_meter; use ratelimit_meter::{GCRA, Threadsafe, Limiter, Decider, Decision}; use std::thread; #[test] fn simple_operation() { let mut lim = Limiter::new() .capacity(5) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); assert_eq!(Decision::Yes, lim.check()); } #[test] fn actual_threadsafety() { let lim = Limiter::new() .capacity(5) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); let mut children = vec![]; for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || { lim.check(); })); } for child in children { child.join().unwrap(); } }
extern crate ratelimit_meter; use ratelimit_meter::{GCRA, Threadsafe, Limiter, Decider, Decision}; use std::thread; use std::time::{Instant, Duration}; #[test] fn simple_operation() { let mut lim = Limiter::new() .capacity(5) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); assert_eq!(Decision::Yes, lim.check()); } #[test] fn actual_threadsafety() { let mut lim = Limiter::new() .capacity(20) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); let now = Instant::now(); let ms = Duration::from_millis(1); let mut children = vec![]; lim.test_and_update(now); for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || { lim.test_and_update(now); })); } for child in children { child.join().unwrap(); } assert!(!lim.test_and_update(now).is_compliant()); assert_eq!(Decision::Yes, lim.test_and_update(now+ms*1000)); }
10
3
5
mixed
--- a/tests/threadsafe.rs +++ b/tests/threadsafe.rs @@ -4,2 +4,3 @@ use std::thread; +use std::time::{Instant, Duration}; @@ -17,4 +18,4 @@ fn actual_threadsafety() { - let lim = Limiter::new() - .capacity(5) + let mut lim = Limiter::new() + .capacity(20) .weight(1) @@ -22,3 +23,7 @@ .unwrap(); + let now = Instant::now(); + let ms = Duration::from_millis(1); let mut children = vec![]; + + lim.test_and_update(now); for _i in 0..20 { @@ -26,3 +31,3 @@ children.push(thread::spawn(move || { - lim.check(); + lim.test_and_update(now); })); @@ -32,2 +37,4 @@ } + assert!(!lim.test_and_update(now).is_compliant()); + assert_eq!(Decision::Yes, lim.test_and_update(now+ms*1000)); }
--- a/tests/threadsafe.rs +++ b/tests/threadsafe.rs @@ ... @@ use std::thread; +use std::time::{Instant, Duration}; @@ ... @@ fn actual_threadsafety() { - let lim = Limiter::new() - .capacity(5) + let mut lim = Limiter::new() + .capacity(20) .weight(1) @@ ... @@ .unwrap(); + let now = Instant::now(); + let ms = Duration::from_millis(1); let mut children = vec![]; + + lim.test_and_update(now); for _i in 0..20 { @@ ... @@ children.push(thread::spawn(move || { - lim.check(); + lim.test_and_update(now); })); @@ ... @@ } + assert!(!lim.test_and_update(now).is_compliant()); + assert_eq!(Decision::Yes, lim.test_and_update(now+ms*1000)); }
--- a/tests/threadsafe.rs +++ b/tests/threadsafe.rs @@ -4,2 +4,3 @@ CON use std::thread; ADD use std::time::{Instant, Duration}; CON @@ -17,4 +18,4 @@ CON fn actual_threadsafety() { DEL let lim = Limiter::new() DEL .capacity(5) ADD let mut lim = Limiter::new() ADD .capacity(20) CON .weight(1) @@ -22,3 +23,7 @@ CON .unwrap(); ADD let now = Instant::now(); ADD let ms = Duration::from_millis(1); CON let mut children = vec![]; ADD ADD lim.test_and_update(now); CON for _i in 0..20 { @@ -26,3 +31,3 @@ CON children.push(thread::spawn(move || { DEL lim.check(); ADD lim.test_and_update(now); CON })); @@ -32,2 +37,4 @@ CON } ADD assert!(!lim.test_and_update(now).is_compliant()); ADD assert_eq!(Decision::Yes, lim.test_and_update(now+ms*1000)); CON }
<<<<<<< SEARCH use ratelimit_meter::{GCRA, Threadsafe, Limiter, Decider, Decision}; use std::thread; #[test] ======= use ratelimit_meter::{GCRA, Threadsafe, Limiter, Decider, Decision}; use std::thread; use std::time::{Instant, Duration}; #[test] >>>>>>> REPLACE <<<<<<< SEARCH #[test] fn actual_threadsafety() { let lim = Limiter::new() .capacity(5) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); let mut children = vec![]; for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || { lim.check(); })); } for child in children { child.join().unwrap(); } } ======= #[test] fn actual_threadsafety() { let mut lim = Limiter::new() .capacity(20) .weight(1) .build::<Threadsafe<GCRA>>() .unwrap(); let now = Instant::now(); let ms = Duration::from_millis(1); let mut children = vec![]; lim.test_and_update(now); for _i in 0..20 { let mut lim = lim.clone(); children.push(thread::spawn(move || { lim.test_and_update(now); })); } for child in children { child.join().unwrap(); } assert!(!lim.test_and_update(now).is_compliant()); assert_eq!(Decision::Yes, lim.test_and_update(now+ms*1000)); } >>>>>>> REPLACE
jawrainey/atc
f5c8c9909a8b7288503f1ed3dcd87c5e59d3817c
settings.py
python
mit
Use environment db url, otherwise a service specific one.
import os class Config(object): """ The shared configuration settings for the flask app. """ PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) CSRF_ENABLED = True CSRF_SESSION_KEY = "supersecretpassword" SECRET_KEY = 'supersecretpassword' class ProdConfig(Config): """ Setup the production configuration for the flask app. Args: Config (object): Inherit the default shared configuration settings. """ ENV = 'prod' DEBUG = False heroku = os.environ.get('DATABASE_URL') if heroku: SQLALCHEMY_DATABASE_URI = heroku else: SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' class DevConfig(Config): """ Setup the development configuration for the flask app. Args: Config (object): Inherit the default shared configuration settings. """ ENV = 'dev' DEBUG = True DB_PATH = os.path.join(Config.PROJECT_ROOT, 'dev.db') SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH)
import os class Config(object): """ The shared configuration settings for the flask app. """ PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) CSRF_ENABLED = True CSRF_SESSION_KEY = "supersecretpassword" SECRET_KEY = 'supersecretpassword' class ProdConfig(Config): """ Setup the production configuration for the flask app. Args: Config (object): Inherit the default shared configuration settings. """ ENV = 'prod' DEBUG = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/example') class DevConfig(Config): """ Setup the development configuration for the flask app. Args: Config (object): Inherit the default shared configuration settings. """ ENV = 'dev' DEBUG = True DB_PATH = os.path.join(Config.PROJECT_ROOT, 'dev.db') SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH)
2
5
1
mixed
--- a/settings.py +++ b/settings.py @@ -22,7 +22,4 @@ DEBUG = False - heroku = os.environ.get('DATABASE_URL') - if heroku: - SQLALCHEMY_DATABASE_URI = heroku - else: - SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' + SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', + 'postgresql://localhost/example')
--- a/settings.py +++ b/settings.py @@ ... @@ DEBUG = False - heroku = os.environ.get('DATABASE_URL') - if heroku: - SQLALCHEMY_DATABASE_URI = heroku - else: - SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' + SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', + 'postgresql://localhost/example')
--- a/settings.py +++ b/settings.py @@ -22,7 +22,4 @@ CON DEBUG = False DEL heroku = os.environ.get('DATABASE_URL') DEL if heroku: DEL SQLALCHEMY_DATABASE_URI = heroku DEL else: DEL SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' ADD SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', ADD 'postgresql://localhost/example') CON
<<<<<<< SEARCH ENV = 'prod' DEBUG = False heroku = os.environ.get('DATABASE_URL') if heroku: SQLALCHEMY_DATABASE_URI = heroku else: SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' ======= ENV = 'prod' DEBUG = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/example') >>>>>>> REPLACE
EBISPOT/goci
e1f1939c2e41273a51275dbeaad9615cdd93e857
goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java
java
apache-2.0
Remove toString method, add setters
package uk.ac.ebi.spot.goci.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by emma on 27/11/14. * * @author emma * <p> * Model object representing status assigned to studies */ @Entity public class CurationStatus { @Id @GeneratedValue private Long id; private String status; private String seqnbr; // JPA no-args constructor public CurationStatus() { } public CurationStatus(Long id, String curationStatus, String seqnbr) { this.id = id; this.status = curationStatus; this.seqnbr = seqnbr; } public Long getId() { return id; } public String getStatus() { return status; } public String getSeqnbr() { return seqnbr; } @Override public String toString() { return "CurationStatus{" + "id=" + id + ", curationStatus='" + status + '\'' + ", seqnbr='" + seqnbr + '\'' + '}'; } }
package uk.ac.ebi.spot.goci.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by emma on 27/11/14. * * @author emma * <p> * Model object representing status assigned to studies */ @Entity public class CurationStatus { @Id @GeneratedValue private Long id; private String status; private String seqnbr; // JPA no-args constructor public CurationStatus() { } public CurationStatus(Long id, String curationStatus, String seqnbr) { this.id = id; this.status = curationStatus; this.seqnbr = seqnbr; } public Long getId() { return id; } public String getStatus() { return status; } public String getSeqnbr() { return seqnbr; } public void setId(Long id) { this.id = id; } public void setStatus(String status) { this.status = status; } public void setSeqnbr(String seqnbr) { this.seqnbr = seqnbr; } }
10
7
1
mixed
--- a/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java +++ b/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java @@ -47,9 +47,12 @@ - @Override - public String toString() { - return "CurationStatus{" + - "id=" + id + - ", curationStatus='" + status + '\'' + - ", seqnbr='" + seqnbr + '\'' + - '}'; + public void setId(Long id) { + this.id = id; + } + + public void setStatus(String status) { + this.status = status; + } + + public void setSeqnbr(String seqnbr) { + this.seqnbr = seqnbr; }
--- a/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java +++ b/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java @@ ... @@ - @Override - public String toString() { - return "CurationStatus{" + - "id=" + id + - ", curationStatus='" + status + '\'' + - ", seqnbr='" + seqnbr + '\'' + - '}'; + public void setId(Long id) { + this.id = id; + } + + public void setStatus(String status) { + this.status = status; + } + + public void setSeqnbr(String seqnbr) { + this.seqnbr = seqnbr; }
--- a/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java +++ b/goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/CurationStatus.java @@ -47,9 +47,12 @@ CON DEL @Override DEL public String toString() { DEL return "CurationStatus{" + DEL "id=" + id + DEL ", curationStatus='" + status + '\'' + DEL ", seqnbr='" + seqnbr + '\'' + DEL '}'; ADD public void setId(Long id) { ADD this.id = id; ADD } ADD ADD public void setStatus(String status) { ADD this.status = status; ADD } ADD ADD public void setSeqnbr(String seqnbr) { ADD this.seqnbr = seqnbr; CON }
<<<<<<< SEARCH } @Override public String toString() { return "CurationStatus{" + "id=" + id + ", curationStatus='" + status + '\'' + ", seqnbr='" + seqnbr + '\'' + '}'; } } ======= } public void setId(Long id) { this.id = id; } public void setStatus(String status) { this.status = status; } public void setSeqnbr(String seqnbr) { this.seqnbr = seqnbr; } } >>>>>>> REPLACE
nihn/linkedin-scraper
e743f82d93e9501c8b3bd827ee0553ceec8aadb6
linkedin_scraper/spiders/search.py
python
mit
Allow Spider to log into LinkedIn. * SearchSpider now uses InitSpider as base class, * SearchSpider now accepts username and password arguments, * username and password can also be set by SPIDER_USERNAME and SPIDER_PASSWORD env variables, * SearchSpider log into LinkedIn by sending form with credentials to /uas/login endpoint.
import scrapy class SearchSpider(scrapy.Spider): name = 'search' allowed_domains = ['linkedin.com'] start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] def parse(self, response): for search_result in response.css('li.mod.result.people'): *first_name, last_name = search_result.css('b::text').extract() yield { 'first_name': ' '.join(first_name), 'last_name': last_name, }
from os import environ from scrapy.spiders.init import InitSpider from scrapy.http import Request, FormRequest class SearchSpider(InitSpider): name = 'search' allowed_domains = ['linkedin.com'] login_page = 'https://www.linkedin.com/uas/login' start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] def __init__(self, *args, **kwargs): try: self.username = kwargs.pop('username', environ['SPIDER_USERNAME']) self.password = kwargs.pop('password', environ['SPIDER_PASSWORD']) except KeyError: self.logger.error('Both username and password need to be specified ' 'by -a option or SPIDER_<PARAM> environment var') super().__init__(*args, **kwargs) def init_request(self): return Request(url=self.login_page, callback=self.login) def login(self, response): return FormRequest.from_response( response, callback=self.check_login_response, formdata={'session_key': self.username, 'session_password': self.password}) def parse(self, response): for search_result in response.css('li.mod.result.people'): *first_name, last_name = search_result.css('b::text').extract() yield { 'first_name': ' '.join(first_name), 'last_name': last_name, } def check_login_response(self, response): if b'Sign Out' in response.body: self.logger.debug("Successfully logged in. Let's start crawling!") return self.initialized() self.logger.error('Login failed!')
33
2
2
mixed
--- a/linkedin_scraper/spiders/search.py +++ b/linkedin_scraper/spiders/search.py @@ -1,9 +1,33 @@ -import scrapy +from os import environ + +from scrapy.spiders.init import InitSpider +from scrapy.http import Request, FormRequest -class SearchSpider(scrapy.Spider): +class SearchSpider(InitSpider): name = 'search' allowed_domains = ['linkedin.com'] + login_page = 'https://www.linkedin.com/uas/login' + start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] + + def __init__(self, *args, **kwargs): + try: + self.username = kwargs.pop('username', environ['SPIDER_USERNAME']) + self.password = kwargs.pop('password', environ['SPIDER_PASSWORD']) + except KeyError: + self.logger.error('Both username and password need to be specified ' + 'by -a option or SPIDER_<PARAM> environment var') + + super().__init__(*args, **kwargs) + + def init_request(self): + return Request(url=self.login_page, callback=self.login) + + def login(self, response): + return FormRequest.from_response( + response, callback=self.check_login_response, + formdata={'session_key': self.username, + 'session_password': self.password}) @@ -16 +40,8 @@ } + + def check_login_response(self, response): + if b'Sign Out' in response.body: + self.logger.debug("Successfully logged in. Let's start crawling!") + return self.initialized() + + self.logger.error('Login failed!')
--- a/linkedin_scraper/spiders/search.py +++ b/linkedin_scraper/spiders/search.py @@ ... @@ -import scrapy +from os import environ + +from scrapy.spiders.init import InitSpider +from scrapy.http import Request, FormRequest -class SearchSpider(scrapy.Spider): +class SearchSpider(InitSpider): name = 'search' allowed_domains = ['linkedin.com'] + login_page = 'https://www.linkedin.com/uas/login' + start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] + + def __init__(self, *args, **kwargs): + try: + self.username = kwargs.pop('username', environ['SPIDER_USERNAME']) + self.password = kwargs.pop('password', environ['SPIDER_PASSWORD']) + except KeyError: + self.logger.error('Both username and password need to be specified ' + 'by -a option or SPIDER_<PARAM> environment var') + + super().__init__(*args, **kwargs) + + def init_request(self): + return Request(url=self.login_page, callback=self.login) + + def login(self, response): + return FormRequest.from_response( + response, callback=self.check_login_response, + formdata={'session_key': self.username, + 'session_password': self.password}) @@ ... @@ } + + def check_login_response(self, response): + if b'Sign Out' in response.body: + self.logger.debug("Successfully logged in. Let's start crawling!") + return self.initialized() + + self.logger.error('Login failed!')
--- a/linkedin_scraper/spiders/search.py +++ b/linkedin_scraper/spiders/search.py @@ -1,9 +1,33 @@ DEL import scrapy ADD from os import environ ADD ADD from scrapy.spiders.init import InitSpider ADD from scrapy.http import Request, FormRequest CON CON DEL class SearchSpider(scrapy.Spider): ADD class SearchSpider(InitSpider): CON name = 'search' CON allowed_domains = ['linkedin.com'] ADD login_page = 'https://www.linkedin.com/uas/login' ADD CON start_urls = [ CON 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] ADD ADD def __init__(self, *args, **kwargs): ADD try: ADD self.username = kwargs.pop('username', environ['SPIDER_USERNAME']) ADD self.password = kwargs.pop('password', environ['SPIDER_PASSWORD']) ADD except KeyError: ADD self.logger.error('Both username and password need to be specified ' ADD 'by -a option or SPIDER_<PARAM> environment var') ADD ADD super().__init__(*args, **kwargs) ADD ADD def init_request(self): ADD return Request(url=self.login_page, callback=self.login) ADD ADD def login(self, response): ADD return FormRequest.from_response( ADD response, callback=self.check_login_response, ADD formdata={'session_key': self.username, ADD 'session_password': self.password}) CON @@ -16 +40,8 @@ CON } ADD ADD def check_login_response(self, response): ADD if b'Sign Out' in response.body: ADD self.logger.debug("Successfully logged in. Let's start crawling!") ADD return self.initialized() ADD ADD self.logger.error('Login failed!')
<<<<<<< SEARCH import scrapy class SearchSpider(scrapy.Spider): name = 'search' allowed_domains = ['linkedin.com'] start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] def parse(self, response): ======= from os import environ from scrapy.spiders.init import InitSpider from scrapy.http import Request, FormRequest class SearchSpider(InitSpider): name = 'search' allowed_domains = ['linkedin.com'] login_page = 'https://www.linkedin.com/uas/login' start_urls = [ 'https://www.linkedin.com/vsearch/f?type=people&keywords=MateuszMoneta'] def __init__(self, *args, **kwargs): try: self.username = kwargs.pop('username', environ['SPIDER_USERNAME']) self.password = kwargs.pop('password', environ['SPIDER_PASSWORD']) except KeyError: self.logger.error('Both username and password need to be specified ' 'by -a option or SPIDER_<PARAM> environment var') super().__init__(*args, **kwargs) def init_request(self): return Request(url=self.login_page, callback=self.login) def login(self, response): return FormRequest.from_response( response, callback=self.check_login_response, formdata={'session_key': self.username, 'session_password': self.password}) def parse(self, response): >>>>>>> REPLACE <<<<<<< SEARCH 'last_name': last_name, } ======= 'last_name': last_name, } def check_login_response(self, response): if b'Sign Out' in response.body: self.logger.debug("Successfully logged in. Let's start crawling!") return self.initialized() self.logger.error('Login failed!') >>>>>>> REPLACE
ScottMaclure/scott-cv
93043e90d1e352c089a00cd65a5bbfed12e4453a
components/Footer.js
javascript
mit
Update component to pass tests.
var React = require('react'), DOM = React.DOM; module.exports = React.createClass({ propTypes: { version: React.PropTypes.string, year: React.PropTypes.number, author: React.PropTypes.string, email: React.PropTypes.string, githubUrl: React.PropTypes.string }, getDefaultProps: function () { return { year: new Date().getFullYear(), author: 'YourNameHere', email: '[email protected]', githubUrl: null }; }, render: function () { return DOM.footer(null, [ DOM.hr(null, null), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, [ DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small(null, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') ) ) ) ]); } });
var React = require('react'), DOM = React.DOM; module.exports = React.createClass({ propTypes: { version: React.PropTypes.string, year: React.PropTypes.number, author: React.PropTypes.string, email: React.PropTypes.string, githubUrl: React.PropTypes.string }, getDefaultProps: function () { return { year: new Date().getFullYear(), author: 'YourNameHere', email: '[email protected]', githubUrl: null }; }, render: function () { return DOM.footer(null, [ DOM.hr(null, null), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, [ DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small({ className: 'footer__version'}, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') ) ) ) ]); } });
2
2
2
mixed
--- a/components/Footer.js +++ b/components/Footer.js @@ -30,3 +30,3 @@ DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), - DOM.small(null, ' v' + this.props.version) + DOM.small({ className: 'footer__version'}, ' v' + this.props.version) ])), @@ -36,3 +36,3 @@ DOM.small(null, - DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') + DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') )
--- a/components/Footer.js +++ b/components/Footer.js @@ ... @@ DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), - DOM.small(null, ' v' + this.props.version) + DOM.small({ className: 'footer__version'}, ' v' + this.props.version) ])), @@ ... @@ DOM.small(null, - DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') + DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') )
--- a/components/Footer.js +++ b/components/Footer.js @@ -30,3 +30,3 @@ CON DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DEL DOM.small(null, ' v' + this.props.version) ADD DOM.small({ className: 'footer__version'}, ' v' + this.props.version) CON ])), @@ -36,3 +36,3 @@ CON DOM.small(null, DEL DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') ADD DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') CON )
<<<<<<< SEARCH DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small(null, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') ) ) ======= DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small({ className: 'footer__version'}, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') ) ) >>>>>>> REPLACE
kotlintest/kotlintest
0163f06fff5ae2a9a29db3572ce42c8b79ed345b
src/test/kotlin/io/kotlintest/TestCaseTest.kt
kotlin
mit
Add a test to verify tagged tests are active by default If no include / exclude tags are specified, tagged tests should be active.
package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } }
package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } "tagged tests should be active by default" { testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe true } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } }
6
0
1
add_only
--- a/src/test/kotlin/io/kotlintest/TestCaseTest.kt +++ b/src/test/kotlin/io/kotlintest/TestCaseTest.kt @@ -32,2 +32,8 @@ } + + "tagged tests should be active by default" { + testTaggedA.isActive shouldBe true + untaggedTest.isActive shouldBe true + testTaggedB.isActive shouldBe true + } }
--- a/src/test/kotlin/io/kotlintest/TestCaseTest.kt +++ b/src/test/kotlin/io/kotlintest/TestCaseTest.kt @@ ... @@ } + + "tagged tests should be active by default" { + testTaggedA.isActive shouldBe true + untaggedTest.isActive shouldBe true + testTaggedB.isActive shouldBe true + } }
--- a/src/test/kotlin/io/kotlintest/TestCaseTest.kt +++ b/src/test/kotlin/io/kotlintest/TestCaseTest.kt @@ -32,2 +32,8 @@ CON } ADD ADD "tagged tests should be active by default" { ADD testTaggedA.isActive shouldBe true ADD untaggedTest.isActive shouldBe true ADD testTaggedB.isActive shouldBe true ADD } CON }
<<<<<<< SEARCH testTaggedB.isActive shouldBe false } } ======= testTaggedB.isActive shouldBe false } "tagged tests should be active by default" { testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe true } } >>>>>>> REPLACE
arunoda/meteor-up
1abf50595d4893a904b04b8b5c03d5adf8e53743
src/updates.js
javascript
mit
Add support for beta versions to update notifier
import Npm from 'silent-npm-registry-client'; import boxen from 'boxen'; import chalk from 'chalk'; import pkg from '../package.json'; export default function() { return new Promise(function(resolve) { const params = { timeout: 1000, package: pkg.name, auth: {} }; const npm = new Npm(); const uri = 'https://registry.npmjs.org/npm'; npm.distTags.fetch(uri, params, function(err, res) { if (err) { resolve(); return; } const npmVersion = res.latest; const local = pkg.version.split('.').map(n => Number(n)); const remote = npmVersion.split('.').map(n => Number(n)); const available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (available) { let text = `update available ${pkg.version} => ${npmVersion}`; text += `\nTo update, run ${chalk.green('npm i -g mup')}`; console.log( boxen(text, { padding: 1, margin: 1, align: 'center', borderColor: 'yellow' }) ); } resolve(); }); }); }
import Npm from 'silent-npm-registry-client'; import boxen from 'boxen'; import chalk from 'chalk'; import pkg from '../package.json'; export default function() { return new Promise(function(resolve) { const params = { timeout: 1000, package: pkg.name, auth: {} }; const npm = new Npm(); const uri = 'https://registry.npmjs.org/npm'; npm.distTags.fetch(uri, params, function(err, res) { if (err) { resolve(); return; } const npmVersion = '1.2.7' || res.latest; const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); const beta = pkg.version.split('.')[2].split('-').length > 1; let available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (beta && !available) { available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; } if (available) { let text = `update available ${pkg.version} => ${npmVersion}`; text += `\nTo update, run ${chalk.green('npm i -g mup')}`; console.log( boxen(text, { padding: 1, margin: 1, align: 'center', borderColor: 'yellow' }) ); } resolve(); }); }); }
10
4
1
mixed
--- a/src/updates.js +++ b/src/updates.js @@ -21,9 +21,15 @@ - const npmVersion = res.latest; - const local = pkg.version.split('.').map(n => Number(n)); - const remote = npmVersion.split('.').map(n => Number(n)); + const npmVersion = '1.2.7' || res.latest; + const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); + const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); - const available = remote[0] > local[0] || + const beta = pkg.version.split('.')[2].split('-').length > 1; + + let available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; + + if (beta && !available) { + available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; + }
--- a/src/updates.js +++ b/src/updates.js @@ ... @@ - const npmVersion = res.latest; - const local = pkg.version.split('.').map(n => Number(n)); - const remote = npmVersion.split('.').map(n => Number(n)); + const npmVersion = '1.2.7' || res.latest; + const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); + const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); - const available = remote[0] > local[0] || + const beta = pkg.version.split('.')[2].split('-').length > 1; + + let available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; + + if (beta && !available) { + available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; + }
--- a/src/updates.js +++ b/src/updates.js @@ -21,9 +21,15 @@ CON DEL const npmVersion = res.latest; DEL const local = pkg.version.split('.').map(n => Number(n)); DEL const remote = npmVersion.split('.').map(n => Number(n)); ADD const npmVersion = '1.2.7' || res.latest; ADD const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); ADD const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); CON DEL const available = remote[0] > local[0] || ADD const beta = pkg.version.split('.')[2].split('-').length > 1; ADD ADD let available = remote[0] > local[0] || CON remote[0] === local[0] && remote[1] > local[1] || CON remote[1] === local[1] && remote[2] > local[2]; ADD ADD if (beta && !available) { ADD available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; ADD } CON
<<<<<<< SEARCH } const npmVersion = res.latest; const local = pkg.version.split('.').map(n => Number(n)); const remote = npmVersion.split('.').map(n => Number(n)); const available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (available) { ======= } const npmVersion = '1.2.7' || res.latest; const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); const beta = pkg.version.split('.')[2].split('-').length > 1; let available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (beta && !available) { available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; } if (available) { >>>>>>> REPLACE
raineszm/rust-blas
0de9e298b10c1e86704f94b2b5c10f479f87c415
src/vector/mod.rs
rust
mit
Implement BlasVector on Vec and slice
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. pub mod ll; pub mod ops; pub trait BlasVector<T> { fn inc(&self) -> i32; fn len(&self) -> i32; fn as_ptr(&self) -> *const T; fn as_mut_ptr(&mut self) -> *mut T; }
// Copyright 2014 Michael Yang. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use std::raw::Repr; pub mod ll; pub mod ops; pub trait BlasVector<T> { fn inc(&self) -> i32; fn len(&self) -> i32; fn as_ptr(&self) -> *const T; fn as_mut_ptr(&mut self) -> *mut T; } impl<T> BlasVector<T> for Vec<T> { #[inline] fn inc(&self) -> i32 { 1i32 } #[inline] fn len(&self) -> i32 { let l: Option<i32> = NumCast::from(self.len()); match l { Some(l) => l, None => panic!(), } } #[inline] fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() } #[inline] fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() } } impl<'a, T> BlasVector<T> for &'a [T] { #[inline] fn inc(&self) -> i32 { 1i32 } #[inline] fn len(&self) -> i32 { let l: Option<i32> = NumCast::from(self.len()); match l { Some(l) => l, None => panic!(), } } #[inline] fn as_ptr(&self) -> *const T { self.repr().data } #[inline] fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T } }
42
0
2
add_only
--- a/src/vector/mod.rs +++ b/src/vector/mod.rs @@ -3,2 +3,4 @@ // license that can be found in the LICENSE file. + +use std::raw::Repr; @@ -13 +15,41 @@ } + +impl<T> BlasVector<T> for Vec<T> { + #[inline] + fn inc(&self) -> i32 { 1i32 } + + #[inline] + fn len(&self) -> i32 { + let l: Option<i32> = NumCast::from(self.len()); + match l { + Some(l) => l, + None => panic!(), + } + } + + #[inline] + fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() } + + #[inline] + fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() } +} + +impl<'a, T> BlasVector<T> for &'a [T] { + #[inline] + fn inc(&self) -> i32 { 1i32 } + + #[inline] + fn len(&self) -> i32 { + let l: Option<i32> = NumCast::from(self.len()); + match l { + Some(l) => l, + None => panic!(), + } + } + + #[inline] + fn as_ptr(&self) -> *const T { self.repr().data } + + #[inline] + fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T } +}
--- a/src/vector/mod.rs +++ b/src/vector/mod.rs @@ ... @@ // license that can be found in the LICENSE file. + +use std::raw::Repr; @@ ... @@ } + +impl<T> BlasVector<T> for Vec<T> { + #[inline] + fn inc(&self) -> i32 { 1i32 } + + #[inline] + fn len(&self) -> i32 { + let l: Option<i32> = NumCast::from(self.len()); + match l { + Some(l) => l, + None => panic!(), + } + } + + #[inline] + fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() } + + #[inline] + fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() } +} + +impl<'a, T> BlasVector<T> for &'a [T] { + #[inline] + fn inc(&self) -> i32 { 1i32 } + + #[inline] + fn len(&self) -> i32 { + let l: Option<i32> = NumCast::from(self.len()); + match l { + Some(l) => l, + None => panic!(), + } + } + + #[inline] + fn as_ptr(&self) -> *const T { self.repr().data } + + #[inline] + fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T } +}
--- a/src/vector/mod.rs +++ b/src/vector/mod.rs @@ -3,2 +3,4 @@ CON // license that can be found in the LICENSE file. ADD ADD use std::raw::Repr; CON @@ -13 +15,41 @@ CON } ADD ADD impl<T> BlasVector<T> for Vec<T> { ADD #[inline] ADD fn inc(&self) -> i32 { 1i32 } ADD ADD #[inline] ADD fn len(&self) -> i32 { ADD let l: Option<i32> = NumCast::from(self.len()); ADD match l { ADD Some(l) => l, ADD None => panic!(), ADD } ADD } ADD ADD #[inline] ADD fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() } ADD ADD #[inline] ADD fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() } ADD } ADD ADD impl<'a, T> BlasVector<T> for &'a [T] { ADD #[inline] ADD fn inc(&self) -> i32 { 1i32 } ADD ADD #[inline] ADD fn len(&self) -> i32 { ADD let l: Option<i32> = NumCast::from(self.len()); ADD match l { ADD Some(l) => l, ADD None => panic!(), ADD } ADD } ADD ADD #[inline] ADD fn as_ptr(&self) -> *const T { self.repr().data } ADD ADD #[inline] ADD fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T } ADD }
<<<<<<< SEARCH // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. pub mod ll; ======= // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use std::raw::Repr; pub mod ll; >>>>>>> REPLACE <<<<<<< SEARCH fn as_mut_ptr(&mut self) -> *mut T; } ======= fn as_mut_ptr(&mut self) -> *mut T; } impl<T> BlasVector<T> for Vec<T> { #[inline] fn inc(&self) -> i32 { 1i32 } #[inline] fn len(&self) -> i32 { let l: Option<i32> = NumCast::from(self.len()); match l { Some(l) => l, None => panic!(), } } #[inline] fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() } #[inline] fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() } } impl<'a, T> BlasVector<T> for &'a [T] { #[inline] fn inc(&self) -> i32 { 1i32 } #[inline] fn len(&self) -> i32 { let l: Option<i32> = NumCast::from(self.len()); match l { Some(l) => l, None => panic!(), } } #[inline] fn as_ptr(&self) -> *const T { self.repr().data } #[inline] fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T } } >>>>>>> REPLACE
opennode/nodeconductor
96b554c62fb9449760d423f7420ae75d78998269
nodeconductor/quotas/handlers.py
python
mit
Create generic quantity quota handler(saas-217)
def add_quotas_to_scope(sender, instance, created=False, **kwargs): if created: from nodeconductor.quotas import models for quota_name in sender.QUOTAS_NAMES: models.Quota.objects.create(name=quota_name, scope=instance)
from django.db.models import signals def add_quotas_to_scope(sender, instance, created=False, **kwargs): if created: from nodeconductor.quotas import models for quota_name in sender.QUOTAS_NAMES: models.Quota.objects.create(name=quota_name, scope=instance) def quantity_quota_handler_fabric(path_to_quota_scope, quota_name, count=1): """ Return signal handler that increases or decreases quota usage by <count> on object creation or deletion :param path_to_quota_scope: path to object with quotas from created object :param quota_name: name of changed quota :param count: value, that will be added to quota usage Example. This code will add 1 to customer "nc-instances" quotas on instance creation and remove 1 on instance deletion: .. code-block:: python # handlers.py: increase_customer_nc_instances_quota = quotas_handlers.quantity_quota_handler_fabric( path_to_quota_scope='cloud_project_membership.project.customer', quota_name='nc-instances', count=1, ) # apps.py signals.post_save.connect( handlers.increase_customer_nc_instances_quota, sender=Instance, dispatch_uid='nodeconductor.iaas.handlers.increase_customer_nc_instances_quota', ) """ def handler(sender, instance, **kwargs): signal = kwargs['signal'] assert signal in (signals.post_save, signals.post_delete), \ '"quantity_quota_handler" can be used only with post_delete or post_save signals' scope = reduce(getattr, path_to_quota_scope.split("."), instance) if signal == signals.post_save and kwargs.get('created'): scope.add_quota_usage(quota_name, count) elif signal == signals.post_delete: scope.add_quota_usage(quota_name, -count) return handler
46
0
2
add_only
--- a/nodeconductor/quotas/handlers.py +++ b/nodeconductor/quotas/handlers.py @@ -1 +1,3 @@ +from django.db.models import signals + @@ -6 +8,45 @@ models.Quota.objects.create(name=quota_name, scope=instance) + + +def quantity_quota_handler_fabric(path_to_quota_scope, quota_name, count=1): + """ + Return signal handler that increases or decreases quota usage by <count> on object creation or deletion + + :param path_to_quota_scope: path to object with quotas from created object + :param quota_name: name of changed quota + :param count: value, that will be added to quota usage + + Example. + This code will add 1 to customer "nc-instances" quotas on instance creation and remove 1 on instance deletion: + + .. code-block:: python + + # handlers.py: + + increase_customer_nc_instances_quota = quotas_handlers.quantity_quota_handler_fabric( + path_to_quota_scope='cloud_project_membership.project.customer', + quota_name='nc-instances', + count=1, + ) + + # apps.py + + signals.post_save.connect( + handlers.increase_customer_nc_instances_quota, + sender=Instance, + dispatch_uid='nodeconductor.iaas.handlers.increase_customer_nc_instances_quota', + ) + + """ + def handler(sender, instance, **kwargs): + signal = kwargs['signal'] + assert signal in (signals.post_save, signals.post_delete), \ + '"quantity_quota_handler" can be used only with post_delete or post_save signals' + + scope = reduce(getattr, path_to_quota_scope.split("."), instance) + if signal == signals.post_save and kwargs.get('created'): + scope.add_quota_usage(quota_name, count) + elif signal == signals.post_delete: + scope.add_quota_usage(quota_name, -count) + + return handler
--- a/nodeconductor/quotas/handlers.py +++ b/nodeconductor/quotas/handlers.py @@ ... @@ +from django.db.models import signals + @@ ... @@ models.Quota.objects.create(name=quota_name, scope=instance) + + +def quantity_quota_handler_fabric(path_to_quota_scope, quota_name, count=1): + """ + Return signal handler that increases or decreases quota usage by <count> on object creation or deletion + + :param path_to_quota_scope: path to object with quotas from created object + :param quota_name: name of changed quota + :param count: value, that will be added to quota usage + + Example. + This code will add 1 to customer "nc-instances" quotas on instance creation and remove 1 on instance deletion: + + .. code-block:: python + + # handlers.py: + + increase_customer_nc_instances_quota = quotas_handlers.quantity_quota_handler_fabric( + path_to_quota_scope='cloud_project_membership.project.customer', + quota_name='nc-instances', + count=1, + ) + + # apps.py + + signals.post_save.connect( + handlers.increase_customer_nc_instances_quota, + sender=Instance, + dispatch_uid='nodeconductor.iaas.handlers.increase_customer_nc_instances_quota', + ) + + """ + def handler(sender, instance, **kwargs): + signal = kwargs['signal'] + assert signal in (signals.post_save, signals.post_delete), \ + '"quantity_quota_handler" can be used only with post_delete or post_save signals' + + scope = reduce(getattr, path_to_quota_scope.split("."), instance) + if signal == signals.post_save and kwargs.get('created'): + scope.add_quota_usage(quota_name, count) + elif signal == signals.post_delete: + scope.add_quota_usage(quota_name, -count) + + return handler
--- a/nodeconductor/quotas/handlers.py +++ b/nodeconductor/quotas/handlers.py @@ -1 +1,3 @@ ADD from django.db.models import signals ADD CON @@ -6 +8,45 @@ CON models.Quota.objects.create(name=quota_name, scope=instance) ADD ADD ADD def quantity_quota_handler_fabric(path_to_quota_scope, quota_name, count=1): ADD """ ADD Return signal handler that increases or decreases quota usage by <count> on object creation or deletion ADD ADD :param path_to_quota_scope: path to object with quotas from created object ADD :param quota_name: name of changed quota ADD :param count: value, that will be added to quota usage ADD ADD Example. ADD This code will add 1 to customer "nc-instances" quotas on instance creation and remove 1 on instance deletion: ADD ADD .. code-block:: python ADD ADD # handlers.py: ADD ADD increase_customer_nc_instances_quota = quotas_handlers.quantity_quota_handler_fabric( ADD path_to_quota_scope='cloud_project_membership.project.customer', ADD quota_name='nc-instances', ADD count=1, ADD ) ADD ADD # apps.py ADD ADD signals.post_save.connect( ADD handlers.increase_customer_nc_instances_quota, ADD sender=Instance, ADD dispatch_uid='nodeconductor.iaas.handlers.increase_customer_nc_instances_quota', ADD ) ADD ADD """ ADD def handler(sender, instance, **kwargs): ADD signal = kwargs['signal'] ADD assert signal in (signals.post_save, signals.post_delete), \ ADD '"quantity_quota_handler" can be used only with post_delete or post_save signals' ADD ADD scope = reduce(getattr, path_to_quota_scope.split("."), instance) ADD if signal == signals.post_save and kwargs.get('created'): ADD scope.add_quota_usage(quota_name, count) ADD elif signal == signals.post_delete: ADD scope.add_quota_usage(quota_name, -count) ADD ADD return handler
<<<<<<< SEARCH def add_quotas_to_scope(sender, instance, created=False, **kwargs): ======= from django.db.models import signals def add_quotas_to_scope(sender, instance, created=False, **kwargs): >>>>>>> REPLACE <<<<<<< SEARCH for quota_name in sender.QUOTAS_NAMES: models.Quota.objects.create(name=quota_name, scope=instance) ======= for quota_name in sender.QUOTAS_NAMES: models.Quota.objects.create(name=quota_name, scope=instance) def quantity_quota_handler_fabric(path_to_quota_scope, quota_name, count=1): """ Return signal handler that increases or decreases quota usage by <count> on object creation or deletion :param path_to_quota_scope: path to object with quotas from created object :param quota_name: name of changed quota :param count: value, that will be added to quota usage Example. This code will add 1 to customer "nc-instances" quotas on instance creation and remove 1 on instance deletion: .. code-block:: python # handlers.py: increase_customer_nc_instances_quota = quotas_handlers.quantity_quota_handler_fabric( path_to_quota_scope='cloud_project_membership.project.customer', quota_name='nc-instances', count=1, ) # apps.py signals.post_save.connect( handlers.increase_customer_nc_instances_quota, sender=Instance, dispatch_uid='nodeconductor.iaas.handlers.increase_customer_nc_instances_quota', ) """ def handler(sender, instance, **kwargs): signal = kwargs['signal'] assert signal in (signals.post_save, signals.post_delete), \ '"quantity_quota_handler" can be used only with post_delete or post_save signals' scope = reduce(getattr, path_to_quota_scope.split("."), instance) if signal == signals.post_save and kwargs.get('created'): scope.add_quota_usage(quota_name, count) elif signal == signals.post_delete: scope.add_quota_usage(quota_name, -count) return handler >>>>>>> REPLACE
magum/rust-rosetta
a6f0d969307f70b1d0894c2ecfc6dac1800acdc4
src/lib.rs
rust
unlicense
Check that source files are covered by Cargo.toml Closes https://github.com/Hoverbear/rust-rosetta/issues/236
// Dummy main library // not_tested #[allow(dead_code)] #[cfg(not(test))] fn main() { }
// Dummy main library // It also contains a test module, which checks if all source files are covered by `Cargo.toml` #![feature(phase)] extern crate regex; #[phase(plugin)] extern crate regex_macros; #[allow(dead_code)] #[cfg(not(test))] fn main() { } #[cfg(test)] mod test { use std::collections::HashSet; use std::io::BufferedReader; use std::io::fs::{mod, File}; // A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if not_covered.len() > 0 { println!("Error, the following source files are not covered by Cargo.toml:"); for source in not_covered.iter() { println!("{}", source); } fail!("Please add the previous source files to Cargo.toml"); } } // Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::readdir(&Path::new("./src")).unwrap(); paths.iter().map(|p| p.filename_str().unwrap().to_string()) .filter(|s| s[].ends_with(".rs")).collect() } // Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open(&Path::new("./Cargo.toml")).unwrap(); let mut reader = BufferedReader::new(c_toml); let regex = regex!("path = \"(.*)\""); reader.lines().filter_map(|l| { let l = l.unwrap(); regex.captures(l[]).map(|c| Path::new(c.at(1)).filename_str().unwrap().to_string()) }).collect() } // Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } }
54
2
1
mixed
--- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,59 @@ // Dummy main library -// not_tested +// It also contains a test module, which checks if all source files are covered by `Cargo.toml` + +#![feature(phase)] + +extern crate regex; +#[phase(plugin)] extern crate regex_macros; + #[allow(dead_code)] #[cfg(not(test))] +fn main() { } -fn main() { +#[cfg(test)] +mod test { + use std::collections::HashSet; + use std::io::BufferedReader; + use std::io::fs::{mod, File}; + + // A test to check if all source files are covered by `Cargo.toml` + #[test] + fn check_sources_covered() { + let sources = get_source_files(); + let bins = get_toml_paths(); + let not_covered = get_not_covered(&sources, &bins); + + if not_covered.len() > 0 { + println!("Error, the following source files are not covered by Cargo.toml:"); + + for source in not_covered.iter() { + println!("{}", source); + } + + fail!("Please add the previous source files to Cargo.toml"); + } + } + + // Returns the names of the source files in the `src` directory + fn get_source_files() -> HashSet<String> { + let paths = fs::readdir(&Path::new("./src")).unwrap(); + paths.iter().map(|p| p.filename_str().unwrap().to_string()) + .filter(|s| s[].ends_with(".rs")).collect() + } + + // Returns the paths of the source files referenced in Cargo.toml + fn get_toml_paths() -> HashSet<String> { + let c_toml = File::open(&Path::new("./Cargo.toml")).unwrap(); + let mut reader = BufferedReader::new(c_toml); + let regex = regex!("path = \"(.*)\""); + reader.lines().filter_map(|l| { + let l = l.unwrap(); + regex.captures(l[]).map(|c| Path::new(c.at(1)).filename_str().unwrap().to_string()) + }).collect() + } + + // Returns the filenames of the source files which are not covered by Cargo.toml + fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { + sources.difference(paths).collect() + } }
--- a/src/lib.rs +++ b/src/lib.rs @@ ... @@ // Dummy main library -// not_tested +// It also contains a test module, which checks if all source files are covered by `Cargo.toml` + +#![feature(phase)] + +extern crate regex; +#[phase(plugin)] extern crate regex_macros; + #[allow(dead_code)] #[cfg(not(test))] +fn main() { } -fn main() { +#[cfg(test)] +mod test { + use std::collections::HashSet; + use std::io::BufferedReader; + use std::io::fs::{mod, File}; + + // A test to check if all source files are covered by `Cargo.toml` + #[test] + fn check_sources_covered() { + let sources = get_source_files(); + let bins = get_toml_paths(); + let not_covered = get_not_covered(&sources, &bins); + + if not_covered.len() > 0 { + println!("Error, the following source files are not covered by Cargo.toml:"); + + for source in not_covered.iter() { + println!("{}", source); + } + + fail!("Please add the previous source files to Cargo.toml"); + } + } + + // Returns the names of the source files in the `src` directory + fn get_source_files() -> HashSet<String> { + let paths = fs::readdir(&Path::new("./src")).unwrap(); + paths.iter().map(|p| p.filename_str().unwrap().to_string()) + .filter(|s| s[].ends_with(".rs")).collect() + } + + // Returns the paths of the source files referenced in Cargo.toml + fn get_toml_paths() -> HashSet<String> { + let c_toml = File::open(&Path::new("./Cargo.toml")).unwrap(); + let mut reader = BufferedReader::new(c_toml); + let regex = regex!("path = \"(.*)\""); + reader.lines().filter_map(|l| { + let l = l.unwrap(); + regex.captures(l[]).map(|c| Path::new(c.at(1)).filename_str().unwrap().to_string()) + }).collect() + } + + // Returns the filenames of the source files which are not covered by Cargo.toml + fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { + sources.difference(paths).collect() + } }
--- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,59 @@ CON // Dummy main library DEL // not_tested ADD // It also contains a test module, which checks if all source files are covered by `Cargo.toml` ADD ADD #![feature(phase)] ADD ADD extern crate regex; ADD #[phase(plugin)] extern crate regex_macros; ADD CON #[allow(dead_code)] CON #[cfg(not(test))] ADD fn main() { } CON DEL fn main() { ADD #[cfg(test)] ADD mod test { ADD use std::collections::HashSet; ADD use std::io::BufferedReader; ADD use std::io::fs::{mod, File}; ADD ADD // A test to check if all source files are covered by `Cargo.toml` ADD #[test] ADD fn check_sources_covered() { ADD let sources = get_source_files(); ADD let bins = get_toml_paths(); ADD let not_covered = get_not_covered(&sources, &bins); ADD ADD if not_covered.len() > 0 { ADD println!("Error, the following source files are not covered by Cargo.toml:"); ADD ADD for source in not_covered.iter() { ADD println!("{}", source); ADD } ADD ADD fail!("Please add the previous source files to Cargo.toml"); ADD } ADD } ADD ADD // Returns the names of the source files in the `src` directory ADD fn get_source_files() -> HashSet<String> { ADD let paths = fs::readdir(&Path::new("./src")).unwrap(); ADD paths.iter().map(|p| p.filename_str().unwrap().to_string()) ADD .filter(|s| s[].ends_with(".rs")).collect() ADD } ADD ADD // Returns the paths of the source files referenced in Cargo.toml ADD fn get_toml_paths() -> HashSet<String> { ADD let c_toml = File::open(&Path::new("./Cargo.toml")).unwrap(); ADD let mut reader = BufferedReader::new(c_toml); ADD let regex = regex!("path = \"(.*)\""); ADD reader.lines().filter_map(|l| { ADD let l = l.unwrap(); ADD regex.captures(l[]).map(|c| Path::new(c.at(1)).filename_str().unwrap().to_string()) ADD }).collect() ADD } ADD ADD // Returns the filenames of the source files which are not covered by Cargo.toml ADD fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { ADD sources.difference(paths).collect() ADD } CON }
<<<<<<< SEARCH // Dummy main library // not_tested #[allow(dead_code)] #[cfg(not(test))] fn main() { } ======= // Dummy main library // It also contains a test module, which checks if all source files are covered by `Cargo.toml` #![feature(phase)] extern crate regex; #[phase(plugin)] extern crate regex_macros; #[allow(dead_code)] #[cfg(not(test))] fn main() { } #[cfg(test)] mod test { use std::collections::HashSet; use std::io::BufferedReader; use std::io::fs::{mod, File}; // A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if not_covered.len() > 0 { println!("Error, the following source files are not covered by Cargo.toml:"); for source in not_covered.iter() { println!("{}", source); } fail!("Please add the previous source files to Cargo.toml"); } } // Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::readdir(&Path::new("./src")).unwrap(); paths.iter().map(|p| p.filename_str().unwrap().to_string()) .filter(|s| s[].ends_with(".rs")).collect() } // Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open(&Path::new("./Cargo.toml")).unwrap(); let mut reader = BufferedReader::new(c_toml); let regex = regex!("path = \"(.*)\""); reader.lines().filter_map(|l| { let l = l.unwrap(); regex.captures(l[]).map(|c| Path::new(c.at(1)).filename_str().unwrap().to_string()) }).collect() } // Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } } >>>>>>> REPLACE
dtolnay/cxx
4aea27578878bdd8416a2c95defcef57d9d65302
cmd/src/main.rs
rust
apache-2.0
Use clap's required_unless to enforce input file path
mod gen; mod syntax; use gen::include; use std::io::{self, Write}; use std::path::PathBuf; use std::process; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "cxxbridge", author)] struct Opt { /// Input Rust source file containing #[cxx::bridge] #[structopt(parse(from_os_str))] input: Option<PathBuf>, /// Emit header with declarations only #[structopt(long)] header: bool, } fn main() { let opt = Opt::from_args(); if let Some(input) = opt.input { let gen = if opt.header { gen::do_generate_header } else { gen::do_generate_bridge }; let bridge = gen(&input); let _ = io::stdout().lock().write_all(bridge.as_ref()); } else if opt.header { let header = include::HEADER; let _ = io::stdout().lock().write_all(header.as_ref()); } else { let _ = Opt::clap().after_help("").print_help(); process::exit(1); } }
mod gen; mod syntax; use gen::include; use std::io::{self, Write}; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "cxxbridge", author)] struct Opt { /// Input Rust source file containing #[cxx::bridge] #[structopt(parse(from_os_str), required_unless = "header")] input: Option<PathBuf>, /// Emit header with declarations only #[structopt(long)] header: bool, } fn write(content: impl AsRef<[u8]>) { let _ = io::stdout().lock().write_all(content.as_ref()); } fn main() { let opt = Opt::from_args(); match (opt.input, opt.header) { (Some(input), true) => write(gen::do_generate_header(&input)), (Some(input), false) => write(gen::do_generate_bridge(&input)), (None, true) => write(include::HEADER), (None, false) => unreachable!(), // enforced by required_unless } }
10
16
4
mixed
--- a/cmd/src/main.rs +++ b/cmd/src/main.rs @@ -6,3 +6,2 @@ use std::path::PathBuf; -use std::process; use structopt::StructOpt; @@ -13,3 +12,3 @@ /// Input Rust source file containing #[cxx::bridge] - #[structopt(parse(from_os_str))] + #[structopt(parse(from_os_str), required_unless = "header")] input: Option<PathBuf>, @@ -21,2 +20,6 @@ +fn write(content: impl AsRef<[u8]>) { + let _ = io::stdout().lock().write_all(content.as_ref()); +} + fn main() { @@ -24,16 +27,7 @@ - if let Some(input) = opt.input { - let gen = if opt.header { - gen::do_generate_header - } else { - gen::do_generate_bridge - }; - let bridge = gen(&input); - let _ = io::stdout().lock().write_all(bridge.as_ref()); - } else if opt.header { - let header = include::HEADER; - let _ = io::stdout().lock().write_all(header.as_ref()); - } else { - let _ = Opt::clap().after_help("").print_help(); - process::exit(1); + match (opt.input, opt.header) { + (Some(input), true) => write(gen::do_generate_header(&input)), + (Some(input), false) => write(gen::do_generate_bridge(&input)), + (None, true) => write(include::HEADER), + (None, false) => unreachable!(), // enforced by required_unless }
--- a/cmd/src/main.rs +++ b/cmd/src/main.rs @@ ... @@ use std::path::PathBuf; -use std::process; use structopt::StructOpt; @@ ... @@ /// Input Rust source file containing #[cxx::bridge] - #[structopt(parse(from_os_str))] + #[structopt(parse(from_os_str), required_unless = "header")] input: Option<PathBuf>, @@ ... @@ +fn write(content: impl AsRef<[u8]>) { + let _ = io::stdout().lock().write_all(content.as_ref()); +} + fn main() { @@ ... @@ - if let Some(input) = opt.input { - let gen = if opt.header { - gen::do_generate_header - } else { - gen::do_generate_bridge - }; - let bridge = gen(&input); - let _ = io::stdout().lock().write_all(bridge.as_ref()); - } else if opt.header { - let header = include::HEADER; - let _ = io::stdout().lock().write_all(header.as_ref()); - } else { - let _ = Opt::clap().after_help("").print_help(); - process::exit(1); + match (opt.input, opt.header) { + (Some(input), true) => write(gen::do_generate_header(&input)), + (Some(input), false) => write(gen::do_generate_bridge(&input)), + (None, true) => write(include::HEADER), + (None, false) => unreachable!(), // enforced by required_unless }
--- a/cmd/src/main.rs +++ b/cmd/src/main.rs @@ -6,3 +6,2 @@ CON use std::path::PathBuf; DEL use std::process; CON use structopt::StructOpt; @@ -13,3 +12,3 @@ CON /// Input Rust source file containing #[cxx::bridge] DEL #[structopt(parse(from_os_str))] ADD #[structopt(parse(from_os_str), required_unless = "header")] CON input: Option<PathBuf>, @@ -21,2 +20,6 @@ CON ADD fn write(content: impl AsRef<[u8]>) { ADD let _ = io::stdout().lock().write_all(content.as_ref()); ADD } ADD CON fn main() { @@ -24,16 +27,7 @@ CON DEL if let Some(input) = opt.input { DEL let gen = if opt.header { DEL gen::do_generate_header DEL } else { DEL gen::do_generate_bridge DEL }; DEL let bridge = gen(&input); DEL let _ = io::stdout().lock().write_all(bridge.as_ref()); DEL } else if opt.header { DEL let header = include::HEADER; DEL let _ = io::stdout().lock().write_all(header.as_ref()); DEL } else { DEL let _ = Opt::clap().after_help("").print_help(); DEL process::exit(1); ADD match (opt.input, opt.header) { ADD (Some(input), true) => write(gen::do_generate_header(&input)), ADD (Some(input), false) => write(gen::do_generate_bridge(&input)), ADD (None, true) => write(include::HEADER), ADD (None, false) => unreachable!(), // enforced by required_unless CON }
<<<<<<< SEARCH use std::io::{self, Write}; use std::path::PathBuf; use std::process; use structopt::StructOpt; ======= use std::io::{self, Write}; use std::path::PathBuf; use structopt::StructOpt; >>>>>>> REPLACE <<<<<<< SEARCH struct Opt { /// Input Rust source file containing #[cxx::bridge] #[structopt(parse(from_os_str))] input: Option<PathBuf>, ======= struct Opt { /// Input Rust source file containing #[cxx::bridge] #[structopt(parse(from_os_str), required_unless = "header")] input: Option<PathBuf>, >>>>>>> REPLACE <<<<<<< SEARCH } fn main() { let opt = Opt::from_args(); if let Some(input) = opt.input { let gen = if opt.header { gen::do_generate_header } else { gen::do_generate_bridge }; let bridge = gen(&input); let _ = io::stdout().lock().write_all(bridge.as_ref()); } else if opt.header { let header = include::HEADER; let _ = io::stdout().lock().write_all(header.as_ref()); } else { let _ = Opt::clap().after_help("").print_help(); process::exit(1); } } ======= } fn write(content: impl AsRef<[u8]>) { let _ = io::stdout().lock().write_all(content.as_ref()); } fn main() { let opt = Opt::from_args(); match (opt.input, opt.header) { (Some(input), true) => write(gen::do_generate_header(&input)), (Some(input), false) => write(gen::do_generate_bridge(&input)), (None, true) => write(include::HEADER), (None, false) => unreachable!(), // enforced by required_unless } } >>>>>>> REPLACE
android/tv-samples
00fc23d3ab920d52682d2e2b9630f762979b35f8
ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt
kotlin
apache-2.0
Enable StrictMode for debug builds The penalty is only set to log so this should not prevent development yet still give developers a way to easily spot/find the violation. Bug: 162035725 Change-Id: Id518dda3076c395a8f2721dd780fc5c3a6e8f60c
/* * Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference import android.app.Application import timber.log.Timber /** * Initializes libraries, such as Timber, and sets up application wide settings. */ class TvReferenceApplication : Application() { override fun onCreate() { super.onCreate() // TODO(b/162013888): Plant a timber tree for non-debug builds. if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } }
/* * Copyright 2020 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference import android.app.Application import android.os.StrictMode import timber.log.Timber /** * Initializes libraries, such as Timber, and sets up application wide settings. */ class TvReferenceApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { enableStrictMode() } // TODO(b/162013888): Plant a timber tree for non-debug builds. if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } private fun enableStrictMode() { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build() ) } }
16
0
3
add_only
--- a/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt +++ b/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt @@ -18,2 +18,3 @@ import android.app.Application +import android.os.StrictMode import timber.log.Timber @@ -28,2 +29,6 @@ + if (BuildConfig.DEBUG) { + enableStrictMode() + } + // TODO(b/162013888): Plant a timber tree for non-debug builds. @@ -33,2 +38,13 @@ } + + private fun enableStrictMode() { + StrictMode.setThreadPolicy( + StrictMode.ThreadPolicy.Builder() + .detectDiskReads() + .detectDiskWrites() + .detectNetwork() + .penaltyLog() + .build() + ) + } }
--- a/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt +++ b/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt @@ ... @@ import android.app.Application +import android.os.StrictMode import timber.log.Timber @@ ... @@ + if (BuildConfig.DEBUG) { + enableStrictMode() + } + // TODO(b/162013888): Plant a timber tree for non-debug builds. @@ ... @@ } + + private fun enableStrictMode() { + StrictMode.setThreadPolicy( + StrictMode.ThreadPolicy.Builder() + .detectDiskReads() + .detectDiskWrites() + .detectNetwork() + .penaltyLog() + .build() + ) + } }
--- a/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt +++ b/ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/TvReferenceApplication.kt @@ -18,2 +18,3 @@ CON import android.app.Application ADD import android.os.StrictMode CON import timber.log.Timber @@ -28,2 +29,6 @@ CON ADD if (BuildConfig.DEBUG) { ADD enableStrictMode() ADD } ADD CON // TODO(b/162013888): Plant a timber tree for non-debug builds. @@ -33,2 +38,13 @@ CON } ADD ADD private fun enableStrictMode() { ADD StrictMode.setThreadPolicy( ADD StrictMode.ThreadPolicy.Builder() ADD .detectDiskReads() ADD .detectDiskWrites() ADD .detectNetwork() ADD .penaltyLog() ADD .build() ADD ) ADD } CON }
<<<<<<< SEARCH import android.app.Application import timber.log.Timber ======= import android.app.Application import android.os.StrictMode import timber.log.Timber >>>>>>> REPLACE <<<<<<< SEARCH super.onCreate() // TODO(b/162013888): Plant a timber tree for non-debug builds. if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } } ======= super.onCreate() if (BuildConfig.DEBUG) { enableStrictMode() } // TODO(b/162013888): Plant a timber tree for non-debug builds. if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } private fun enableStrictMode() { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build() ) } } >>>>>>> REPLACE
Armavica/99-Problems-Rust
e8ff455dbce28e641cbcae19596562fe0631a8f7
01-10/p10.rs
rust
cc0-1.0
Remove unique vector matching from Problem 10
enum Node<T> { One(T), Many(uint, T) } fn pack<T: Clone+Eq>(list: &[T]) -> ~[~[T]] { let mut it = list.iter(); let mut result = ~[]; let mut l = 1; loop { match it.nth(l - 1) { Some(e) => { let mut slice = ~[]; slice.push(e.clone()); for f in it.take_while(|&a| *a == *e) { slice.push(f.clone()); } l = slice.len(); result.push(slice); }, None => break } } result } fn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] { list.map(|e| match *e { [ref a] => One(a.clone()), [ref a, ..] => Many(e.len(), a.clone()), _ => unreachable!() }) } fn main() { let list = ~['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']; println!("{:?}", encode(pack(list))); }
enum Node<T> { One(T), Many(uint, T) } fn pack<T: Clone+Eq>(list: &[T]) -> ~[~[T]] { let mut it = list.iter(); let mut result = ~[]; let mut l = 1; loop { match it.nth(l - 1) { Some(e) => { let mut slice = ~[]; slice.push(e.clone()); for f in it.take_while(|&a| *a == *e) { slice.push(f.clone()); } l = slice.len(); result.push(slice); }, None => break } } result } fn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] { list.map(|e| match e.len() { 1 => One(e[0].clone()), n => Many(n, e[0].clone()) }) } fn main() { let list = ~['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']; println!("{:?}", encode(pack(list))); }
3
4
1
mixed
--- a/01-10/p10.rs +++ b/01-10/p10.rs @@ -28,6 +28,5 @@ list.map(|e| - match *e { - [ref a] => One(a.clone()), - [ref a, ..] => Many(e.len(), a.clone()), - _ => unreachable!() + match e.len() { + 1 => One(e[0].clone()), + n => Many(n, e[0].clone()) })
--- a/01-10/p10.rs +++ b/01-10/p10.rs @@ ... @@ list.map(|e| - match *e { - [ref a] => One(a.clone()), - [ref a, ..] => Many(e.len(), a.clone()), - _ => unreachable!() + match e.len() { + 1 => One(e[0].clone()), + n => Many(n, e[0].clone()) })
--- a/01-10/p10.rs +++ b/01-10/p10.rs @@ -28,6 +28,5 @@ CON list.map(|e| DEL match *e { DEL [ref a] => One(a.clone()), DEL [ref a, ..] => Many(e.len(), a.clone()), DEL _ => unreachable!() ADD match e.len() { ADD 1 => One(e[0].clone()), ADD n => Many(n, e[0].clone()) CON })
<<<<<<< SEARCH fn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] { list.map(|e| match *e { [ref a] => One(a.clone()), [ref a, ..] => Many(e.len(), a.clone()), _ => unreachable!() }) } ======= fn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] { list.map(|e| match e.len() { 1 => One(e[0].clone()), n => Many(n, e[0].clone()) }) } >>>>>>> REPLACE
tylerreisinger/rust-color
b9f0831d1839db86beab44e0dcd29ee5fcc028a2
src/color.rs
rust
mit
Remove ColorCast trait for now
use num; pub trait Color: Clone + PartialEq { type Tag; type ChannelsTuple; fn num_channels() -> u32; fn from_tuple(values: Self::ChannelsTuple) -> Self; fn to_tuple(self) -> Self::ChannelsTuple; } pub trait PolarColor: Color { type Angular; type Cartesian; } pub trait Flatten: Color { type ScalarFormat; fn from_slice(values: &[Self::ScalarFormat]) -> Self; fn as_slice(&self) -> &[Self::ScalarFormat]; } pub trait HomogeneousColor: Color { type ChannelFormat; fn broadcast(value: Self::ChannelFormat) -> Self; fn clamp(self, min: Self::ChannelFormat, max: Self::ChannelFormat) -> Self; } pub trait Color3: Color {} pub trait Color4: Color {} pub trait Lerp { type Position: num::Float; fn lerp(&self, right: &Self, pos: Self::Position) -> Self; } pub trait Invert { fn invert(self) -> Self; } pub trait Bounded { fn normalize(self) -> Self; fn is_normalized(&self) -> bool; } pub trait ColorCast: Color { fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>; }
use num; pub trait Color: Clone + PartialEq { type Tag; type ChannelsTuple; fn num_channels() -> u32; fn from_tuple(values: Self::ChannelsTuple) -> Self; fn to_tuple(self) -> Self::ChannelsTuple; } pub trait PolarColor: Color { type Angular; type Cartesian; } pub trait Flatten: Color { type ScalarFormat; fn from_slice(values: &[Self::ScalarFormat]) -> Self; fn as_slice(&self) -> &[Self::ScalarFormat]; } pub trait HomogeneousColor: Color { type ChannelFormat; fn broadcast(value: Self::ChannelFormat) -> Self; fn clamp(self, min: Self::ChannelFormat, max: Self::ChannelFormat) -> Self; } pub trait Color3: Color {} pub trait Color4: Color {} pub trait Lerp { type Position: num::Float; fn lerp(&self, right: &Self, pos: Self::Position) -> Self; } pub trait Invert { fn invert(self) -> Self; } pub trait Bounded { fn normalize(self) -> Self; fn is_normalized(&self) -> bool; }
0
3
1
del_only
--- a/src/color.rs +++ b/src/color.rs @@ -46,4 +46 @@ -pub trait ColorCast: Color { - fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>; -}
--- a/src/color.rs +++ b/src/color.rs @@ ... @@ -pub trait ColorCast: Color { - fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>; -}
--- a/src/color.rs +++ b/src/color.rs @@ -46,4 +46 @@ CON DEL pub trait ColorCast: Color { DEL fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>; DEL }
<<<<<<< SEARCH } pub trait ColorCast: Color { fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>; } ======= } >>>>>>> REPLACE
takke/DataStats
c0be5d3e98bfaa910c3d9de04d1f83ca79d8b8be
app/src/main/java/jp/takke/datastats/BootReceiver.java
java
apache-2.0
Fix crash on boot (Android 8.0 or later)
package jp.takke.datastats; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import jp.takke.util.MyLog; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MyLog.i("BootReceiver.onReceive"); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // 端末起動時の処理 // 自動起動の確認 final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final boolean startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, false); MyLog.i("start on boot[" + (startOnBoot ? "YES" : "NO") + "]"); if (startOnBoot) { // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); context.startService(serviceIntent); } } } }
package jp.takke.datastats; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import jp.takke.util.MyLog; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MyLog.i("BootReceiver.onReceive"); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // 端末起動時の処理 // 自動起動の確認 final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final boolean startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, false); MyLog.i("start on boot[" + (startOnBoot ? "YES" : "NO") + "]"); if (startOnBoot) { // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); if (Build.VERSION.SDK_INT >= 26) { context.startForegroundService(serviceIntent); } else { context.startService(serviceIntent); } } } } }
6
1
2
mixed
--- a/app/src/main/java/jp/takke/datastats/BootReceiver.java +++ b/app/src/main/java/jp/takke/datastats/BootReceiver.java @@ -6,2 +6,3 @@ import android.content.SharedPreferences; +import android.os.Build; import android.preference.PreferenceManager; @@ -29,3 +30,7 @@ final Intent serviceIntent = new Intent(context, LayerService.class); - context.startService(serviceIntent); + if (Build.VERSION.SDK_INT >= 26) { + context.startForegroundService(serviceIntent); + } else { + context.startService(serviceIntent); + } }
--- a/app/src/main/java/jp/takke/datastats/BootReceiver.java +++ b/app/src/main/java/jp/takke/datastats/BootReceiver.java @@ ... @@ import android.content.SharedPreferences; +import android.os.Build; import android.preference.PreferenceManager; @@ ... @@ final Intent serviceIntent = new Intent(context, LayerService.class); - context.startService(serviceIntent); + if (Build.VERSION.SDK_INT >= 26) { + context.startForegroundService(serviceIntent); + } else { + context.startService(serviceIntent); + } }
--- a/app/src/main/java/jp/takke/datastats/BootReceiver.java +++ b/app/src/main/java/jp/takke/datastats/BootReceiver.java @@ -6,2 +6,3 @@ CON import android.content.SharedPreferences; ADD import android.os.Build; CON import android.preference.PreferenceManager; @@ -29,3 +30,7 @@ CON final Intent serviceIntent = new Intent(context, LayerService.class); DEL context.startService(serviceIntent); ADD if (Build.VERSION.SDK_INT >= 26) { ADD context.startForegroundService(serviceIntent); ADD } else { ADD context.startService(serviceIntent); ADD } CON }
<<<<<<< SEARCH import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; ======= import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; >>>>>>> REPLACE <<<<<<< SEARCH // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); context.startService(serviceIntent); } } ======= // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); if (Build.VERSION.SDK_INT >= 26) { context.startForegroundService(serviceIntent); } else { context.startService(serviceIntent); } } } >>>>>>> REPLACE
Lukasa/hyper
d6b7cccb14cd1f82bb3a6b070999204fafacf07e
hyper/common/util.py
python
mit
Fix to_host_port_tuple to resolve test case issues
# -*- coding: utf-8 -*- """ hyper/common/util ~~~~~~~~~~~~~~~~~ General utility functions for use with hyper. """ from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ try: host, port = host_port_str.rsplit(':', 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
# -*- coding: utf-8 -*- """ hyper/common/util ~~~~~~~~~~~~~~~~~ General utility functions for use with hyper. """ from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ if ']' in host_port_str: delim = ']:' else: delim = ':' try: host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
6
1
1
mixed
--- a/hyper/common/util.py +++ b/hyper/common/util.py @@ -33,4 +33,9 @@ """ + if ']' in host_port_str: + delim = ']:' + else: + delim = ':' + try: - host, port = host_port_str.rsplit(':', 1) + host, port = host_port_str.rsplit(delim, 1) except ValueError:
--- a/hyper/common/util.py +++ b/hyper/common/util.py @@ ... @@ """ + if ']' in host_port_str: + delim = ']:' + else: + delim = ':' + try: - host, port = host_port_str.rsplit(':', 1) + host, port = host_port_str.rsplit(delim, 1) except ValueError:
--- a/hyper/common/util.py +++ b/hyper/common/util.py @@ -33,4 +33,9 @@ CON """ ADD if ']' in host_port_str: ADD delim = ']:' ADD else: ADD delim = ':' ADD CON try: DEL host, port = host_port_str.rsplit(':', 1) ADD host, port = host_port_str.rsplit(delim, 1) CON except ValueError:
<<<<<<< SEARCH to a tuple. """ try: host, port = host_port_str.rsplit(':', 1) except ValueError: host, port = host_port_str, default_port ======= to a tuple. """ if ']' in host_port_str: delim = ']:' else: delim = ':' try: host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port >>>>>>> REPLACE
SumOfUs/Champaign
b7a630ec9e2467eb172bb4ed55d6c24401f970d7
app/assets/javascripts/member-facing/backbone/petition.js
javascript
mit
Add option to Petition.js to skip post submit action
const GlobalEvents = require('shared/global_events'); const Petition = Backbone.View.extend({ el: '.petition-bar', globalEvents: { 'form:submitted': 'handleSuccess', }, // options: object with any of the following keys // followUpUrl: the url to redirect to after success // submissionCallback: callback with event and server data for successful submission initialize(options = {}) { this.followUpUrl = options.followUpUrl; this.submissionCallback = options.submissionCallback; GlobalEvents.bindEvents(this); }, handleSuccess(e, data) { let hasCallbackFunction = (typeof this.submissionCallback === 'function'); if (hasCallbackFunction) { this.submissionCallback(e, data); } if (data && data.follow_up_url) { this.redirectTo(data.follow_up_url); } else if (this.followUpUrl) { this.redirectTo(this.followUpUrl); } else if(!hasCallbackFunction) { // only do this option if no redirect or callback supplied alert(I18n.t('petition.excited_confirmation')); } }, redirectTo(url) { window.location.href = url; }, }); module.exports = Petition;
const GlobalEvents = require('shared/global_events'); const Petition = Backbone.View.extend({ el: '.petition-bar', globalEvents: { 'form:submitted': 'handleSuccess', }, // options: object with any of the following keys // followUpUrl: the url to redirect to after success // submissionCallback: callback with event and server data for successful submission initialize(options = {}) { this.followUpUrl = options.followUpUrl; this.submissionCallback = options.submissionCallback; this.skipOnSuccessAction = options.skipOnSuccessAction; GlobalEvents.bindEvents(this); }, handleSuccess(e, data) { $.publish('petition:submitted'); if(this.skipOnSuccessAction) { return; } let hasCallbackFunction = (typeof this.submissionCallback === 'function'); if (hasCallbackFunction) { this.submissionCallback(e, data); } if (data && data.follow_up_url) { this.redirectTo(data.follow_up_url); } else if (this.followUpUrl) { this.redirectTo(this.followUpUrl); } else if(!hasCallbackFunction) { // only do this option if no redirect or callback supplied alert(I18n.t('petition.excited_confirmation')); } }, redirectTo(url) { window.location.href = url; }, }); module.exports = Petition;
5
0
2
add_only
--- a/app/assets/javascripts/member-facing/backbone/petition.js +++ b/app/assets/javascripts/member-facing/backbone/petition.js @@ -16,2 +16,3 @@ this.submissionCallback = options.submissionCallback; + this.skipOnSuccessAction = options.skipOnSuccessAction; GlobalEvents.bindEvents(this); @@ -20,2 +21,6 @@ handleSuccess(e, data) { + $.publish('petition:submitted'); + if(this.skipOnSuccessAction) { + return; + } let hasCallbackFunction = (typeof this.submissionCallback === 'function');
--- a/app/assets/javascripts/member-facing/backbone/petition.js +++ b/app/assets/javascripts/member-facing/backbone/petition.js @@ ... @@ this.submissionCallback = options.submissionCallback; + this.skipOnSuccessAction = options.skipOnSuccessAction; GlobalEvents.bindEvents(this); @@ ... @@ handleSuccess(e, data) { + $.publish('petition:submitted'); + if(this.skipOnSuccessAction) { + return; + } let hasCallbackFunction = (typeof this.submissionCallback === 'function');
--- a/app/assets/javascripts/member-facing/backbone/petition.js +++ b/app/assets/javascripts/member-facing/backbone/petition.js @@ -16,2 +16,3 @@ CON this.submissionCallback = options.submissionCallback; ADD this.skipOnSuccessAction = options.skipOnSuccessAction; CON GlobalEvents.bindEvents(this); @@ -20,2 +21,6 @@ CON handleSuccess(e, data) { ADD $.publish('petition:submitted'); ADD if(this.skipOnSuccessAction) { ADD return; ADD } CON let hasCallbackFunction = (typeof this.submissionCallback === 'function');
<<<<<<< SEARCH this.followUpUrl = options.followUpUrl; this.submissionCallback = options.submissionCallback; GlobalEvents.bindEvents(this); }, handleSuccess(e, data) { let hasCallbackFunction = (typeof this.submissionCallback === 'function'); if (hasCallbackFunction) { ======= this.followUpUrl = options.followUpUrl; this.submissionCallback = options.submissionCallback; this.skipOnSuccessAction = options.skipOnSuccessAction; GlobalEvents.bindEvents(this); }, handleSuccess(e, data) { $.publish('petition:submitted'); if(this.skipOnSuccessAction) { return; } let hasCallbackFunction = (typeof this.submissionCallback === 'function'); if (hasCallbackFunction) { >>>>>>> REPLACE
agronholm/cbor2
0866695a2f60538d59277f45a69771664d6dee27
setup.py
python
mit
Fix glibc version detect string
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) min_unix_version = not windows and sys.version_info >= (3, 3) if cpython and ((min_unix_version and libc_ok) or min_win_version): _cbor2 = Extension( '_cbor2', # math.h routines are built-in to MSVCRT libraries=['m'] if not windows else [], extra_compile_args=['-std=c99'], sources=[ 'source/module.c', 'source/encoder.c', 'source/decoder.c', 'source/tags.c', 'source/halffloat.c', ] ) kwargs = {'ext_modules': [_cbor2]} else: kwargs = {} setup( use_scm_version={ 'version_scheme': 'post-release', 'local_scheme': 'dirty-tag' }, setup_requires=[ 'setuptools >= 36.2.7', 'setuptools_scm >= 1.7.0' ], **kwargs )
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' if is_glibc: glibc_ver = platform.libc_ver()[1] libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) libc_ok = libc_numeric >= (2, 9) else: libc_ok = False windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) min_unix_version = not windows and sys.version_info >= (3, 3) if cpython and ((min_unix_version and libc_ok) or min_win_version): _cbor2 = Extension( '_cbor2', # math.h routines are built-in to MSVCRT libraries=['m'] if not windows else [], extra_compile_args=['-std=c99'], sources=[ 'source/module.c', 'source/encoder.c', 'source/decoder.c', 'source/tags.c', 'source/halffloat.c', ] ) kwargs = {'ext_modules': [_cbor2]} else: kwargs = {} setup( use_scm_version={ 'version_scheme': 'post-release', 'local_scheme': 'dirty-tag' }, setup_requires=[ 'setuptools >= 36.2.7', 'setuptools_scm >= 1.7.0' ], **kwargs )
6
1
1
mixed
--- a/setup.py +++ b/setup.py @@ -6,3 +6,8 @@ is_glibc = platform.libc_ver()[0] == 'glibc' -libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' +if is_glibc: + glibc_ver = platform.libc_ver()[1] + libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) + libc_ok = libc_numeric >= (2, 9) +else: + libc_ok = False windows = sys.platform.startswith('win')
--- a/setup.py +++ b/setup.py @@ ... @@ is_glibc = platform.libc_ver()[0] == 'glibc' -libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' +if is_glibc: + glibc_ver = platform.libc_ver()[1] + libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) + libc_ok = libc_numeric >= (2, 9) +else: + libc_ok = False windows = sys.platform.startswith('win')
--- a/setup.py +++ b/setup.py @@ -6,3 +6,8 @@ CON is_glibc = platform.libc_ver()[0] == 'glibc' DEL libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' ADD if is_glibc: ADD glibc_ver = platform.libc_ver()[1] ADD libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) ADD libc_ok = libc_numeric >= (2, 9) ADD else: ADD libc_ok = False CON windows = sys.platform.startswith('win')
<<<<<<< SEARCH cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) ======= cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' if is_glibc: glibc_ver = platform.libc_ver()[1] libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) libc_ok = libc_numeric >= (2, 9) else: libc_ok = False windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) >>>>>>> REPLACE
klmitch/cli_tools
0d176d6d40c5267a8672e2f8511eeec3ff7e4102
setup.py
python
apache-2.0
Use install_requires= and bump version It appears that the "requires" keyword argument to setup() doesn't do the right thing. This may be a brain-o on my part. This switches back to using "install_requires" and bumps the version for release.
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='cli_tools', version='0.2.4', author='Kevin L. Mitchell', author_email='[email protected]', url='https://github.com/klmitch/cli_utils', description="Command Line Interface Tools", long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or ' 'later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: User Interfaces', ], py_modules=['cli_tools'], requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), )
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='cli_tools', version='0.2.5', author='Kevin L. Mitchell', author_email='[email protected]', url='https://github.com/klmitch/cli_utils', description="Command Line Interface Tools", long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or ' 'later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: User Interfaces', ], py_modules=['cli_tools'], install_requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), )
2
2
2
mixed
--- a/setup.py +++ b/setup.py @@ -23,3 +23,3 @@ name='cli_tools', - version='0.2.4', + version='0.2.5', author='Kevin L. Mitchell', @@ -43,3 +43,3 @@ py_modules=['cli_tools'], - requires=readreq('requirements.txt'), + install_requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'),
--- a/setup.py +++ b/setup.py @@ ... @@ name='cli_tools', - version='0.2.4', + version='0.2.5', author='Kevin L. Mitchell', @@ ... @@ py_modules=['cli_tools'], - requires=readreq('requirements.txt'), + install_requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'),
--- a/setup.py +++ b/setup.py @@ -23,3 +23,3 @@ CON name='cli_tools', DEL version='0.2.4', ADD version='0.2.5', CON author='Kevin L. Mitchell', @@ -43,3 +43,3 @@ CON py_modules=['cli_tools'], DEL requires=readreq('requirements.txt'), ADD install_requires=readreq('requirements.txt'), CON tests_require=readreq('test-requirements.txt'),
<<<<<<< SEARCH setup( name='cli_tools', version='0.2.4', author='Kevin L. Mitchell', author_email='[email protected]', ======= setup( name='cli_tools', version='0.2.5', author='Kevin L. Mitchell', author_email='[email protected]', >>>>>>> REPLACE <<<<<<< SEARCH ], py_modules=['cli_tools'], requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), ) ======= ], py_modules=['cli_tools'], install_requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), ) >>>>>>> REPLACE
aidancully/rust
bda6d1f158a71efe84d86da2011eac0c45a232c5
compiler/rustc_data_structures/src/memmap.rs
rust
apache-2.0
Add safety comment to StableAddress impl for Mmap
use std::fs::File; use std::io; use std::ops::Deref; use crate::owning_ref::StableAddress; /// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`]. #[cfg(not(target_arch = "wasm32"))] pub struct Mmap(memmap2::Mmap); #[cfg(target_arch = "wasm32")] pub struct Mmap(Vec<u8>); #[cfg(not(target_arch = "wasm32"))] impl Mmap { #[inline] pub unsafe fn map(file: File) -> io::Result<Self> { memmap2::Mmap::map(&file).map(Mmap) } } #[cfg(target_arch = "wasm32")] impl Mmap { #[inline] pub unsafe fn map(mut file: File) -> io::Result<Self> { use std::io::Read; let mut data = Vec::new(); file.read_to_end(&mut data)?; Ok(Mmap(data)) } } impl Deref for Mmap { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { &*self.0 } } unsafe impl StableAddress for Mmap {}
use std::fs::File; use std::io; use std::ops::Deref; use crate::owning_ref::StableAddress; /// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`]. #[cfg(not(target_arch = "wasm32"))] pub struct Mmap(memmap2::Mmap); #[cfg(target_arch = "wasm32")] pub struct Mmap(Vec<u8>); #[cfg(not(target_arch = "wasm32"))] impl Mmap { #[inline] pub unsafe fn map(file: File) -> io::Result<Self> { memmap2::Mmap::map(&file).map(Mmap) } } #[cfg(target_arch = "wasm32")] impl Mmap { #[inline] pub unsafe fn map(mut file: File) -> io::Result<Self> { use std::io::Read; let mut data = Vec::new(); file.read_to_end(&mut data)?; Ok(Mmap(data)) } } impl Deref for Mmap { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { &*self.0 } } // SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this // memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't // export any function that can cause the `Vec` to be re-allocated. As such the address of the // bytes inside this `Vec` is stable. unsafe impl StableAddress for Mmap {}
4
0
1
add_only
--- a/compiler/rustc_data_structures/src/memmap.rs +++ b/compiler/rustc_data_structures/src/memmap.rs @@ -42,2 +42,6 @@ +// SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this +// memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't +// export any function that can cause the `Vec` to be re-allocated. As such the address of the +// bytes inside this `Vec` is stable. unsafe impl StableAddress for Mmap {}
--- a/compiler/rustc_data_structures/src/memmap.rs +++ b/compiler/rustc_data_structures/src/memmap.rs @@ ... @@ +// SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this +// memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't +// export any function that can cause the `Vec` to be re-allocated. As such the address of the +// bytes inside this `Vec` is stable. unsafe impl StableAddress for Mmap {}
--- a/compiler/rustc_data_structures/src/memmap.rs +++ b/compiler/rustc_data_structures/src/memmap.rs @@ -42,2 +42,6 @@ CON ADD // SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this ADD // memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't ADD // export any function that can cause the `Vec` to be re-allocated. As such the address of the ADD // bytes inside this `Vec` is stable. CON unsafe impl StableAddress for Mmap {}
<<<<<<< SEARCH } unsafe impl StableAddress for Mmap {} ======= } // SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this // memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't // export any function that can cause the `Vec` to be re-allocated. As such the address of the // bytes inside this `Vec` is stable. unsafe impl StableAddress for Mmap {} >>>>>>> REPLACE
benmfaul/XRTB
f0ba1a9989ef14955ae014f994d4a444f2b3b0d6
src/com/xrtb/exchanges/Epom.java
java
apache-2.0
Fix epom to not use encoded adm
package com.xrtb.exchanges; import java.io.InputStream; import com.xrtb.pojo.BidRequest; /** * A class to handle Epom ad exchange * @author Ben M. Faul * */ public class Epom extends BidRequest { public Epom() { super(); parseSpecial(); } /** * Make a Epom bid request using a String. * @param in String. The JSON bid request for Epom * @throws Exception on JSON errors. */ public Epom(String in) throws Exception { super(in); parseSpecial(); } /** * Make a Epom bid request using an input stream. * @param in InputStream. The contents of a HTTP post. * @throws Exception on JSON errors. */ public Epom(InputStream in) throws Exception { super(in); parseSpecial(); } /** * Process special Epom stuff, sets the exchange name. */ @Override public boolean parseSpecial() { exchange = "epom"; return true; } }
package com.xrtb.exchanges; import java.io.InputStream; import com.xrtb.pojo.BidRequest; /** * A class to handle Epom ad exchange * @author Ben M. Faul * */ public class Epom extends BidRequest { public Epom() { super(); parseSpecial(); } /** * Make a Epom bid request using a String. * @param in String. The JSON bid request for Epom * @throws Exception on JSON errors. */ public Epom(String in) throws Exception { super(in); parseSpecial(); } /** * Make a Epom bid request using an input stream. * @param in InputStream. The contents of a HTTP post. * @throws Exception on JSON errors. */ public Epom(InputStream in) throws Exception { super(in); parseSpecial(); } /** * Process special Epom stuff, sets the exchange name. */ @Override public boolean parseSpecial() { exchange = "epom"; usesEncodedAdm = false; return true; } }
1
0
1
add_only
--- a/src/com/xrtb/exchanges/Epom.java +++ b/src/com/xrtb/exchanges/Epom.java @@ -44,2 +44,3 @@ exchange = "epom"; + usesEncodedAdm = false; return true;
--- a/src/com/xrtb/exchanges/Epom.java +++ b/src/com/xrtb/exchanges/Epom.java @@ ... @@ exchange = "epom"; + usesEncodedAdm = false; return true;
--- a/src/com/xrtb/exchanges/Epom.java +++ b/src/com/xrtb/exchanges/Epom.java @@ -44,2 +44,3 @@ CON exchange = "epom"; ADD usesEncodedAdm = false; CON return true;
<<<<<<< SEARCH public boolean parseSpecial() { exchange = "epom"; return true; } ======= public boolean parseSpecial() { exchange = "epom"; usesEncodedAdm = false; return true; } >>>>>>> REPLACE
RafaelFazzolino/TecProg
08024fb4324829ac9f56d2d3773b97b9acee1c71
src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java
java
agpl-3.0
Change of variables of Estatisitca
package br.com.MDSGPP.ChamadaParlamentar.model; import java.util.ArrayList; public class Estatistica { private String nome; private String numeroSessao; private String totalSessao; private String porcentagem; private ArrayList<String> lista = new ArrayList<String>(); public Estatistica(){ } public String getNumeroSessao() { return numeroSessao; } public void setNumeroSessao(String numeroSessao) { this.numeroSessao = numeroSessao; } public String getTotalSessao() { return totalSessao; } public void setTotalSessao(String totalSessao) { this.totalSessao = totalSessao; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getPorcentagem() { return porcentagem; } public void setPorcentagem(String porcentagem) { this.porcentagem = porcentagem; } public ArrayList<String> getLista() { return lista; } public void setLista(ArrayList<String> lista) { this.lista = lista; } }
package br.com.MDSGPP.ChamadaParlamentar.model; import java.util.ArrayList; public class Estatistica { private String name; private String numberOfSession; private String totalSessao; private String percentage; private ArrayList<String> lista = new ArrayList<String>(); public Estatistica(){ } public String getNumeroSessao() { return numberOfSession; } public void setNumeroSessao(String numberOfSession) { this.numberOfSession = numberOfSession; } public String getTotalSessao() { return totalSessao; } public void setTotalSessao(String totalSessao) { this.totalSessao = totalSessao; } public String getNome() { return name; } public void setNome(String name) { this.name = name; } public String getPorcentagem() { return percentage; } public void setPorcentagem(String percentage) { this.percentage = percentage; } public ArrayList<String> getLista() { return list; } public void setLista(ArrayList<String> list) { this.list = list; } }
15
15
5
mixed
--- a/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java +++ b/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java @@ -6,6 +6,6 @@ - private String nome; - private String numeroSessao; + private String name; + private String numberOfSession; private String totalSessao; - private String porcentagem; + private String percentage; private ArrayList<String> lista = new ArrayList<String>(); @@ -16,7 +16,7 @@ public String getNumeroSessao() { - return numeroSessao; + return numberOfSession; } - public void setNumeroSessao(String numeroSessao) { - this.numeroSessao = numeroSessao; + public void setNumeroSessao(String numberOfSession) { + this.numberOfSession = numberOfSession; } @@ -32,7 +32,7 @@ public String getNome() { - return nome; + return name; } - public void setNome(String nome) { - this.nome = nome; + public void setNome(String name) { + this.name = name; } @@ -40,7 +40,7 @@ public String getPorcentagem() { - return porcentagem; + return percentage; } - public void setPorcentagem(String porcentagem) { - this.porcentagem = porcentagem; + public void setPorcentagem(String percentage) { + this.percentage = percentage; } @@ -48,7 +48,7 @@ public ArrayList<String> getLista() { - return lista; + return list; } - public void setLista(ArrayList<String> lista) { - this.lista = lista; + public void setLista(ArrayList<String> list) { + this.list = list; }
--- a/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java +++ b/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java @@ ... @@ - private String nome; - private String numeroSessao; + private String name; + private String numberOfSession; private String totalSessao; - private String porcentagem; + private String percentage; private ArrayList<String> lista = new ArrayList<String>(); @@ ... @@ public String getNumeroSessao() { - return numeroSessao; + return numberOfSession; } - public void setNumeroSessao(String numeroSessao) { - this.numeroSessao = numeroSessao; + public void setNumeroSessao(String numberOfSession) { + this.numberOfSession = numberOfSession; } @@ ... @@ public String getNome() { - return nome; + return name; } - public void setNome(String nome) { - this.nome = nome; + public void setNome(String name) { + this.name = name; } @@ ... @@ public String getPorcentagem() { - return porcentagem; + return percentage; } - public void setPorcentagem(String porcentagem) { - this.porcentagem = porcentagem; + public void setPorcentagem(String percentage) { + this.percentage = percentage; } @@ ... @@ public ArrayList<String> getLista() { - return lista; + return list; } - public void setLista(ArrayList<String> lista) { - this.lista = lista; + public void setLista(ArrayList<String> list) { + this.list = list; }
--- a/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java +++ b/src/main/java/br/com/MDSGPP/ChamadaParlamentar/model/Estatistica.java @@ -6,6 +6,6 @@ CON DEL private String nome; DEL private String numeroSessao; ADD private String name; ADD private String numberOfSession; CON private String totalSessao; DEL private String porcentagem; ADD private String percentage; CON private ArrayList<String> lista = new ArrayList<String>(); @@ -16,7 +16,7 @@ CON public String getNumeroSessao() { DEL return numeroSessao; ADD return numberOfSession; CON } CON DEL public void setNumeroSessao(String numeroSessao) { DEL this.numeroSessao = numeroSessao; ADD public void setNumeroSessao(String numberOfSession) { ADD this.numberOfSession = numberOfSession; CON } @@ -32,7 +32,7 @@ CON public String getNome() { DEL return nome; ADD return name; CON } CON DEL public void setNome(String nome) { DEL this.nome = nome; ADD public void setNome(String name) { ADD this.name = name; CON } @@ -40,7 +40,7 @@ CON public String getPorcentagem() { DEL return porcentagem; ADD return percentage; CON } CON DEL public void setPorcentagem(String porcentagem) { DEL this.porcentagem = porcentagem; ADD public void setPorcentagem(String percentage) { ADD this.percentage = percentage; CON } @@ -48,7 +48,7 @@ CON public ArrayList<String> getLista() { DEL return lista; ADD return list; CON } CON DEL public void setLista(ArrayList<String> lista) { DEL this.lista = lista; ADD public void setLista(ArrayList<String> list) { ADD this.list = list; CON }
<<<<<<< SEARCH public class Estatistica { private String nome; private String numeroSessao; private String totalSessao; private String porcentagem; private ArrayList<String> lista = new ArrayList<String>(); ======= public class Estatistica { private String name; private String numberOfSession; private String totalSessao; private String percentage; private ArrayList<String> lista = new ArrayList<String>(); >>>>>>> REPLACE <<<<<<< SEARCH public String getNumeroSessao() { return numeroSessao; } public void setNumeroSessao(String numeroSessao) { this.numeroSessao = numeroSessao; } ======= public String getNumeroSessao() { return numberOfSession; } public void setNumeroSessao(String numberOfSession) { this.numberOfSession = numberOfSession; } >>>>>>> REPLACE <<<<<<< SEARCH public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getPorcentagem() { return porcentagem; } public void setPorcentagem(String porcentagem) { this.porcentagem = porcentagem; } public ArrayList<String> getLista() { return lista; } public void setLista(ArrayList<String> lista) { this.lista = lista; } } ======= public String getNome() { return name; } public void setNome(String name) { this.name = name; } public String getPorcentagem() { return percentage; } public void setPorcentagem(String percentage) { this.percentage = percentage; } public ArrayList<String> getLista() { return list; } public void setLista(ArrayList<String> list) { this.list = list; } } >>>>>>> REPLACE
rhuss/sundrio
28c9307a1fd11487c5487be7184fd73517642d3c
annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java
java
apache-2.0
Fix isBuildable() in buildable repository.
/* * Copyright 2015 The original authors. * * 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.sundr.builder.internal; import javax.lang.model.element.TypeElement; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; public class BuildableRepository { private final Set<TypeElement> buildables = new LinkedHashSet<>(); public void register(TypeElement buildable) { buildables.add(buildable); } public Set<TypeElement> getBuildables() { return Collections.unmodifiableSet(buildables); } public boolean isBuildable(TypeElement buildable) { return buildable != null && buildables.contains(buildable.getQualifiedName().toString()); } public void clear() { buildables.clear(); } }
/* * Copyright 2015 The original authors. * * 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.sundr.builder.internal; import javax.lang.model.element.TypeElement; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; public class BuildableRepository { private final Set<TypeElement> buildables = new LinkedHashSet<>(); public void register(TypeElement buildable) { buildables.add(buildable); } public Set<TypeElement> getBuildables() { return Collections.unmodifiableSet(buildables); } public boolean isBuildable(TypeElement buildable) { return buildable != null && buildables.contains(buildable); } public void clear() { buildables.clear(); } }
1
1
1
mixed
--- a/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java +++ b/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java @@ -36,3 +36,3 @@ public boolean isBuildable(TypeElement buildable) { - return buildable != null && buildables.contains(buildable.getQualifiedName().toString()); + return buildable != null && buildables.contains(buildable); }
--- a/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java +++ b/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java @@ ... @@ public boolean isBuildable(TypeElement buildable) { - return buildable != null && buildables.contains(buildable.getQualifiedName().toString()); + return buildable != null && buildables.contains(buildable); }
--- a/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java +++ b/annotations/src/main/java/io/sundr/builder/internal/BuildableRepository.java @@ -36,3 +36,3 @@ CON public boolean isBuildable(TypeElement buildable) { DEL return buildable != null && buildables.contains(buildable.getQualifiedName().toString()); ADD return buildable != null && buildables.contains(buildable); CON }
<<<<<<< SEARCH public boolean isBuildable(TypeElement buildable) { return buildable != null && buildables.contains(buildable.getQualifiedName().toString()); } ======= public boolean isBuildable(TypeElement buildable) { return buildable != null && buildables.contains(buildable); } >>>>>>> REPLACE
fischmax/redox
20b13666f6792534ca8f95e2b03e3e68d5476bca
filesystem/apps/test/test.rs
rust
mit
Use an array to label all commands and add `ptr_write` command
use std::{io, fs}; macro_rules! readln { () => { { let mut line = String::new(); match io::stdin().read_line(&mut line) { Ok(n) => Some(line.trim().to_string()), Err(e) => None } } }; } fn console_title(title: &str){ } #[no_mangle] pub fn main() { console_title("Test"); println!("Type help for a command list"); while let Some(line) = readln!() { let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect(); if let Some(command) = args.get(0) { println!("# {}", line); match &command[..] { "panic" => panic!("Test panic"), "ls" => { // TODO: when libredox is completed //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } _ => println!("Commands: panic"), } } } }
#![feature(alloc)] #![feature(core)] extern crate alloc; extern crate core; use alloc::boxed::Box; use std::{io, fs, rand}; use core::ptr; macro_rules! readln { () => { { let mut line = String::new(); match io::stdin().read_line(&mut line) { Ok(n) => Some(line.trim().to_string()), Err(e) => None } } }; } fn console_title(title: &str){ } #[no_mangle] pub fn main() { console_title("Test"); println!("Type help for a command list"); while let Some(line) = readln!() { let args: Vec<String> = line.split(' ').map(|arg| arg.to_string()).collect(); if let Some(command) = args.get(0) { println!("# {}", line); let console_commands = ["panic", "ls", "ptr_write"]; match &command[..] { command if command == console_commands[0] => panic!("Test panic"), command if command == console_commands[1] => { // TODO: import std::fs functions into libredox //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } command if command == console_commands[2] => { let a_ptr = rand() as *mut u8; // TODO: import Box::{from_raw, to_raw} methods in libredox //let mut a_box = Box::new(rand() as u8); unsafe { ptr::write(a_ptr, rand() as u8); //ptr::write(a_box.to_raw(), rand() as u8); } } _ => println!("Commands: {}", console_commands.join(" ")), } } } }
23
5
3
mixed
--- a/filesystem/apps/test/test.rs +++ b/filesystem/apps/test/test.rs @@ -1,2 +1,10 @@ -use std::{io, fs}; +#![feature(alloc)] +#![feature(core)] + +extern crate alloc; +extern crate core; + +use alloc::boxed::Box; +use std::{io, fs, rand}; +use core::ptr; @@ -28,2 +36,3 @@ println!("# {}", line); + let console_commands = ["panic", "ls", "ptr_write"]; @@ -31,8 +40,17 @@ { - "panic" => panic!("Test panic"), - "ls" => { - // TODO: when libredox is completed + command if command == console_commands[0] => panic!("Test panic"), + command if command == console_commands[1] => { + // TODO: import std::fs functions into libredox //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } - _ => println!("Commands: panic"), + command if command == console_commands[2] => { + let a_ptr = rand() as *mut u8; + // TODO: import Box::{from_raw, to_raw} methods in libredox + //let mut a_box = Box::new(rand() as u8); + unsafe { + ptr::write(a_ptr, rand() as u8); + //ptr::write(a_box.to_raw(), rand() as u8); + } + } + _ => println!("Commands: {}", console_commands.join(" ")), }
--- a/filesystem/apps/test/test.rs +++ b/filesystem/apps/test/test.rs @@ ... @@ -use std::{io, fs}; +#![feature(alloc)] +#![feature(core)] + +extern crate alloc; +extern crate core; + +use alloc::boxed::Box; +use std::{io, fs, rand}; +use core::ptr; @@ ... @@ println!("# {}", line); + let console_commands = ["panic", "ls", "ptr_write"]; @@ ... @@ { - "panic" => panic!("Test panic"), - "ls" => { - // TODO: when libredox is completed + command if command == console_commands[0] => panic!("Test panic"), + command if command == console_commands[1] => { + // TODO: import std::fs functions into libredox //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } - _ => println!("Commands: panic"), + command if command == console_commands[2] => { + let a_ptr = rand() as *mut u8; + // TODO: import Box::{from_raw, to_raw} methods in libredox + //let mut a_box = Box::new(rand() as u8); + unsafe { + ptr::write(a_ptr, rand() as u8); + //ptr::write(a_box.to_raw(), rand() as u8); + } + } + _ => println!("Commands: {}", console_commands.join(" ")), }
--- a/filesystem/apps/test/test.rs +++ b/filesystem/apps/test/test.rs @@ -1,2 +1,10 @@ DEL use std::{io, fs}; ADD #![feature(alloc)] ADD #![feature(core)] ADD ADD extern crate alloc; ADD extern crate core; ADD ADD use alloc::boxed::Box; ADD use std::{io, fs, rand}; ADD use core::ptr; CON @@ -28,2 +36,3 @@ CON println!("# {}", line); ADD let console_commands = ["panic", "ls", "ptr_write"]; CON @@ -31,8 +40,17 @@ CON { DEL "panic" => panic!("Test panic"), DEL "ls" => { DEL // TODO: when libredox is completed ADD command if command == console_commands[0] => panic!("Test panic"), ADD command if command == console_commands[1] => { ADD // TODO: import std::fs functions into libredox CON //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); CON } DEL _ => println!("Commands: panic"), ADD command if command == console_commands[2] => { ADD let a_ptr = rand() as *mut u8; ADD // TODO: import Box::{from_raw, to_raw} methods in libredox ADD //let mut a_box = Box::new(rand() as u8); ADD unsafe { ADD ptr::write(a_ptr, rand() as u8); ADD //ptr::write(a_box.to_raw(), rand() as u8); ADD } ADD } ADD _ => println!("Commands: {}", console_commands.join(" ")), CON }
<<<<<<< SEARCH use std::{io, fs}; macro_rules! readln { ======= #![feature(alloc)] #![feature(core)] extern crate alloc; extern crate core; use alloc::boxed::Box; use std::{io, fs, rand}; use core::ptr; macro_rules! readln { >>>>>>> REPLACE <<<<<<< SEARCH if let Some(command) = args.get(0) { println!("# {}", line); match &command[..] { "panic" => panic!("Test panic"), "ls" => { // TODO: when libredox is completed //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } _ => println!("Commands: panic"), } } ======= if let Some(command) = args.get(0) { println!("# {}", line); let console_commands = ["panic", "ls", "ptr_write"]; match &command[..] { command if command == console_commands[0] => panic!("Test panic"), command if command == console_commands[1] => { // TODO: import std::fs functions into libredox //fs::read_dir("/").unwrap().map(|dir| println!("{}", dir)); } command if command == console_commands[2] => { let a_ptr = rand() as *mut u8; // TODO: import Box::{from_raw, to_raw} methods in libredox //let mut a_box = Box::new(rand() as u8); unsafe { ptr::write(a_ptr, rand() as u8); //ptr::write(a_box.to_raw(), rand() as u8); } } _ => println!("Commands: {}", console_commands.join(" ")), } } >>>>>>> REPLACE
joaander/hoomd-blue
3bddeade05ca5ddc799733baa1545aa2b8b68060
hoomd/tune/custom_tuner.py
python
bsd-3-clause
Fix attaching on custom tuners
from hoomd import _hoomd from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def updater(self): return self._action @updater.setter def updater(self, updater): if isinstance(updater, Action): self._action = updater else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) super().attach(simulation) self._action.attach(simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner'
from hoomd import _hoomd from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def tuner(self): return self._action @tuner.setter def tuner(self, tuner): if isinstance(tuner, Action): self._action = tuner else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation)
13
6
4
mixed
--- a/hoomd/tune/custom_tuner.py +++ b/hoomd/tune/custom_tuner.py @@ -1,2 +1,3 @@ from hoomd import _hoomd +from hoomd.operation import _Operation from hoomd.custom import ( @@ -8,9 +9,9 @@ @property - def updater(self): + def tuner(self): return self._action - @updater.setter - def updater(self, updater): - if isinstance(updater, Action): - self._action = updater + @tuner.setter + def tuner(self, tuner): + if isinstance(tuner, Action): + self._action = tuner else: @@ -31,4 +32,4 @@ simulation.state._cpp_sys_def, self.trigger, self._action) - super().attach(simulation) self._action.attach(simulation) + _Operation.attach(self, simulation) @@ -39 +40,7 @@ _cpp_class_name = 'PythonTuner' + + def attach(self, simulation): + self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( + simulation.state._cpp_sys_def, self.trigger, self._action) + self._action.attach(simulation) + _Operation.attach(self, simulation)
--- a/hoomd/tune/custom_tuner.py +++ b/hoomd/tune/custom_tuner.py @@ ... @@ from hoomd import _hoomd +from hoomd.operation import _Operation from hoomd.custom import ( @@ ... @@ @property - def updater(self): + def tuner(self): return self._action - @updater.setter - def updater(self, updater): - if isinstance(updater, Action): - self._action = updater + @tuner.setter + def tuner(self, tuner): + if isinstance(tuner, Action): + self._action = tuner else: @@ ... @@ simulation.state._cpp_sys_def, self.trigger, self._action) - super().attach(simulation) self._action.attach(simulation) + _Operation.attach(self, simulation) @@ ... @@ _cpp_class_name = 'PythonTuner' + + def attach(self, simulation): + self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( + simulation.state._cpp_sys_def, self.trigger, self._action) + self._action.attach(simulation) + _Operation.attach(self, simulation)
--- a/hoomd/tune/custom_tuner.py +++ b/hoomd/tune/custom_tuner.py @@ -1,2 +1,3 @@ CON from hoomd import _hoomd ADD from hoomd.operation import _Operation CON from hoomd.custom import ( @@ -8,9 +9,9 @@ CON @property DEL def updater(self): ADD def tuner(self): CON return self._action CON DEL @updater.setter DEL def updater(self, updater): DEL if isinstance(updater, Action): DEL self._action = updater ADD @tuner.setter ADD def tuner(self, tuner): ADD if isinstance(tuner, Action): ADD self._action = tuner CON else: @@ -31,4 +32,4 @@ CON simulation.state._cpp_sys_def, self.trigger, self._action) DEL super().attach(simulation) CON self._action.attach(simulation) ADD _Operation.attach(self, simulation) CON @@ -39 +40,7 @@ CON _cpp_class_name = 'PythonTuner' ADD ADD def attach(self, simulation): ADD self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( ADD simulation.state._cpp_sys_def, self.trigger, self._action) ADD self._action.attach(simulation) ADD _Operation.attach(self, simulation)
<<<<<<< SEARCH from hoomd import _hoomd from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) ======= from hoomd import _hoomd from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) >>>>>>> REPLACE <<<<<<< SEARCH class _TunerProperty: @property def updater(self): return self._action @updater.setter def updater(self, updater): if isinstance(updater, Action): self._action = updater else: raise ValueError( ======= class _TunerProperty: @property def tuner(self): return self._action @tuner.setter def tuner(self, tuner): if isinstance(tuner, Action): self._action = tuner else: raise ValueError( >>>>>>> REPLACE <<<<<<< SEARCH self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) super().attach(simulation) self._action.attach(simulation) ======= self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) >>>>>>> REPLACE <<<<<<< SEARCH _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' ======= _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) >>>>>>> REPLACE
jpace121/RustRestrictedIntegers
e905a9240a320bda7b72c6485e35b41baeedbb5e
src/lib.rs
rust
apache-2.0
Switch to using a struct. Use ugly hack.
use std::ops::{Add, Sub}; #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum LimitVal { Val(u8) } impl Add for LimitVal { type Output = LimitVal; fn add(self, other: LimitVal) -> LimitVal { let val1 = match self { LimitVal::Val(x) => x, }; let val2 = match other { LimitVal::Val(x) => x, }; LimitVal::Val(val1+val2) } } #[cfg(test)] mod tests { /* Can always put in own file, then would need: extern crate adder; (or whatever) and then namespace:: the functions. */ use super::*; #[test] fn test_add() { let x: LimitVal = LimitVal::Val(1); let y = LimitVal::Val(2); let z = x + y; assert_eq!(z,LimitVal::Val(3)); } }
use std::ops::{Add, Sub}; #[derive(Debug,PartialEq,Eq)] pub struct LimitVal { Val : u8, Max : u8, Min : u8, //Fix : Fn(u8) -> u8 //This caused wierd issues, ignore for now. } impl Add for LimitVal { type Output = LimitVal; fn add(self, other: LimitVal) -> LimitVal { let mut result: LimitVal = LimitVal{Val: 0, Max: 0, Min: 0}; //hack result.Val = self.Val + other.Val; result.Max = if(self.Max > other.Max){ other.Max // choose the smallest one }else{ self.Max }; result.Min = if(self.Min > other.Min){ self.Min // choose the biggest one }else{ other.Min }; result } } #[cfg(test)] mod tests { /* Can always put in own file, then would need: extern crate adder; (or whatever) and then namespace:: the functions. */ use super::*; #[test] fn test_add() { let mut x: LimitVal = LimitVal{Val: 2, Max: 10, Min: 0}; let mut y: LimitVal = LimitVal{Val: 3, Max: 10, Min: 0}; let z = x + y; assert_eq!(z.Val,5); } }
23
16
3
mixed
--- a/src/lib.rs +++ b/src/lib.rs @@ -2,5 +2,8 @@ -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub enum LimitVal { - Val(u8) +#[derive(Debug,PartialEq,Eq)] +pub struct LimitVal { + Val : u8, + Max : u8, + Min : u8, + //Fix : Fn(u8) -> u8 //This caused wierd issues, ignore for now. } @@ -12,12 +15,15 @@ fn add(self, other: LimitVal) -> LimitVal { - let val1 = match self { - LimitVal::Val(x) => x, - }; - - let val2 = match other { - LimitVal::Val(x) => x, - }; - - LimitVal::Val(val1+val2) - + let mut result: LimitVal = LimitVal{Val: 0, Max: 0, Min: 0}; //hack + result.Val = self.Val + other.Val; + result.Max = if(self.Max > other.Max){ + other.Max // choose the smallest one + }else{ + self.Max + }; + result.Min = if(self.Min > other.Min){ + self.Min // choose the biggest one + }else{ + other.Min + }; + result } @@ -36,6 +42,7 @@ fn test_add() { - let x: LimitVal = LimitVal::Val(1); - let y = LimitVal::Val(2); + let mut x: LimitVal = LimitVal{Val: 2, Max: 10, Min: 0}; + let mut y: LimitVal = LimitVal{Val: 3, Max: 10, Min: 0}; + let z = x + y; - assert_eq!(z,LimitVal::Val(3)); + assert_eq!(z.Val,5); }
--- a/src/lib.rs +++ b/src/lib.rs @@ ... @@ -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub enum LimitVal { - Val(u8) +#[derive(Debug,PartialEq,Eq)] +pub struct LimitVal { + Val : u8, + Max : u8, + Min : u8, + //Fix : Fn(u8) -> u8 //This caused wierd issues, ignore for now. } @@ ... @@ fn add(self, other: LimitVal) -> LimitVal { - let val1 = match self { - LimitVal::Val(x) => x, - }; - - let val2 = match other { - LimitVal::Val(x) => x, - }; - - LimitVal::Val(val1+val2) - + let mut result: LimitVal = LimitVal{Val: 0, Max: 0, Min: 0}; //hack + result.Val = self.Val + other.Val; + result.Max = if(self.Max > other.Max){ + other.Max // choose the smallest one + }else{ + self.Max + }; + result.Min = if(self.Min > other.Min){ + self.Min // choose the biggest one + }else{ + other.Min + }; + result } @@ ... @@ fn test_add() { - let x: LimitVal = LimitVal::Val(1); - let y = LimitVal::Val(2); + let mut x: LimitVal = LimitVal{Val: 2, Max: 10, Min: 0}; + let mut y: LimitVal = LimitVal{Val: 3, Max: 10, Min: 0}; + let z = x + y; - assert_eq!(z,LimitVal::Val(3)); + assert_eq!(z.Val,5); }
--- a/src/lib.rs +++ b/src/lib.rs @@ -2,5 +2,8 @@ CON DEL #[derive(Debug,Copy,Clone,PartialEq,Eq)] DEL pub enum LimitVal { DEL Val(u8) ADD #[derive(Debug,PartialEq,Eq)] ADD pub struct LimitVal { ADD Val : u8, ADD Max : u8, ADD Min : u8, ADD //Fix : Fn(u8) -> u8 //This caused wierd issues, ignore for now. CON } @@ -12,12 +15,15 @@ CON fn add(self, other: LimitVal) -> LimitVal { DEL let val1 = match self { DEL LimitVal::Val(x) => x, DEL }; DEL DEL let val2 = match other { DEL LimitVal::Val(x) => x, DEL }; DEL DEL LimitVal::Val(val1+val2) DEL ADD let mut result: LimitVal = LimitVal{Val: 0, Max: 0, Min: 0}; //hack ADD result.Val = self.Val + other.Val; ADD result.Max = if(self.Max > other.Max){ ADD other.Max // choose the smallest one ADD }else{ ADD self.Max ADD }; ADD result.Min = if(self.Min > other.Min){ ADD self.Min // choose the biggest one ADD }else{ ADD other.Min ADD }; ADD result CON } @@ -36,6 +42,7 @@ CON fn test_add() { DEL let x: LimitVal = LimitVal::Val(1); DEL let y = LimitVal::Val(2); ADD let mut x: LimitVal = LimitVal{Val: 2, Max: 10, Min: 0}; ADD let mut y: LimitVal = LimitVal{Val: 3, Max: 10, Min: 0}; ADD CON let z = x + y; DEL assert_eq!(z,LimitVal::Val(3)); ADD assert_eq!(z.Val,5); CON }
<<<<<<< SEARCH use std::ops::{Add, Sub}; #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum LimitVal { Val(u8) } ======= use std::ops::{Add, Sub}; #[derive(Debug,PartialEq,Eq)] pub struct LimitVal { Val : u8, Max : u8, Min : u8, //Fix : Fn(u8) -> u8 //This caused wierd issues, ignore for now. } >>>>>>> REPLACE <<<<<<< SEARCH fn add(self, other: LimitVal) -> LimitVal { let val1 = match self { LimitVal::Val(x) => x, }; let val2 = match other { LimitVal::Val(x) => x, }; LimitVal::Val(val1+val2) } } ======= fn add(self, other: LimitVal) -> LimitVal { let mut result: LimitVal = LimitVal{Val: 0, Max: 0, Min: 0}; //hack result.Val = self.Val + other.Val; result.Max = if(self.Max > other.Max){ other.Max // choose the smallest one }else{ self.Max }; result.Min = if(self.Min > other.Min){ self.Min // choose the biggest one }else{ other.Min }; result } } >>>>>>> REPLACE <<<<<<< SEARCH #[test] fn test_add() { let x: LimitVal = LimitVal::Val(1); let y = LimitVal::Val(2); let z = x + y; assert_eq!(z,LimitVal::Val(3)); } } ======= #[test] fn test_add() { let mut x: LimitVal = LimitVal{Val: 2, Max: 10, Min: 0}; let mut y: LimitVal = LimitVal{Val: 3, Max: 10, Min: 0}; let z = x + y; assert_eq!(z.Val,5); } } >>>>>>> REPLACE
quis/quis.cc
a6fdca45fc7da9262aee33176e764e76400e1e00
source/themes/quis/gulpfile.js
javascript
mit
Set up watch task in Gulp
var gulp = require('gulp'), plugins = require('gulp-load-plugins')(); gulp.task('sass', () => gulp .src('css/quis.scss') .pipe(plugins.sass({ outputStyle: 'compressed' })) .pipe(gulp.dest('css/')) ); gulp.task('js', () => gulp .src([ 'js/constants.js', 'js/rateLimit.js', 'js/scrollPages.js', 'js/scrollPhotos.js', 'js/jquery.infinitescroll.js', 'js/jquery.viewportSelector.js', 'js/map.js', 'js/init.js', ]) .pipe(plugins.uglify({ outputStyle: 'compressed' })) .pipe(plugins.concat('quis.js')) .pipe(gulp.dest('js/')) ); gulp.task('default', ['sass', 'js'] );
var gulp = require('gulp'), plugins = require('gulp-load-plugins')(); gulp.task('sass', () => gulp .src('css/quis.scss') .pipe(plugins.sass({ outputStyle: 'compressed' })) .pipe(gulp.dest('css/')) ); gulp.task('js', () => gulp .src([ 'js/constants.js', 'js/rateLimit.js', 'js/scrollPages.js', 'js/scrollPhotos.js', 'js/jquery.infinitescroll.js', 'js/jquery.viewportSelector.js', 'js/map.js', 'js/init.js', ]) .pipe(plugins.uglify({ outputStyle: 'compressed' })) .pipe(plugins.concat('quis.js')) .pipe(gulp.dest('js/')) ); gulp.task('watchForChanges', function() { gulp.watch('js/**/*', ['js']); gulp.watch('css/**/*', ['sass']); }); gulp.task('build', ['sass', 'js'] ); gulp.task('default', ['build', 'watchForChanges'] );
10
1
1
mixed
--- a/source/themes/quis/gulpfile.js +++ b/source/themes/quis/gulpfile.js @@ -29,4 +29,13 @@ -gulp.task('default', +gulp.task('watchForChanges', function() { + gulp.watch('js/**/*', ['js']); + gulp.watch('css/**/*', ['sass']); +}); + +gulp.task('build', ['sass', 'js'] ); + +gulp.task('default', + ['build', 'watchForChanges'] +);
--- a/source/themes/quis/gulpfile.js +++ b/source/themes/quis/gulpfile.js @@ ... @@ -gulp.task('default', +gulp.task('watchForChanges', function() { + gulp.watch('js/**/*', ['js']); + gulp.watch('css/**/*', ['sass']); +}); + +gulp.task('build', ['sass', 'js'] ); + +gulp.task('default', + ['build', 'watchForChanges'] +);
--- a/source/themes/quis/gulpfile.js +++ b/source/themes/quis/gulpfile.js @@ -29,4 +29,13 @@ CON DEL gulp.task('default', ADD gulp.task('watchForChanges', function() { ADD gulp.watch('js/**/*', ['js']); ADD gulp.watch('css/**/*', ['sass']); ADD }); ADD ADD gulp.task('build', CON ['sass', 'js'] CON ); ADD ADD gulp.task('default', ADD ['build', 'watchForChanges'] ADD );
<<<<<<< SEARCH ); gulp.task('default', ['sass', 'js'] ); ======= ); gulp.task('watchForChanges', function() { gulp.watch('js/**/*', ['js']); gulp.watch('css/**/*', ['sass']); }); gulp.task('build', ['sass', 'js'] ); gulp.task('default', ['build', 'watchForChanges'] ); >>>>>>> REPLACE
Sylius/SyliusUiBundle
14b0f6f7d1b0ee4a33957a2bf569b5d56b260253
Resources/private/js/app.js
javascript
mit
[Admin] Improve the shipment ship form
(function($) { $.fn.extend({ requireConfirmation: function() { return this.each(function() { return $(this).on('click', function(event) { event.preventDefault(); var actionButton = $(this); if (actionButton.is('a')) { $('#confirmation-button').attr('href', actionButton.attr('href')); } if (actionButton.is('button')) { $('#confirmation-button').on('click', function(event) { event.preventDefault(); return actionButton.closest('form').submit(); }); } return $('#confirmation-modal').modal('show'); }); }); } }); $(document).ready(function() { $('#sidebar') .first() .sidebar('attach events', '#sidebar-toggle', 'show') ; $('.ui.checkbox').checkbox(); $('.ui.accordion').accordion(); $('.link.ui.dropdown').dropdown({action: 'hide'}); $('.button.ui.dropdown').dropdown({action: 'hide'}); $('.menu .item').tab(); $('.form button').on('click', function() { return $(this).closest('form').addClass('loading'); }); $('.message .close').on('click', function() { return $(this).closest('.message').transition('fade'); }); $('.loadable.button').on('click', function() { return $(this).addClass('loading'); }); $('[data-requires-confirmation]').requireConfirmation(); $('.special.cards .image').dimmer({ on: 'hover' }); }); })(jQuery);
(function($) { $.fn.extend({ requireConfirmation: function() { return this.each(function() { return $(this).on('click', function(event) { event.preventDefault(); var actionButton = $(this); if (actionButton.is('a')) { $('#confirmation-button').attr('href', actionButton.attr('href')); } if (actionButton.is('button')) { $('#confirmation-button').on('click', function(event) { event.preventDefault(); return actionButton.closest('form').submit(); }); } return $('#confirmation-modal').modal('show'); }); }); } }); $(document).ready(function() { $('#sidebar') .first() .sidebar('attach events', '#sidebar-toggle', 'show') ; $('.ui.checkbox').checkbox(); $('.ui.accordion').accordion(); $('.link.ui.dropdown').dropdown({action: 'hide'}); $('.button.ui.dropdown').dropdown({action: 'hide'}); $('.menu .item').tab(); $('.form button').on('click', function() { return $(this).closest('form').addClass('loading'); }); $('.message .close').on('click', function() { return $(this).closest('.message').transition('fade'); }); $('.loadable.button').on('click', function() { return $(this).addClass('loading'); }); $('.popups').popup(); $('[data-requires-confirmation]').requireConfirmation(); $('.special.cards .image').dimmer({ on: 'hover' }); }); })(jQuery);
1
0
1
add_only
--- a/Resources/private/js/app.js +++ b/Resources/private/js/app.js @@ -47,2 +47,3 @@ }); + $('.popups').popup();
--- a/Resources/private/js/app.js +++ b/Resources/private/js/app.js @@ ... @@ }); + $('.popups').popup();
--- a/Resources/private/js/app.js +++ b/Resources/private/js/app.js @@ -47,2 +47,3 @@ CON }); ADD $('.popups').popup(); CON
<<<<<<< SEARCH return $(this).addClass('loading'); }); $('[data-requires-confirmation]').requireConfirmation(); ======= return $(this).addClass('loading'); }); $('.popups').popup(); $('[data-requires-confirmation]').requireConfirmation(); >>>>>>> REPLACE
andstatus/andstatus
8561ec3223f91aaad4f46f02a2b25812d4063ec2
app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt
kotlin
apache-2.0
Extend logging of error, related to android.media.MediaMetadataRetriever.MediaMetadataRetriever (occurs at Travis-ci)
/* * Copyright (c) 2020 yvolk (Yuri Volkov), http://yurivolkov.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.andstatus.app.graphics import org.andstatus.app.context.DemoData import org.andstatus.app.context.TestSuite import org.andstatus.app.graphics.MediaMetadata import org.junit.Assert import org.junit.Before import org.junit.Test class MediaMetadataTest { @Before fun setUp() { TestSuite.initialize(this) } @Test fun testFromFilePath() { val path = DemoData.demoData.localVideoTestUri.toString() MediaMetadata.Companion.fromFilePath(path).let { Assert.assertEquals("For path '$path' returned: $it", 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong() ) } } }
/* * Copyright (c) 2020 yvolk (Yuri Volkov), http://yurivolkov.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.andstatus.app.graphics import org.andstatus.app.context.DemoData import org.andstatus.app.context.TestSuite import org.andstatus.app.util.MyLog import org.junit.Assert import org.junit.Before import org.junit.Test class MediaMetadataTest { @Before fun setUp() { TestSuite.initialize(this) } @Test fun testFromFilePath() { val path = DemoData.demoData.localVideoTestUri.toString() MediaMetadata.Companion.fromFilePath(path).let { Assert.assertEquals( "For path '$path' returned: $it" + (if (it.isFailure) "\n" + MyLog.getStackTrace(it.cause) else ""), 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong() ) } } }
4
2
2
mixed
--- a/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt +++ b/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt @@ -19,3 +19,3 @@ import org.andstatus.app.context.TestSuite -import org.andstatus.app.graphics.MediaMetadata +import org.andstatus.app.util.MyLog import org.junit.Assert @@ -34,3 +34,5 @@ MediaMetadata.Companion.fromFilePath(path).let { - Assert.assertEquals("For path '$path' returned: $it", + Assert.assertEquals( + "For path '$path' returned: $it" + + (if (it.isFailure) "\n" + MyLog.getStackTrace(it.cause) else ""), 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong()
--- a/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt +++ b/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt @@ ... @@ import org.andstatus.app.context.TestSuite -import org.andstatus.app.graphics.MediaMetadata +import org.andstatus.app.util.MyLog import org.junit.Assert @@ ... @@ MediaMetadata.Companion.fromFilePath(path).let { - Assert.assertEquals("For path '$path' returned: $it", + Assert.assertEquals( + "For path '$path' returned: $it" + + (if (it.isFailure) "\n" + MyLog.getStackTrace(it.cause) else ""), 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong()
--- a/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt +++ b/app/src/androidTest/kotlin/org/andstatus/app/graphics/MediaMetadataTest.kt @@ -19,3 +19,3 @@ CON import org.andstatus.app.context.TestSuite DEL import org.andstatus.app.graphics.MediaMetadata ADD import org.andstatus.app.util.MyLog CON import org.junit.Assert @@ -34,3 +34,5 @@ CON MediaMetadata.Companion.fromFilePath(path).let { DEL Assert.assertEquals("For path '$path' returned: $it", ADD Assert.assertEquals( ADD "For path '$path' returned: $it" + ADD (if (it.isFailure) "\n" + MyLog.getStackTrace(it.cause) else ""), CON 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong()
<<<<<<< SEARCH import org.andstatus.app.context.DemoData import org.andstatus.app.context.TestSuite import org.andstatus.app.graphics.MediaMetadata import org.junit.Assert import org.junit.Before ======= import org.andstatus.app.context.DemoData import org.andstatus.app.context.TestSuite import org.andstatus.app.util.MyLog import org.junit.Assert import org.junit.Before >>>>>>> REPLACE <<<<<<< SEARCH val path = DemoData.demoData.localVideoTestUri.toString() MediaMetadata.Companion.fromFilePath(path).let { Assert.assertEquals("For path '$path' returned: $it", 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong() ) ======= val path = DemoData.demoData.localVideoTestUri.toString() MediaMetadata.Companion.fromFilePath(path).let { Assert.assertEquals( "For path '$path' returned: $it" + (if (it.isFailure) "\n" + MyLog.getStackTrace(it.cause) else ""), 180, it.getOrElse(MediaMetadata.EMPTY).height.toLong() ) >>>>>>> REPLACE
edx/edx-app-android
c857c531c5473ae9920c1f0308c29ac327ced0ea
OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java
java
apache-2.0
Fix 'onRevisit' callback calls wrongly issue. - LEARNER-3953
package org.edx.mobile.base; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.edx.mobile.event.NewRelicEvent; import de.greenrobot.event.EventBus; import roboguice.fragment.RoboFragment; public class BaseFragment extends RoboFragment { private boolean isFirstVisit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { isFirstVisit = true; return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onResume() { super.onResume(); if (isFirstVisit) { isFirstVisit = false; } else { onRevisit(); } } /** * Called when a Fragment is re-displayed to the user (the user has navigated back to it). * Defined to mock the behavior of {@link Activity#onRestart() Activity.onRestart} function. */ protected void onRevisit() { } }
package org.edx.mobile.base; import android.app.Activity; import android.os.Bundle; import org.edx.mobile.event.NewRelicEvent; import de.greenrobot.event.EventBus; import roboguice.fragment.RoboFragment; public class BaseFragment extends RoboFragment { private boolean isFirstVisit = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } @Override public void onResume() { super.onResume(); if (isFirstVisit) { isFirstVisit = false; } else { onRevisit(); } } /** * Called when a Fragment is re-displayed to the user (the user has navigated back to it). * Defined to mock the behavior of {@link Activity#onRestart() Activity.onRestart} function. */ protected void onRevisit() { } }
1
12
3
mixed
--- a/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java +++ b/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java @@ -4,6 +4,2 @@ import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; @@ -15,3 +11,3 @@ public class BaseFragment extends RoboFragment { - private boolean isFirstVisit; + private boolean isFirstVisit = true; @@ -21,9 +17,2 @@ EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - isFirstVisit = true; - return super.onCreateView(inflater, container, savedInstanceState); }
--- a/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java +++ b/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java @@ ... @@ import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; @@ ... @@ public class BaseFragment extends RoboFragment { - private boolean isFirstVisit; + private boolean isFirstVisit = true; @@ ... @@ EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - isFirstVisit = true; - return super.onCreateView(inflater, container, savedInstanceState); }
--- a/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java +++ b/OpenEdXMobile/src/main/java/org/edx/mobile/base/BaseFragment.java @@ -4,6 +4,2 @@ CON import android.os.Bundle; DEL import android.support.annotation.Nullable; DEL import android.view.LayoutInflater; DEL import android.view.View; DEL import android.view.ViewGroup; CON @@ -15,3 +11,3 @@ CON public class BaseFragment extends RoboFragment { DEL private boolean isFirstVisit; ADD private boolean isFirstVisit = true; CON @@ -21,9 +17,2 @@ CON EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); DEL } DEL DEL @Nullable DEL @Override DEL public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { DEL isFirstVisit = true; DEL return super.onCreateView(inflater, container, savedInstanceState); CON }
<<<<<<< SEARCH import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.edx.mobile.event.NewRelicEvent; ======= import android.app.Activity; import android.os.Bundle; import org.edx.mobile.event.NewRelicEvent; >>>>>>> REPLACE <<<<<<< SEARCH public class BaseFragment extends RoboFragment { private boolean isFirstVisit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { isFirstVisit = true; return super.onCreateView(inflater, container, savedInstanceState); } ======= public class BaseFragment extends RoboFragment { private boolean isFirstVisit = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().post(new NewRelicEvent(getClass().getSimpleName())); } >>>>>>> REPLACE
ruhan1/indy
7a3dd0b68b49c57e6b02f265d4dc1b07464a4c19
subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java
java
apache-2.0
Fix a wrong line problem This problem will cause compilation error when after license header formatting, which is caused by the package line removed.
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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 javax.enterprise.context.ApplicationScoped; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @ApplicationScoped public class SlashTolerationFilter implements Filter { @Override public void init( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletRequest hsr = (HttpServletRequest) servletRequest; String newURI = hsr.getRequestURI().replaceAll( "/+", "/" ); servletRequest.getRequestDispatcher(newURI).forward(servletRequest, servletResponse); } @Override public void destroy() { } }
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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.commonjava.indy.bind.jaxrs; import javax.enterprise.context.ApplicationScoped; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @ApplicationScoped public class SlashTolerationFilter implements Filter { @Override public void init( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletRequest hsr = (HttpServletRequest) servletRequest; String newURI = hsr.getRequestURI().replaceAll( "/+", "/" ); servletRequest.getRequestDispatcher(newURI).forward(servletRequest, servletResponse); } @Override public void destroy() { } }
2
0
1
add_only
--- a/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java +++ b/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java @@ -15,2 +15,4 @@ */ +package org.commonjava.indy.bind.jaxrs; + import javax.enterprise.context.ApplicationScoped;
--- a/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java +++ b/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java @@ ... @@ */ +package org.commonjava.indy.bind.jaxrs; + import javax.enterprise.context.ApplicationScoped;
--- a/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java +++ b/subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java @@ -15,2 +15,4 @@ CON */ ADD package org.commonjava.indy.bind.jaxrs; ADD CON import javax.enterprise.context.ApplicationScoped;
<<<<<<< SEARCH * limitations under the License. */ import javax.enterprise.context.ApplicationScoped; import javax.servlet.*; ======= * limitations under the License. */ package org.commonjava.indy.bind.jaxrs; import javax.enterprise.context.ApplicationScoped; import javax.servlet.*; >>>>>>> REPLACE
vespa-engine/vespa
79fc46bf80ef3538ec46587e21089cbda288f875
vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java
java
apache-2.0
Read policy from resource name
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.athenz.client.zms.bindings; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * @author olaa */ @JsonIgnoreProperties(ignoreUnknown = true) public class PolicyEntity { @JsonInclude(JsonInclude.Include.NON_EMPTY) private final List<AssertionEntity> assertions; private final String name; public PolicyEntity(@JsonProperty("name") String name, @JsonProperty("assertions") List<AssertionEntity> assertions) { this.name = name; this.assertions = assertions; } public String getName() { return name; } public List<AssertionEntity> getAssertions() { return assertions; } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.athenz.client.zms.bindings; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author olaa */ @JsonIgnoreProperties(ignoreUnknown = true) public class PolicyEntity { private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$"); @JsonInclude(JsonInclude.Include.NON_EMPTY) private final List<AssertionEntity> assertions; private final String name; public PolicyEntity(@JsonProperty("name") String name, @JsonProperty("assertions") List<AssertionEntity> assertions) { this.name = nameFromResourceString(name); this.assertions = assertions; } private static String nameFromResourceString(String resource) { Matcher matcher = namePattern.matcher(resource); if (!matcher.matches()) throw new IllegalArgumentException("Could not find policy name from resource string: " + resource); return matcher.group("name"); } public String getName() { return name; } public List<AssertionEntity> getAssertions() { return assertions; } }
11
1
3
mixed
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java @@ -8,2 +8,4 @@ import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @@ -14,2 +16,3 @@ public class PolicyEntity { + private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$"); @@ -21,4 +24,11 @@ @JsonProperty("assertions") List<AssertionEntity> assertions) { - this.name = name; + this.name = nameFromResourceString(name); this.assertions = assertions; + } + + private static String nameFromResourceString(String resource) { + Matcher matcher = namePattern.matcher(resource); + if (!matcher.matches()) + throw new IllegalArgumentException("Could not find policy name from resource string: " + resource); + return matcher.group("name"); }
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java @@ ... @@ import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @@ ... @@ public class PolicyEntity { + private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$"); @@ ... @@ @JsonProperty("assertions") List<AssertionEntity> assertions) { - this.name = name; + this.name = nameFromResourceString(name); this.assertions = assertions; + } + + private static String nameFromResourceString(String resource) { + Matcher matcher = namePattern.matcher(resource); + if (!matcher.matches()) + throw new IllegalArgumentException("Could not find policy name from resource string: " + resource); + return matcher.group("name"); }
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/PolicyEntity.java @@ -8,2 +8,4 @@ CON import java.util.List; ADD import java.util.regex.Matcher; ADD import java.util.regex.Pattern; CON @@ -14,2 +16,3 @@ CON public class PolicyEntity { ADD private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$"); CON @@ -21,4 +24,11 @@ CON @JsonProperty("assertions") List<AssertionEntity> assertions) { DEL this.name = name; ADD this.name = nameFromResourceString(name); CON this.assertions = assertions; ADD } ADD ADD private static String nameFromResourceString(String resource) { ADD Matcher matcher = namePattern.matcher(resource); ADD if (!matcher.matches()) ADD throw new IllegalArgumentException("Could not find policy name from resource string: " + resource); ADD return matcher.group("name"); CON }
<<<<<<< SEARCH import java.util.List; /** ======= import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** >>>>>>> REPLACE <<<<<<< SEARCH @JsonIgnoreProperties(ignoreUnknown = true) public class PolicyEntity { @JsonInclude(JsonInclude.Include.NON_EMPTY) ======= @JsonIgnoreProperties(ignoreUnknown = true) public class PolicyEntity { private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$"); @JsonInclude(JsonInclude.Include.NON_EMPTY) >>>>>>> REPLACE <<<<<<< SEARCH public PolicyEntity(@JsonProperty("name") String name, @JsonProperty("assertions") List<AssertionEntity> assertions) { this.name = name; this.assertions = assertions; } ======= public PolicyEntity(@JsonProperty("name") String name, @JsonProperty("assertions") List<AssertionEntity> assertions) { this.name = nameFromResourceString(name); this.assertions = assertions; } private static String nameFromResourceString(String resource) { Matcher matcher = namePattern.matcher(resource); if (!matcher.matches()) throw new IllegalArgumentException("Could not find policy name from resource string: " + resource); return matcher.group("name"); } >>>>>>> REPLACE
spreadflow/spreadflow-core
6422f6057d43dfb5259028291991f39c5b81b446
spreadflow_core/flow.py
python
mit
Refactor Flowmap into a MutableMapping
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict class Flowmap(dict): def __init__(self): super(Flowmap, self).__init__() self.decorators = [] self.annotations = {} def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict, MutableMapping class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() self.annotations = {} self.connections = {} self.decorators = [] def __getitem__(self, key): return self.connections[key] def __setitem__(self, key, value): self.connections[key] = value def __delitem__(self, key): del self.connections[key] def __iter__(self): return iter(self.connections) def __len__(self): return len(self.connections) def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
19
3
1
mixed
--- a/spreadflow_core/flow.py +++ b/spreadflow_core/flow.py @@ -4,10 +4,26 @@ -from collections import defaultdict +from collections import defaultdict, MutableMapping -class Flowmap(dict): +class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() + self.annotations = {} + self.connections = {} self.decorators = [] - self.annotations = {} + + def __getitem__(self, key): + return self.connections[key] + + def __setitem__(self, key, value): + self.connections[key] = value + + def __delitem__(self, key): + del self.connections[key] + + def __iter__(self): + return iter(self.connections) + + def __len__(self): + return len(self.connections)
--- a/spreadflow_core/flow.py +++ b/spreadflow_core/flow.py @@ ... @@ -from collections import defaultdict +from collections import defaultdict, MutableMapping -class Flowmap(dict): +class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() + self.annotations = {} + self.connections = {} self.decorators = [] - self.annotations = {} + + def __getitem__(self, key): + return self.connections[key] + + def __setitem__(self, key, value): + self.connections[key] = value + + def __delitem__(self, key): + del self.connections[key] + + def __iter__(self): + return iter(self.connections) + + def __len__(self): + return len(self.connections)
--- a/spreadflow_core/flow.py +++ b/spreadflow_core/flow.py @@ -4,10 +4,26 @@ CON DEL from collections import defaultdict ADD from collections import defaultdict, MutableMapping CON CON DEL class Flowmap(dict): ADD class Flowmap(MutableMapping): CON def __init__(self): CON super(Flowmap, self).__init__() ADD self.annotations = {} ADD self.connections = {} CON self.decorators = [] DEL self.annotations = {} ADD ADD def __getitem__(self, key): ADD return self.connections[key] ADD ADD def __setitem__(self, key, value): ADD self.connections[key] = value ADD ADD def __delitem__(self, key): ADD del self.connections[key] ADD ADD def __iter__(self): ADD return iter(self.connections) ADD ADD def __len__(self): ADD return len(self.connections) CON
<<<<<<< SEARCH from __future__ import unicode_literals from collections import defaultdict class Flowmap(dict): def __init__(self): super(Flowmap, self).__init__() self.decorators = [] self.annotations = {} def graph(self): ======= from __future__ import unicode_literals from collections import defaultdict, MutableMapping class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() self.annotations = {} self.connections = {} self.decorators = [] def __getitem__(self, key): return self.connections[key] def __setitem__(self, key, value): self.connections[key] = value def __delitem__(self, key): del self.connections[key] def __iter__(self): return iter(self.connections) def __len__(self): return len(self.connections) def graph(self): >>>>>>> REPLACE
santigimeno/node-unix-stream
d04770d63c8e434bdd4dd56b9ed2b4046c8905ca
src/unix_stream.js
javascript
isc
Choose the correct build directory - We get it from the process.config.default_configuration
var util = require('util'); var Socket = require('net').Socket; var bindings = require(__dirname + '/../build/Debug/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
var util = require('util'); var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
3
1
1
mixed
--- a/src/unix_stream.js +++ b/src/unix_stream.js @@ -3,3 +3,5 @@ -var bindings = require(__dirname + '/../build/Debug/unix_stream.node'); +/* Make sure we choose the correct build directory */ +var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; +var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node');
--- a/src/unix_stream.js +++ b/src/unix_stream.js @@ ... @@ -var bindings = require(__dirname + '/../build/Debug/unix_stream.node'); +/* Make sure we choose the correct build directory */ +var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; +var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node');
--- a/src/unix_stream.js +++ b/src/unix_stream.js @@ -3,3 +3,5 @@ CON DEL var bindings = require(__dirname + '/../build/Debug/unix_stream.node'); ADD /* Make sure we choose the correct build directory */ ADD var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; ADD var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); CON
<<<<<<< SEARCH var Socket = require('net').Socket; var bindings = require(__dirname + '/../build/Debug/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; ======= var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; >>>>>>> REPLACE
teobaranga/T-Tasks
be691f14a280358fc60b2b65008f074abce88ba2
t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt
kotlin
apache-2.0
Store task reminders in Firebase per user
package com.teo.ttasks.util import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import timber.log.Timber object FirebaseUtil { private const val DB_TASKS = "tasks" /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { return this.getReference(DB_TASKS) } /** * Get a reference to the reminder property of the given task * * @param taskId ID of the task */ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { if (this.key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") return null } return this.child(taskId).child("reminder") } /** * Set or clear the reminder date for a given task * * @param taskId ID of the modified task * @param dateInMillis the reminder date in milliseconds, can be null to remove the reminder */ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { this.reminder(taskId)?.setValue(dateInMillis) } }
package com.teo.ttasks.util import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import timber.log.Timber object FirebaseUtil { private const val DB_TASKS = "tasks" private val firebaseAuth = FirebaseAuth.getInstance() /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { return getReference("users/${firebaseAuth.currentUser!!.uid}/$DB_TASKS") } /** * Get a reference to the reminder property of the given task * * @param taskId ID of the task */ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { if (key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") return null } return child(taskId).child("reminder") } /** * Set or clear the reminder date for a given task * * @param taskId ID of the modified task * @param dateInMillis the reminder date in milliseconds, can be null to remove the reminder */ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { reminder(taskId)?.setValue(dateInMillis) } }
7
4
5
mixed
--- a/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt +++ b/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt @@ -2,2 +2,3 @@ +import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference @@ -10,5 +11,7 @@ + private val firebaseAuth = FirebaseAuth.getInstance() + /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { - return this.getReference(DB_TASKS) + return getReference("users/${firebaseAuth.currentUser!!.uid}/$DB_TASKS") } @@ -21,3 +24,3 @@ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { - if (this.key != DB_TASKS) { + if (key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") @@ -25,3 +28,3 @@ } - return this.child(taskId).child("reminder") + return child(taskId).child("reminder") } @@ -35,3 +38,3 @@ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { - this.reminder(taskId)?.setValue(dateInMillis) + reminder(taskId)?.setValue(dateInMillis) }
--- a/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt +++ b/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt @@ ... @@ +import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference @@ ... @@ + private val firebaseAuth = FirebaseAuth.getInstance() + /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { - return this.getReference(DB_TASKS) + return getReference("users/${firebaseAuth.currentUser!!.uid}/$DB_TASKS") } @@ ... @@ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { - if (this.key != DB_TASKS) { + if (key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") @@ ... @@ } - return this.child(taskId).child("reminder") + return child(taskId).child("reminder") } @@ ... @@ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { - this.reminder(taskId)?.setValue(dateInMillis) + reminder(taskId)?.setValue(dateInMillis) }
--- a/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt +++ b/t-tasks/src/main/java/com/teo/ttasks/util/FirebaseUtil.kt @@ -2,2 +2,3 @@ CON ADD import com.google.firebase.auth.FirebaseAuth CON import com.google.firebase.database.DatabaseReference @@ -10,5 +11,7 @@ CON ADD private val firebaseAuth = FirebaseAuth.getInstance() ADD CON /** The reference to the Firebase Database containing additional information about all the tasks */ CON fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { DEL return this.getReference(DB_TASKS) ADD return getReference("users/${firebaseAuth.currentUser!!.uid}/$DB_TASKS") CON } @@ -21,3 +24,3 @@ CON fun DatabaseReference.reminder(taskId: String): DatabaseReference? { DEL if (this.key != DB_TASKS) { ADD if (key != DB_TASKS) { CON Timber.w("Attempting to access task reminders in the wrong database") @@ -25,3 +28,3 @@ CON } DEL return this.child(taskId).child("reminder") ADD return child(taskId).child("reminder") CON } @@ -35,3 +38,3 @@ CON fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { DEL this.reminder(taskId)?.setValue(dateInMillis) ADD reminder(taskId)?.setValue(dateInMillis) CON }
<<<<<<< SEARCH package com.teo.ttasks.util import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase ======= package com.teo.ttasks.util import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase >>>>>>> REPLACE <<<<<<< SEARCH private const val DB_TASKS = "tasks" /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { return this.getReference(DB_TASKS) } ======= private const val DB_TASKS = "tasks" private val firebaseAuth = FirebaseAuth.getInstance() /** The reference to the Firebase Database containing additional information about all the tasks */ fun FirebaseDatabase.getTasksDatabase(): DatabaseReference { return getReference("users/${firebaseAuth.currentUser!!.uid}/$DB_TASKS") } >>>>>>> REPLACE <<<<<<< SEARCH */ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { if (this.key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") return null } return this.child(taskId).child("reminder") } ======= */ fun DatabaseReference.reminder(taskId: String): DatabaseReference? { if (key != DB_TASKS) { Timber.w("Attempting to access task reminders in the wrong database") return null } return child(taskId).child("reminder") } >>>>>>> REPLACE <<<<<<< SEARCH */ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { this.reminder(taskId)?.setValue(dateInMillis) } } ======= */ fun DatabaseReference.saveReminder(taskId: String, dateInMillis: Long?) { reminder(taskId)?.setValue(dateInMillis) } } >>>>>>> REPLACE
robinverduijn/gradle
b3d56e078f37d4ea467d8c74d0a12894ed052581
subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts
kotlin
apache-2.0
Remove `integTestRuntimeOnly` references from `kotlinDslProviderPlugins` The project no longer has integration tests.
/* * Copyright 2018 the original author or authors. * * 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 build.withCompileOnlyGradleApiModulesWithParameterNames import org.gradle.gradlebuild.unittestandcompile.ModuleType plugins { `kotlin-dsl-module` } description = "Kotlin DSL Provider Plugins" gradlebuildJava { moduleType = ModuleType.CORE } withCompileOnlyGradleApiModulesWithParameterNames( ":plugins", ":pluginDevelopment" ) dependencies { compile(project(":distributionsDependencies")) compile(project(":kotlinDsl")) testImplementation(project(":kotlinDslTestFixtures")) testImplementation(project(":plugins")) integTestRuntimeOnly(project(":runtimeApiInfo")) integTestRuntimeOnly(project(":apiMetadata")) }
/* * Copyright 2018 the original author or authors. * * 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 build.withCompileOnlyGradleApiModulesWithParameterNames import org.gradle.gradlebuild.unittestandcompile.ModuleType plugins { `kotlin-dsl-module` } description = "Kotlin DSL Provider Plugins" gradlebuildJava { moduleType = ModuleType.CORE } withCompileOnlyGradleApiModulesWithParameterNames( ":plugins", ":pluginDevelopment" ) dependencies { compile(project(":distributionsDependencies")) compile(project(":kotlinDsl")) testImplementation(project(":kotlinDslTestFixtures")) testImplementation(project(":plugins")) }
0
3
1
del_only
--- a/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts +++ b/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts @@ -42,5 +42,2 @@ testImplementation(project(":plugins")) - - integTestRuntimeOnly(project(":runtimeApiInfo")) - integTestRuntimeOnly(project(":apiMetadata")) }
--- a/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts +++ b/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts @@ ... @@ testImplementation(project(":plugins")) - - integTestRuntimeOnly(project(":runtimeApiInfo")) - integTestRuntimeOnly(project(":apiMetadata")) }
--- a/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts +++ b/subprojects/kotlin-dsl-provider-plugins/kotlin-dsl-provider-plugins.gradle.kts @@ -42,5 +42,2 @@ CON testImplementation(project(":plugins")) DEL DEL integTestRuntimeOnly(project(":runtimeApiInfo")) DEL integTestRuntimeOnly(project(":apiMetadata")) CON }
<<<<<<< SEARCH testImplementation(project(":kotlinDslTestFixtures")) testImplementation(project(":plugins")) integTestRuntimeOnly(project(":runtimeApiInfo")) integTestRuntimeOnly(project(":apiMetadata")) } ======= testImplementation(project(":kotlinDslTestFixtures")) testImplementation(project(":plugins")) } >>>>>>> REPLACE
TeamTwisted/external_skia
6776a538f946a25e921f8ecd11a0ce1ddd422d0d
tools/skp/page_sets/skia_ukwsj_nexus10.py
python
bsd-3-clause
Increase timeout of ukwsj to get more consistent SKP captures BUG=skia:3574 TBR=borenet NOTRY=true Review URL: https://codereview.chromium.org/1038443002
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_ukwsj_nexus10.json' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(5) class SkiaUkwsjNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaUkwsjNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_ukwsj_nexus10.json') urls_list = [ # Why: for Clank CY 'http://uk.wsj.com/home-page', ] for url in urls_list: self.AddUserStory(SkiaBuildbotDesktopPage(url, self))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_ukwsj_nexus10.json' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(15) class SkiaUkwsjNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaUkwsjNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_ukwsj_nexus10.json') urls_list = [ # Why: for Clank CY 'http://uk.wsj.com/home-page', ] for url in urls_list: self.AddUserStory(SkiaBuildbotDesktopPage(url, self))
1
1
1
mixed
--- a/tools/skp/page_sets/skia_ukwsj_nexus10.py +++ b/tools/skp/page_sets/skia_ukwsj_nexus10.py @@ -22,3 +22,3 @@ action_runner.NavigateToPage(self) - action_runner.Wait(5) + action_runner.Wait(15)
--- a/tools/skp/page_sets/skia_ukwsj_nexus10.py +++ b/tools/skp/page_sets/skia_ukwsj_nexus10.py @@ ... @@ action_runner.NavigateToPage(self) - action_runner.Wait(5) + action_runner.Wait(15)
--- a/tools/skp/page_sets/skia_ukwsj_nexus10.py +++ b/tools/skp/page_sets/skia_ukwsj_nexus10.py @@ -22,3 +22,3 @@ CON action_runner.NavigateToPage(self) DEL action_runner.Wait(5) ADD action_runner.Wait(15) CON
<<<<<<< SEARCH def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(5) ======= def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(15) >>>>>>> REPLACE
xflows/clowdflows-backend
3b4c645792c1a58cdce3dc25171723e7139d66da
workflows/api/permissions.py
python
mit
Return True for preview if workflow public
from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False
from rest_framework import permissions from workflows.models import * class IsAdminOrSelf(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.is_authenticated(): # Don't allow adding widgets to workflows not owned by the user if view.model == Widget and 'workflow' in request.data: serializer = view.serializer_class(data=request.data) serializer.is_valid() workflow = serializer.validated_data['workflow'] if request.GET.get('preview', '0') == '1': if workflow.public: return True return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: return request.user.is_staff else: return True def has_object_permission(self, request, view, obj): if request.user and request.user.is_authenticated(): if request.user.is_superuser: return True # Allow only editing of the user's workflow objects if isinstance(obj, Workflow): return obj.user == request.user if isinstance(obj, Widget): return obj.workflow.user == request.user if isinstance(obj, Connection): return obj.workflow.user == request.user if isinstance(obj, Input): return obj.widget.workflow.user == request.user if isinstance(obj, Output): return obj.widget.workflow.user == request.user return False
3
0
1
add_only
--- a/workflows/api/permissions.py +++ b/workflows/api/permissions.py @@ -13,2 +13,5 @@ workflow = serializer.validated_data['workflow'] + if request.GET.get('preview', '0') == '1': + if workflow.public: + return True return workflow.user == request.user
--- a/workflows/api/permissions.py +++ b/workflows/api/permissions.py @@ ... @@ workflow = serializer.validated_data['workflow'] + if request.GET.get('preview', '0') == '1': + if workflow.public: + return True return workflow.user == request.user
--- a/workflows/api/permissions.py +++ b/workflows/api/permissions.py @@ -13,2 +13,5 @@ CON workflow = serializer.validated_data['workflow'] ADD if request.GET.get('preview', '0') == '1': ADD if workflow.public: ADD return True CON return workflow.user == request.user
<<<<<<< SEARCH serializer.is_valid() workflow = serializer.validated_data['workflow'] return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: ======= serializer.is_valid() workflow = serializer.validated_data['workflow'] if request.GET.get('preview', '0') == '1': if workflow.public: return True return workflow.user == request.user if view.model == Workflow and 'staff_pick' in request.data: >>>>>>> REPLACE
shinhithi/google-services
16d4bf86166a3d8a3be37417ac8e29e9ece1e7c2
android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java
java
apache-2.0
Remove deprecated Logger usage in Analytics Change-Id: I66165a76f3a8a47af8473555c6280450835a75c2
/* * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
/* * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
1
1
1
mixed
--- a/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java +++ b/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java @@ -38,3 +38,3 @@ GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); - analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); + // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker);
--- a/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java +++ b/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java @@ ... @@ GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); - analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); + // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker);
--- a/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java +++ b/android/analytics/app/src/main/java/com/google/samples/quickstart/analytics/AnalyticsApplication.java @@ -38,3 +38,3 @@ CON GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); DEL analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); ADD // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG CON mTracker = analytics.newTracker(R.xml.global_tracker);
<<<<<<< SEARCH if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); mTracker = analytics.newTracker(R.xml.global_tracker); } ======= if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker); } >>>>>>> REPLACE
anthonycr/Lightning-Browser
278eed458a49dc0e41d0556c8734a434a0c36cef
app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt
kotlin
mpl-2.0
Make factory method more idiomatic
package acr.browser.lightning.animation import android.support.annotation.DrawableRes import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation import android.view.animation.Transformation import android.widget.ImageView /** * Animation specific helper code. */ object AnimationUtils { /** * Creates an animation that rotates an [ImageView] around the Y axis by 180 degrees and changes * the image resource shown when the view is rotated 90 degrees to the user. * * @param imageView the view to rotate. * @param drawableRes the drawable to set when the view is rotated by 90 degrees. * @return an animation that will change the image shown by the view. */ @JvmStatic fun createRotationTransitionAnimation(imageView: ImageView, @DrawableRes drawableRes: Int): Animation { val animation = object : Animation() { private var setFinalDrawable: Boolean = false override fun applyTransformation(interpolatedTime: Float, t: Transformation) = if (interpolatedTime < 0.5f) { imageView.rotationY = 90f * interpolatedTime * 2f } else { if (!setFinalDrawable) { setFinalDrawable = true imageView.setImageResource(drawableRes) } imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f } } animation.duration = 300 animation.interpolator = AccelerateDecelerateInterpolator() return animation } }
package acr.browser.lightning.animation import android.support.annotation.DrawableRes import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation import android.view.animation.Transformation import android.widget.ImageView /** * Animation specific helper code. */ object AnimationUtils { /** * Creates an animation that rotates an [ImageView] around the Y axis by 180 degrees and changes * the image resource shown when the view is rotated 90 degrees to the user. * * @param imageView the view to rotate. * @param drawableRes the drawable to set when the view is rotated by 90 degrees. * @return an animation that will change the image shown by the view. */ @JvmStatic fun createRotationTransitionAnimation( imageView: ImageView, @DrawableRes drawableRes: Int ): Animation = object : Animation() { private var setFinalDrawable: Boolean = false override fun applyTransformation(interpolatedTime: Float, t: Transformation) = if (interpolatedTime < 0.5f) { imageView.rotationY = 90f * interpolatedTime * 2f } else { if (!setFinalDrawable) { setFinalDrawable = true imageView.setImageResource(drawableRes) } imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f } }.apply { duration = 300 interpolator = AccelerateDecelerateInterpolator() } }
17
18
1
mixed
--- a/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt +++ b/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt @@ -22,24 +22,23 @@ @JvmStatic - fun createRotationTransitionAnimation(imageView: ImageView, - @DrawableRes drawableRes: Int): Animation { - val animation = object : Animation() { + fun createRotationTransitionAnimation( + imageView: ImageView, + @DrawableRes drawableRes: Int + ): Animation = object : Animation() { - private var setFinalDrawable: Boolean = false + private var setFinalDrawable: Boolean = false - override fun applyTransformation(interpolatedTime: Float, t: Transformation) = - if (interpolatedTime < 0.5f) { - imageView.rotationY = 90f * interpolatedTime * 2f - } else { - if (!setFinalDrawable) { - setFinalDrawable = true - imageView.setImageResource(drawableRes) - } - imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f + override fun applyTransformation(interpolatedTime: Float, t: Transformation) = + if (interpolatedTime < 0.5f) { + imageView.rotationY = 90f * interpolatedTime * 2f + } else { + if (!setFinalDrawable) { + setFinalDrawable = true + imageView.setImageResource(drawableRes) } - } + imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f + } - animation.duration = 300 - animation.interpolator = AccelerateDecelerateInterpolator() - - return animation + }.apply { + duration = 300 + interpolator = AccelerateDecelerateInterpolator() }
--- a/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt +++ b/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt @@ ... @@ @JvmStatic - fun createRotationTransitionAnimation(imageView: ImageView, - @DrawableRes drawableRes: Int): Animation { - val animation = object : Animation() { + fun createRotationTransitionAnimation( + imageView: ImageView, + @DrawableRes drawableRes: Int + ): Animation = object : Animation() { - private var setFinalDrawable: Boolean = false + private var setFinalDrawable: Boolean = false - override fun applyTransformation(interpolatedTime: Float, t: Transformation) = - if (interpolatedTime < 0.5f) { - imageView.rotationY = 90f * interpolatedTime * 2f - } else { - if (!setFinalDrawable) { - setFinalDrawable = true - imageView.setImageResource(drawableRes) - } - imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f + override fun applyTransformation(interpolatedTime: Float, t: Transformation) = + if (interpolatedTime < 0.5f) { + imageView.rotationY = 90f * interpolatedTime * 2f + } else { + if (!setFinalDrawable) { + setFinalDrawable = true + imageView.setImageResource(drawableRes) } - } + imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f + } - animation.duration = 300 - animation.interpolator = AccelerateDecelerateInterpolator() - - return animation + }.apply { + duration = 300 + interpolator = AccelerateDecelerateInterpolator() }
--- a/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt +++ b/app/src/main/java/acr/browser/lightning/animation/AnimationUtils.kt @@ -22,24 +22,23 @@ CON @JvmStatic DEL fun createRotationTransitionAnimation(imageView: ImageView, DEL @DrawableRes drawableRes: Int): Animation { DEL val animation = object : Animation() { ADD fun createRotationTransitionAnimation( ADD imageView: ImageView, ADD @DrawableRes drawableRes: Int ADD ): Animation = object : Animation() { CON DEL private var setFinalDrawable: Boolean = false ADD private var setFinalDrawable: Boolean = false CON DEL override fun applyTransformation(interpolatedTime: Float, t: Transformation) = DEL if (interpolatedTime < 0.5f) { DEL imageView.rotationY = 90f * interpolatedTime * 2f DEL } else { DEL if (!setFinalDrawable) { DEL setFinalDrawable = true DEL imageView.setImageResource(drawableRes) DEL } DEL imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f ADD override fun applyTransformation(interpolatedTime: Float, t: Transformation) = ADD if (interpolatedTime < 0.5f) { ADD imageView.rotationY = 90f * interpolatedTime * 2f ADD } else { ADD if (!setFinalDrawable) { ADD setFinalDrawable = true ADD imageView.setImageResource(drawableRes) CON } DEL } ADD imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f ADD } CON DEL animation.duration = 300 DEL animation.interpolator = AccelerateDecelerateInterpolator() DEL DEL return animation ADD }.apply { ADD duration = 300 ADD interpolator = AccelerateDecelerateInterpolator() CON }
<<<<<<< SEARCH */ @JvmStatic fun createRotationTransitionAnimation(imageView: ImageView, @DrawableRes drawableRes: Int): Animation { val animation = object : Animation() { private var setFinalDrawable: Boolean = false override fun applyTransformation(interpolatedTime: Float, t: Transformation) = if (interpolatedTime < 0.5f) { imageView.rotationY = 90f * interpolatedTime * 2f } else { if (!setFinalDrawable) { setFinalDrawable = true imageView.setImageResource(drawableRes) } imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f } } animation.duration = 300 animation.interpolator = AccelerateDecelerateInterpolator() return animation } ======= */ @JvmStatic fun createRotationTransitionAnimation( imageView: ImageView, @DrawableRes drawableRes: Int ): Animation = object : Animation() { private var setFinalDrawable: Boolean = false override fun applyTransformation(interpolatedTime: Float, t: Transformation) = if (interpolatedTime < 0.5f) { imageView.rotationY = 90f * interpolatedTime * 2f } else { if (!setFinalDrawable) { setFinalDrawable = true imageView.setImageResource(drawableRes) } imageView.rotationY = -90 + 90f * (interpolatedTime - 0.5f) * 2f } }.apply { duration = 300 interpolator = AccelerateDecelerateInterpolator() } >>>>>>> REPLACE
michaeljoseph/righteous
15b4f0c587bdd5772718d9d75ff5654d9b835ae5
righteous/config.py
python
unlicense
Copy the settings class from an old requests version
# coding: utf-8 """ righteous.config Settings object, lifted from https://github.com/kennethreitz/requests """ from requests.config import Settings class RighteousSettings(Settings): pass settings = RighteousSettings() settings.debug = False settings.cookies = None settings.username = None settings.password = None settings.account_id = None
# coding: utf-8 """ righteous.config Settings object, lifted from https://github.com/kennethreitz/requests """ class Settings(object): _singleton = {} # attributes with defaults __attrs__ = [] def __init__(self, **kwargs): super(Settings, self).__init__() self.__dict__ = self._singleton def __call__(self, *args, **kwargs): # new instance of class to call r = self.__class__() # cache previous settings for __exit__ r.__cache = self.__dict__.copy() map(self.__cache.setdefault, self.__attrs__) # set new settings self.__dict__.update(*args, **kwargs) return r def __enter__(self): pass def __exit__(self, *args): # restore cached copy self.__dict__.update(self.__cache.copy()) del self.__cache def __getattribute__(self, key): if key in object.__getattribute__(self, '__attrs__'): try: return object.__getattribute__(self, key) except AttributeError: return None return object.__getattribute__(self, key) settings = Settings() settings.debug = False settings.cookies = None settings.username = None settings.password = None settings.account_id = None
44
4
1
mixed
--- a/righteous/config.py +++ b/righteous/config.py @@ -9,9 +9,49 @@ -from requests.config import Settings +class Settings(object): + _singleton = {} -class RighteousSettings(Settings): - pass + # attributes with defaults + __attrs__ = [] + + def __init__(self, **kwargs): + super(Settings, self).__init__() + + self.__dict__ = self._singleton -settings = RighteousSettings() + def __call__(self, *args, **kwargs): + # new instance of class to call + r = self.__class__() + + # cache previous settings for __exit__ + r.__cache = self.__dict__.copy() + map(self.__cache.setdefault, self.__attrs__) + + # set new settings + self.__dict__.update(*args, **kwargs) + + return r + + + def __enter__(self): + pass + + + def __exit__(self, *args): + + # restore cached copy + self.__dict__.update(self.__cache.copy()) + del self.__cache + + + def __getattribute__(self, key): + if key in object.__getattribute__(self, '__attrs__'): + try: + return object.__getattribute__(self, key) + except AttributeError: + return None + return object.__getattribute__(self, key) + + +settings = Settings() settings.debug = False
--- a/righteous/config.py +++ b/righteous/config.py @@ ... @@ -from requests.config import Settings +class Settings(object): + _singleton = {} -class RighteousSettings(Settings): - pass + # attributes with defaults + __attrs__ = [] + + def __init__(self, **kwargs): + super(Settings, self).__init__() + + self.__dict__ = self._singleton -settings = RighteousSettings() + def __call__(self, *args, **kwargs): + # new instance of class to call + r = self.__class__() + + # cache previous settings for __exit__ + r.__cache = self.__dict__.copy() + map(self.__cache.setdefault, self.__attrs__) + + # set new settings + self.__dict__.update(*args, **kwargs) + + return r + + + def __enter__(self): + pass + + + def __exit__(self, *args): + + # restore cached copy + self.__dict__.update(self.__cache.copy()) + del self.__cache + + + def __getattribute__(self, key): + if key in object.__getattribute__(self, '__attrs__'): + try: + return object.__getattribute__(self, key) + except AttributeError: + return None + return object.__getattribute__(self, key) + + +settings = Settings() settings.debug = False
--- a/righteous/config.py +++ b/righteous/config.py @@ -9,9 +9,49 @@ CON DEL from requests.config import Settings ADD class Settings(object): ADD _singleton = {} CON DEL class RighteousSettings(Settings): DEL pass ADD # attributes with defaults ADD __attrs__ = [] ADD ADD def __init__(self, **kwargs): ADD super(Settings, self).__init__() ADD ADD self.__dict__ = self._singleton CON CON DEL settings = RighteousSettings() ADD def __call__(self, *args, **kwargs): ADD # new instance of class to call ADD r = self.__class__() ADD ADD # cache previous settings for __exit__ ADD r.__cache = self.__dict__.copy() ADD map(self.__cache.setdefault, self.__attrs__) ADD ADD # set new settings ADD self.__dict__.update(*args, **kwargs) ADD ADD return r ADD ADD ADD def __enter__(self): ADD pass ADD ADD ADD def __exit__(self, *args): ADD ADD # restore cached copy ADD self.__dict__.update(self.__cache.copy()) ADD del self.__cache ADD ADD ADD def __getattribute__(self, key): ADD if key in object.__getattribute__(self, '__attrs__'): ADD try: ADD return object.__getattribute__(self, key) ADD except AttributeError: ADD return None ADD return object.__getattribute__(self, key) ADD ADD ADD settings = Settings() CON settings.debug = False
<<<<<<< SEARCH """ from requests.config import Settings class RighteousSettings(Settings): pass settings = RighteousSettings() settings.debug = False settings.cookies = None ======= """ class Settings(object): _singleton = {} # attributes with defaults __attrs__ = [] def __init__(self, **kwargs): super(Settings, self).__init__() self.__dict__ = self._singleton def __call__(self, *args, **kwargs): # new instance of class to call r = self.__class__() # cache previous settings for __exit__ r.__cache = self.__dict__.copy() map(self.__cache.setdefault, self.__attrs__) # set new settings self.__dict__.update(*args, **kwargs) return r def __enter__(self): pass def __exit__(self, *args): # restore cached copy self.__dict__.update(self.__cache.copy()) del self.__cache def __getattribute__(self, key): if key in object.__getattribute__(self, '__attrs__'): try: return object.__getattribute__(self, key) except AttributeError: return None return object.__getattribute__(self, key) settings = Settings() settings.debug = False settings.cookies = None >>>>>>> REPLACE
Altometrics/jsass
a66cef5dca6c552bc6d8ae76ffaea910366db759
src/main/java/io/bit3/jsass/context/ImportStack.java
java
mit
Use a Deque instead of Stack. java.util.Stack is synchronized which is not necessary here.
package io.bit3.jsass.context; import io.bit3.jsass.importer.Import; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * Stack for tracking currently evaluated file. */ public class ImportStack { /** * A registry where each import will be registered by an incrementing ID. */ private Map<Integer, Import> registry = new HashMap<>(); /** * The current import stack. */ private Stack<Import> stack = new Stack<>(); /** * Register a new import, return the registration ID. */ public int register(Import importSource) { int id = registry.size() + 1; registry.put(id, importSource); return id; } /** * Push an import to the stack by its ID. */ public void push(int id) { stack.push(registry.get(id)); } /** * Pop an import from the stack. */ public void pop() { stack.pop(); } /** * Return the current import. */ public Import peek() { return stack.peek(); } }
package io.bit3.jsass.context; import io.bit3.jsass.importer.Import; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** * Stack for tracking currently evaluated file. */ public class ImportStack { /** * A registry where each import will be registered by an incrementing ID. */ private Map<Integer, Import> registry = new HashMap<>(); /** * The current import stack. */ private Deque<Import> stack = new LinkedList<>(); /** * Register a new import, return the registration ID. */ public int register(Import importSource) { int id = registry.size() + 1; registry.put(id, importSource); return id; } /** * Push an import to the stack by its ID. */ public void push(int id) { stack.push(registry.get(id)); } /** * Pop an import from the stack. */ public void pop() { stack.pop(); } /** * Return the current import. */ public Import peek() { return stack.peek(); } }
3
2
2
mixed
--- a/src/main/java/io/bit3/jsass/context/ImportStack.java +++ b/src/main/java/io/bit3/jsass/context/ImportStack.java @@ -4,5 +4,6 @@ +import java.util.Deque; import java.util.HashMap; +import java.util.LinkedList; import java.util.Map; -import java.util.Stack; @@ -21,3 +22,3 @@ */ - private Stack<Import> stack = new Stack<>(); + private Deque<Import> stack = new LinkedList<>();
--- a/src/main/java/io/bit3/jsass/context/ImportStack.java +++ b/src/main/java/io/bit3/jsass/context/ImportStack.java @@ ... @@ +import java.util.Deque; import java.util.HashMap; +import java.util.LinkedList; import java.util.Map; -import java.util.Stack; @@ ... @@ */ - private Stack<Import> stack = new Stack<>(); + private Deque<Import> stack = new LinkedList<>();
--- a/src/main/java/io/bit3/jsass/context/ImportStack.java +++ b/src/main/java/io/bit3/jsass/context/ImportStack.java @@ -4,5 +4,6 @@ CON ADD import java.util.Deque; CON import java.util.HashMap; ADD import java.util.LinkedList; CON import java.util.Map; DEL import java.util.Stack; CON @@ -21,3 +22,3 @@ CON */ DEL private Stack<Import> stack = new Stack<>(); ADD private Deque<Import> stack = new LinkedList<>(); CON
<<<<<<< SEARCH import io.bit3.jsass.importer.Import; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** ======= import io.bit3.jsass.importer.Import; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** >>>>>>> REPLACE <<<<<<< SEARCH * The current import stack. */ private Stack<Import> stack = new Stack<>(); /** ======= * The current import stack. */ private Deque<Import> stack = new LinkedList<>(); /** >>>>>>> REPLACE
kylewlacy/glitter
3a8d90bc6d0cd14a43dc3da322e7260cd6f751d4
src/uniform_data.rs
rust
apache-2.0
Add impls of `UniformPrimitive` for `f32` and `i32`
use std::slice; use std::mem; pub enum UniformPrimitiveType { Float, Int } pub enum UniformDatumType { Vec1(UniformPrimitiveType), Vec2(UniformPrimitiveType), Vec3(UniformPrimitiveType), Vec4(UniformPrimitiveType), Matrix2x2, Matrix3x3, Matrix4x4 } pub trait UniformData { fn uniform_datum_type() -> UniformDatumType; fn uniform_bytes(&self) -> &[u8]; fn uniform_elements(&self) -> usize; } pub trait UniformDatum { fn uniform_datum_type() -> UniformDatumType; } pub trait UniformPrimitive { fn uniform_primitive_type() -> UniformPrimitiveType; }
use std::slice; use std::mem; pub enum UniformPrimitiveType { Float, Int } pub enum UniformDatumType { Vec1(UniformPrimitiveType), Vec2(UniformPrimitiveType), Vec3(UniformPrimitiveType), Vec4(UniformPrimitiveType), Matrix2x2, Matrix3x3, Matrix4x4 } pub trait UniformData { fn uniform_datum_type() -> UniformDatumType; fn uniform_bytes(&self) -> &[u8]; fn uniform_elements(&self) -> usize; } pub trait UniformDatum { fn uniform_datum_type() -> UniformDatumType; } pub trait UniformPrimitive { fn uniform_primitive_type() -> UniformPrimitiveType; } impl UniformPrimitive for f32 { fn uniform_primitive_type() -> UniformPrimitiveType { UniformPrimitiveType::Float } } impl UniformPrimitive for i32 { fn uniform_primitive_type() -> UniformPrimitiveType { UniformPrimitiveType::Int } }
12
0
1
add_only
--- a/src/uniform_data.rs +++ b/src/uniform_data.rs @@ -34 +34,13 @@ } + +impl UniformPrimitive for f32 { + fn uniform_primitive_type() -> UniformPrimitiveType { + UniformPrimitiveType::Float + } +} + +impl UniformPrimitive for i32 { + fn uniform_primitive_type() -> UniformPrimitiveType { + UniformPrimitiveType::Int + } +}
--- a/src/uniform_data.rs +++ b/src/uniform_data.rs @@ ... @@ } + +impl UniformPrimitive for f32 { + fn uniform_primitive_type() -> UniformPrimitiveType { + UniformPrimitiveType::Float + } +} + +impl UniformPrimitive for i32 { + fn uniform_primitive_type() -> UniformPrimitiveType { + UniformPrimitiveType::Int + } +}
--- a/src/uniform_data.rs +++ b/src/uniform_data.rs @@ -34 +34,13 @@ CON } ADD ADD impl UniformPrimitive for f32 { ADD fn uniform_primitive_type() -> UniformPrimitiveType { ADD UniformPrimitiveType::Float ADD } ADD } ADD ADD impl UniformPrimitive for i32 { ADD fn uniform_primitive_type() -> UniformPrimitiveType { ADD UniformPrimitiveType::Int ADD } ADD }
<<<<<<< SEARCH fn uniform_primitive_type() -> UniformPrimitiveType; } ======= fn uniform_primitive_type() -> UniformPrimitiveType; } impl UniformPrimitive for f32 { fn uniform_primitive_type() -> UniformPrimitiveType { UniformPrimitiveType::Float } } impl UniformPrimitive for i32 { fn uniform_primitive_type() -> UniformPrimitiveType { UniformPrimitiveType::Int } } >>>>>>> REPLACE
CodeCastle/seiseki-junit5-extension
3fa5411205359ec3b676fb55efab7695ceda0184
src/main/java/nl/codecastle/configuration/PropertiesReader.java
java
apache-2.0
Read properties from a property file Reads a property value from either a project property file of the file or value is missing, tries to get a default value for that property.
package nl.codecastle.configuration; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Reads properties file from a given location. */ public class PropertiesReader { private final Properties properties; private final Properties defaultProperties; /** * Reads in the properties from the given path. * Also reads in the defaults properties from the "default.properties" file. * * @param filePath the path of the project properties file */ public PropertiesReader(String filePath) { properties = new Properties(); defaultProperties = new Properties(); try { ClassLoader classLoader = getClass().getClassLoader(); InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties"); InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath); assert (defaultPropertiesStream != null); defaultProperties.load(defaultPropertiesStream); if (projectPropertiesStream != null) { properties.load(projectPropertiesStream); } } catch (IOException e) { e.printStackTrace(); } } /** * Returns the value for the given key from the project properties file. * If the file is missing it retrieves a value from the default properties. * * @param key name of the property needed * @return the value for the given key */ public String getValue(String key) { if (properties.containsKey(key)) { return properties.getProperty(key); } else { return defaultProperties.getProperty(key); } } }
package nl.codecastle.configuration; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Reads properties file from a given location. */ public class PropertiesReader { private final Properties properties; private final Properties defaultProperties; /** * Reads in the properties from the given path. * Also reads in the defaults properties from the "default.properties" file. * * @param filePath the path of the project properties file */ public PropertiesReader(String filePath) { properties = new Properties(); defaultProperties = new Properties(); try { InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties"); InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath); assert (defaultPropertiesStream != null); defaultProperties.load(defaultPropertiesStream); if (projectPropertiesStream != null) { properties.load(projectPropertiesStream); } } catch (IOException e) { e.printStackTrace(); } } /** * Returns the value for the given key from the project properties file. * If the file is missing it retrieves a value from the default properties. * * @param key name of the property needed * @return the value for the given key */ public String getValue(String key) { if (properties.containsKey(key)) { return properties.getProperty(key); } else { return defaultProperties.getProperty(key); } } }
2
3
1
mixed
--- a/src/main/java/nl/codecastle/configuration/PropertiesReader.java +++ b/src/main/java/nl/codecastle/configuration/PropertiesReader.java @@ -26,5 +26,4 @@ try { - ClassLoader classLoader = getClass().getClassLoader(); - InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties"); - InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath); + InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties"); + InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath); assert (defaultPropertiesStream != null);
--- a/src/main/java/nl/codecastle/configuration/PropertiesReader.java +++ b/src/main/java/nl/codecastle/configuration/PropertiesReader.java @@ ... @@ try { - ClassLoader classLoader = getClass().getClassLoader(); - InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties"); - InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath); + InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties"); + InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath); assert (defaultPropertiesStream != null);
--- a/src/main/java/nl/codecastle/configuration/PropertiesReader.java +++ b/src/main/java/nl/codecastle/configuration/PropertiesReader.java @@ -26,5 +26,4 @@ CON try { DEL ClassLoader classLoader = getClass().getClassLoader(); DEL InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties"); DEL InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath); ADD InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties"); ADD InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath); CON assert (defaultPropertiesStream != null);
<<<<<<< SEARCH try { ClassLoader classLoader = getClass().getClassLoader(); InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties"); InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath); assert (defaultPropertiesStream != null); defaultProperties.load(defaultPropertiesStream); ======= try { InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties"); InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath); assert (defaultPropertiesStream != null); defaultProperties.load(defaultPropertiesStream); >>>>>>> REPLACE
Ruben-Sten/TeXiFy-IDEA
9b7b7102aa6596b4c378a27f758dd0a8f5d56916
src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt
kotlin
mit
Enable the out directory on all systems, on by default
package nl.rubensten.texifyidea.run import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.KillableProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.roots.ProjectRootManager /** * @author Sten Wessel */ open class BibtexCommandLineState( environment: ExecutionEnvironment, private val runConfig: BibtexRunConfiguration ) : CommandLineState(environment) { @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { val rootManager = ProjectRootManager.getInstance(environment.project) val fileIndex = rootManager.fileIndex val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!) val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.") val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.") // The working directory is as specified by the user in the working directory. // The fallback (if null) directory is the directory of the main file. val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path) val handler: ProcessHandler = KillableProcessHandler(commandLine) // Reports exit code to run output window when command is terminated ProcessTerminatedListener.attach(handler, environment.project) return handler } }
package nl.rubensten.texifyidea.run import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.KillableProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment /** * @author Sten Wessel */ open class BibtexCommandLineState( environment: ExecutionEnvironment, private val runConfig: BibtexRunConfiguration ) : CommandLineState(environment) { @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.") val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.") // The working directory is as specified by the user in the working directory. // The fallback (if null or empty) directory is the directory of the main file. val bibPath = runConfig.bibWorkingDir?.path val commandLine = if (!(bibPath.equals("") || bibPath == null)) { GeneralCommandLine(command).withWorkDirectory(bibPath) } else { GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path) } val handler: ProcessHandler = KillableProcessHandler(commandLine) // Reports exit code to run output window when command is terminated ProcessTerminatedListener.attach(handler, environment.project) return handler } }
9
6
3
mixed
--- a/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt +++ b/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt @@ -9,3 +9,2 @@ import com.intellij.execution.runners.ExecutionEnvironment -import com.intellij.openapi.roots.ProjectRootManager @@ -21,5 +20,2 @@ override fun startProcess(): ProcessHandler { - val rootManager = ProjectRootManager.getInstance(environment.project) - val fileIndex = rootManager.fileIndex - val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!) @@ -29,4 +25,11 @@ // The working directory is as specified by the user in the working directory. - // The fallback (if null) directory is the directory of the main file. - val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path) + // The fallback (if null or empty) directory is the directory of the main file. + val bibPath = runConfig.bibWorkingDir?.path + val commandLine = if (!(bibPath.equals("") || bibPath == null)) { + GeneralCommandLine(command).withWorkDirectory(bibPath) + } + else { + GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path) + } +
--- a/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt +++ b/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt @@ ... @@ import com.intellij.execution.runners.ExecutionEnvironment -import com.intellij.openapi.roots.ProjectRootManager @@ ... @@ override fun startProcess(): ProcessHandler { - val rootManager = ProjectRootManager.getInstance(environment.project) - val fileIndex = rootManager.fileIndex - val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!) @@ ... @@ // The working directory is as specified by the user in the working directory. - // The fallback (if null) directory is the directory of the main file. - val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path) + // The fallback (if null or empty) directory is the directory of the main file. + val bibPath = runConfig.bibWorkingDir?.path + val commandLine = if (!(bibPath.equals("") || bibPath == null)) { + GeneralCommandLine(command).withWorkDirectory(bibPath) + } + else { + GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path) + } +
--- a/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt +++ b/src/nl/rubensten/texifyidea/run/BibtexCommandLineState.kt @@ -9,3 +9,2 @@ CON import com.intellij.execution.runners.ExecutionEnvironment DEL import com.intellij.openapi.roots.ProjectRootManager CON @@ -21,5 +20,2 @@ CON override fun startProcess(): ProcessHandler { DEL val rootManager = ProjectRootManager.getInstance(environment.project) DEL val fileIndex = rootManager.fileIndex DEL val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!) CON @@ -29,4 +25,11 @@ CON // The working directory is as specified by the user in the working directory. DEL // The fallback (if null) directory is the directory of the main file. DEL val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path) ADD // The fallback (if null or empty) directory is the directory of the main file. ADD val bibPath = runConfig.bibWorkingDir?.path ADD val commandLine = if (!(bibPath.equals("") || bibPath == null)) { ADD GeneralCommandLine(command).withWorkDirectory(bibPath) ADD } ADD else { ADD GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path) ADD } ADD CON
<<<<<<< SEARCH import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.roots.ProjectRootManager /** ======= import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment /** >>>>>>> REPLACE <<<<<<< SEARCH @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { val rootManager = ProjectRootManager.getInstance(environment.project) val fileIndex = rootManager.fileIndex val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!) val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.") val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.") // The working directory is as specified by the user in the working directory. // The fallback (if null) directory is the directory of the main file. val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path) val handler: ProcessHandler = KillableProcessHandler(commandLine) ======= @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.") val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.") // The working directory is as specified by the user in the working directory. // The fallback (if null or empty) directory is the directory of the main file. val bibPath = runConfig.bibWorkingDir?.path val commandLine = if (!(bibPath.equals("") || bibPath == null)) { GeneralCommandLine(command).withWorkDirectory(bibPath) } else { GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path) } val handler: ProcessHandler = KillableProcessHandler(commandLine) >>>>>>> REPLACE
kotlinx/kotlinx.html
84c5f26486bb10dcf9a1908434b5c44b5ee64368
shared/src/main/kotlin/trace-consumer.kt
kotlin
apache-2.0
Remove trace to Appendable as it is not working properly
package html4k.consumers import html4k.Tag import html4k.TagConsumer import java.util.ArrayList import java.util.Date class TraceConsumer<R>(val downstream : TagConsumer<R>, val out : Appendable) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" private val path = ArrayList<String>(1024) override fun onTagStart(tag: Tag) { downstream.onTagStart(tag) path.add(tag.tagName) out.append("[$id] open ${tag.tagName} path: ${path.join(" > ")}\n") } override fun onTagEnd(tag: Tag) { downstream.onTagEnd(tag) path.remove(path.lastIndex) out.append("[$id] close ${tag.tagName} path: ${path.join(" > ")}\n") } override fun finalize(): R { val v = downstream.finalize() out.append("[$id] finalized: ${v.toString()}\n") return v } } object PrintlnAppendable : Appendable { override fun append(csq: CharSequence?): Appendable { print(csq ?: "") return this } override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { print(csq?.subSequence(start, end) ?: "") return this } override fun append(c: Char): Appendable { print(c) return this } } public fun <R> TagConsumer<R>.trace(out : Appendable = PrintlnAppendable) : TagConsumer<R> = TraceConsumer(this, out)
package html4k.consumers import html4k.Tag import html4k.TagConsumer import java.util.ArrayList import java.util.Date class TraceConsumer<R>(val downstream : TagConsumer<R>) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" private val path = ArrayList<String>(1024) override fun onTagStart(tag: Tag) { downstream.onTagStart(tag) path.add(tag.tagName) println("[$id] open ${tag.tagName} path: ${path.join(" > ")}") } override fun onTagEnd(tag: Tag) { downstream.onTagEnd(tag) path.remove(path.lastIndex) println("[$id] close ${tag.tagName} path: ${path.join(" > ")}") } override fun finalize(): R { val v = downstream.finalize() println("[$id] finalized: ${v.toString()}") return v } } public fun <R> TagConsumer<R>.trace() : TagConsumer<R> = TraceConsumer(this)
5
22
5
mixed
--- a/shared/src/main/kotlin/trace-consumer.kt +++ b/shared/src/main/kotlin/trace-consumer.kt @@ -7,3 +7,3 @@ -class TraceConsumer<R>(val downstream : TagConsumer<R>, val out : Appendable) : TagConsumer<R> by downstream { +class TraceConsumer<R>(val downstream : TagConsumer<R>) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" @@ -15,3 +15,3 @@ - out.append("[$id] open ${tag.tagName} path: ${path.join(" > ")}\n") + println("[$id] open ${tag.tagName} path: ${path.join(" > ")}") } @@ -22,3 +22,3 @@ - out.append("[$id] close ${tag.tagName} path: ${path.join(" > ")}\n") + println("[$id] close ${tag.tagName} path: ${path.join(" > ")}") } @@ -28,3 +28,3 @@ - out.append("[$id] finalized: ${v.toString()}\n") + println("[$id] finalized: ${v.toString()}") @@ -34,19 +34,2 @@ -object PrintlnAppendable : Appendable { - override fun append(csq: CharSequence?): Appendable { - print(csq ?: "") - return this - } - - override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { - print(csq?.subSequence(start, end) ?: "") - return this - } - - override fun append(c: Char): Appendable { - print(c) - return this - } -} - -public fun <R> TagConsumer<R>.trace(out : Appendable = PrintlnAppendable) : TagConsumer<R> = TraceConsumer(this, out) +public fun <R> TagConsumer<R>.trace() : TagConsumer<R> = TraceConsumer(this)
--- a/shared/src/main/kotlin/trace-consumer.kt +++ b/shared/src/main/kotlin/trace-consumer.kt @@ ... @@ -class TraceConsumer<R>(val downstream : TagConsumer<R>, val out : Appendable) : TagConsumer<R> by downstream { +class TraceConsumer<R>(val downstream : TagConsumer<R>) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" @@ ... @@ - out.append("[$id] open ${tag.tagName} path: ${path.join(" > ")}\n") + println("[$id] open ${tag.tagName} path: ${path.join(" > ")}") } @@ ... @@ - out.append("[$id] close ${tag.tagName} path: ${path.join(" > ")}\n") + println("[$id] close ${tag.tagName} path: ${path.join(" > ")}") } @@ ... @@ - out.append("[$id] finalized: ${v.toString()}\n") + println("[$id] finalized: ${v.toString()}") @@ ... @@ -object PrintlnAppendable : Appendable { - override fun append(csq: CharSequence?): Appendable { - print(csq ?: "") - return this - } - - override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { - print(csq?.subSequence(start, end) ?: "") - return this - } - - override fun append(c: Char): Appendable { - print(c) - return this - } -} - -public fun <R> TagConsumer<R>.trace(out : Appendable = PrintlnAppendable) : TagConsumer<R> = TraceConsumer(this, out) +public fun <R> TagConsumer<R>.trace() : TagConsumer<R> = TraceConsumer(this)
--- a/shared/src/main/kotlin/trace-consumer.kt +++ b/shared/src/main/kotlin/trace-consumer.kt @@ -7,3 +7,3 @@ CON DEL class TraceConsumer<R>(val downstream : TagConsumer<R>, val out : Appendable) : TagConsumer<R> by downstream { ADD class TraceConsumer<R>(val downstream : TagConsumer<R>) : TagConsumer<R> by downstream { CON private val id = "ID-${Date().getTime() mod 16384}" @@ -15,3 +15,3 @@ CON DEL out.append("[$id] open ${tag.tagName} path: ${path.join(" > ")}\n") ADD println("[$id] open ${tag.tagName} path: ${path.join(" > ")}") CON } @@ -22,3 +22,3 @@ CON DEL out.append("[$id] close ${tag.tagName} path: ${path.join(" > ")}\n") ADD println("[$id] close ${tag.tagName} path: ${path.join(" > ")}") CON } @@ -28,3 +28,3 @@ CON DEL out.append("[$id] finalized: ${v.toString()}\n") ADD println("[$id] finalized: ${v.toString()}") CON @@ -34,19 +34,2 @@ CON DEL object PrintlnAppendable : Appendable { DEL override fun append(csq: CharSequence?): Appendable { DEL print(csq ?: "") DEL return this DEL } DEL DEL override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { DEL print(csq?.subSequence(start, end) ?: "") DEL return this DEL } DEL DEL override fun append(c: Char): Appendable { DEL print(c) DEL return this DEL } DEL } DEL DEL public fun <R> TagConsumer<R>.trace(out : Appendable = PrintlnAppendable) : TagConsumer<R> = TraceConsumer(this, out) ADD public fun <R> TagConsumer<R>.trace() : TagConsumer<R> = TraceConsumer(this)
<<<<<<< SEARCH import java.util.Date class TraceConsumer<R>(val downstream : TagConsumer<R>, val out : Appendable) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" private val path = ArrayList<String>(1024) ======= import java.util.Date class TraceConsumer<R>(val downstream : TagConsumer<R>) : TagConsumer<R> by downstream { private val id = "ID-${Date().getTime() mod 16384}" private val path = ArrayList<String>(1024) >>>>>>> REPLACE <<<<<<< SEARCH path.add(tag.tagName) out.append("[$id] open ${tag.tagName} path: ${path.join(" > ")}\n") } ======= path.add(tag.tagName) println("[$id] open ${tag.tagName} path: ${path.join(" > ")}") } >>>>>>> REPLACE <<<<<<< SEARCH path.remove(path.lastIndex) out.append("[$id] close ${tag.tagName} path: ${path.join(" > ")}\n") } override fun finalize(): R { val v = downstream.finalize() out.append("[$id] finalized: ${v.toString()}\n") return v } } object PrintlnAppendable : Appendable { override fun append(csq: CharSequence?): Appendable { print(csq ?: "") return this } override fun append(csq: CharSequence?, start: Int, end: Int): Appendable { print(csq?.subSequence(start, end) ?: "") return this } override fun append(c: Char): Appendable { print(c) return this } } public fun <R> TagConsumer<R>.trace(out : Appendable = PrintlnAppendable) : TagConsumer<R> = TraceConsumer(this, out) ======= path.remove(path.lastIndex) println("[$id] close ${tag.tagName} path: ${path.join(" > ")}") } override fun finalize(): R { val v = downstream.finalize() println("[$id] finalized: ${v.toString()}") return v } } public fun <R> TagConsumer<R>.trace() : TagConsumer<R> = TraceConsumer(this) >>>>>>> REPLACE
fulcrumapp/fulcrum-desktop
89f47cea38d8debf557518ed6ae9a9842cab8d50
src/main/sync/tasks/download-all-records.js
javascript
bsd-3-clause
Add --form <id> --form <id> --form <id> support to sync command to limit the forms that are sync'd.
import Task from './task'; import DownloadRecords from './download-records'; import DownloadPhotos from './download-photos'; import DownloadVideos from './download-videos'; import DownloadAudio from './download-audio'; import DownloadSignatures from './download-signatures'; // import DownloadPhotos from './download-photos'; export default class DownloadAllRecords extends Task { async run({account, dataSource}) { const forms = await account.findActiveForms(); for (const form of forms) { await new Promise((resolve, reject) => { form.load(dataSource, resolve); }); this.synchronizer.addTask(new DownloadRecords({form: form, ...this.synchronizer.taskParams})); } // download media here to make sure the tasks are ordered after the records this.synchronizer.addTask(new DownloadPhotos(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadVideos(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadAudio(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadSignatures(this.synchronizer.taskParams)); } }
import Task from './task'; import DownloadRecords from './download-records'; import DownloadPhotos from './download-photos'; import DownloadVideos from './download-videos'; import DownloadAudio from './download-audio'; import DownloadSignatures from './download-signatures'; import app from '../../app'; export default class DownloadAllRecords extends Task { async run({dataSource}) { const forms = await this.account.findActiveForms(); const includedForms = this.includedForms; for (const form of forms) { if (includedForms != null && includedForms.indexOf(form.id) === -1) { continue; } await new Promise((resolve, reject) => { form.load(dataSource, resolve); }); this.synchronizer.addTask(new DownloadRecords({form: form, ...this.synchronizer.taskParams})); } // download media here to make sure the tasks are ordered after the records this.synchronizer.addTask(new DownloadPhotos(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadVideos(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadAudio(this.synchronizer.taskParams)); this.synchronizer.addTask(new DownloadSignatures(this.synchronizer.taskParams)); } get includedForms() { if (app.args.form) { return Array.isArray(app.args.form) ? app.args.form : [ app.args.form ]; } return null; } }
17
3
2
mixed
--- a/src/main/sync/tasks/download-all-records.js +++ b/src/main/sync/tasks/download-all-records.js @@ -6,9 +6,15 @@ import DownloadSignatures from './download-signatures'; -// import DownloadPhotos from './download-photos'; +import app from '../../app'; export default class DownloadAllRecords extends Task { - async run({account, dataSource}) { - const forms = await account.findActiveForms(); + async run({dataSource}) { + const forms = await this.account.findActiveForms(); + + const includedForms = this.includedForms; for (const form of forms) { + if (includedForms != null && includedForms.indexOf(form.id) === -1) { + continue; + } + await new Promise((resolve, reject) => { @@ -26,2 +32,10 @@ } + + get includedForms() { + if (app.args.form) { + return Array.isArray(app.args.form) ? app.args.form : [ app.args.form ]; + } + + return null; + } }
--- a/src/main/sync/tasks/download-all-records.js +++ b/src/main/sync/tasks/download-all-records.js @@ ... @@ import DownloadSignatures from './download-signatures'; -// import DownloadPhotos from './download-photos'; +import app from '../../app'; export default class DownloadAllRecords extends Task { - async run({account, dataSource}) { - const forms = await account.findActiveForms(); + async run({dataSource}) { + const forms = await this.account.findActiveForms(); + + const includedForms = this.includedForms; for (const form of forms) { + if (includedForms != null && includedForms.indexOf(form.id) === -1) { + continue; + } + await new Promise((resolve, reject) => { @@ ... @@ } + + get includedForms() { + if (app.args.form) { + return Array.isArray(app.args.form) ? app.args.form : [ app.args.form ]; + } + + return null; + } }
--- a/src/main/sync/tasks/download-all-records.js +++ b/src/main/sync/tasks/download-all-records.js @@ -6,9 +6,15 @@ CON import DownloadSignatures from './download-signatures'; DEL // import DownloadPhotos from './download-photos'; ADD import app from '../../app'; CON CON export default class DownloadAllRecords extends Task { DEL async run({account, dataSource}) { DEL const forms = await account.findActiveForms(); ADD async run({dataSource}) { ADD const forms = await this.account.findActiveForms(); ADD ADD const includedForms = this.includedForms; CON CON for (const form of forms) { ADD if (includedForms != null && includedForms.indexOf(form.id) === -1) { ADD continue; ADD } ADD CON await new Promise((resolve, reject) => { @@ -26,2 +32,10 @@ CON } ADD ADD get includedForms() { ADD if (app.args.form) { ADD return Array.isArray(app.args.form) ? app.args.form : [ app.args.form ]; ADD } ADD ADD return null; ADD } CON }
<<<<<<< SEARCH import DownloadAudio from './download-audio'; import DownloadSignatures from './download-signatures'; // import DownloadPhotos from './download-photos'; export default class DownloadAllRecords extends Task { async run({account, dataSource}) { const forms = await account.findActiveForms(); for (const form of forms) { await new Promise((resolve, reject) => { form.load(dataSource, resolve); ======= import DownloadAudio from './download-audio'; import DownloadSignatures from './download-signatures'; import app from '../../app'; export default class DownloadAllRecords extends Task { async run({dataSource}) { const forms = await this.account.findActiveForms(); const includedForms = this.includedForms; for (const form of forms) { if (includedForms != null && includedForms.indexOf(form.id) === -1) { continue; } await new Promise((resolve, reject) => { form.load(dataSource, resolve); >>>>>>> REPLACE <<<<<<< SEARCH this.synchronizer.addTask(new DownloadSignatures(this.synchronizer.taskParams)); } } ======= this.synchronizer.addTask(new DownloadSignatures(this.synchronizer.taskParams)); } get includedForms() { if (app.args.form) { return Array.isArray(app.args.form) ? app.args.form : [ app.args.form ]; } return null; } } >>>>>>> REPLACE
waltermoreira/tartpy
9ec80ed117ca393a63bf7eb739b4702bfbc0884e
tartpy/eventloop.py
python
mit
Add function to schedule later
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_forever(self, wait=0.05): while True: self.run() time.sleep(wait) def run_in_thread(self): self.thread = threading.Thread(target=self.run_forever, name='event_loop') self.thread.daemon = True self.thread.start()
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def later(self, delay, event): self.scheduler.enter(delay, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_forever(self, wait=0.05): while True: self.run() time.sleep(wait) def run_in_thread(self): self.thread = threading.Thread(target=self.run_forever, name='event_loop') self.thread.daemon = True self.thread.start()
3
0
1
add_only
--- a/tartpy/eventloop.py +++ b/tartpy/eventloop.py @@ -36,2 +36,5 @@ + def later(self, delay, event): + self.scheduler.enter(delay, 1, event) + def stop(self):
--- a/tartpy/eventloop.py +++ b/tartpy/eventloop.py @@ ... @@ + def later(self, delay, event): + self.scheduler.enter(delay, 1, event) + def stop(self):
--- a/tartpy/eventloop.py +++ b/tartpy/eventloop.py @@ -36,2 +36,5 @@ CON ADD def later(self, delay, event): ADD self.scheduler.enter(delay, 1, event) ADD CON def stop(self):
<<<<<<< SEARCH self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" ======= self.scheduler.enter(0, 1, event) def later(self, delay, event): self.scheduler.enter(delay, 1, event) def stop(self): """Stop the loop.""" >>>>>>> REPLACE
vpavic/spring-boot
55ad2b93718b5c2fd9766e2ff0cb867a4ff0110b
spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java
java
apache-2.0
Remove accidentally committed debug code
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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 smoketest.batch; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(OutputCaptureExtension.class) class SampleBatchApplicationTests { @Test void testDefaultSettings(CapturedOutput output) { assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); assertThat(output).contains("completed with the following parameters"); } public static void main(String[] args) throws ClassNotFoundException { System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v)); Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory"); } }
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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 smoketest.batch; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(OutputCaptureExtension.class) class SampleBatchApplicationTests { @Test void testDefaultSettings(CapturedOutput output) { assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); assertThat(output).contains("completed with the following parameters"); } }
0
5
1
del_only
--- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java @@ -36,7 +36,2 @@ - public static void main(String[] args) throws ClassNotFoundException { - System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v)); - Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory"); - } - }
--- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java @@ ... @@ - public static void main(String[] args) throws ClassNotFoundException { - System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v)); - Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory"); - } - }
--- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-batch/src/test/java/smoketest/batch/SampleBatchApplicationTests.java @@ -36,7 +36,2 @@ CON DEL public static void main(String[] args) throws ClassNotFoundException { DEL System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v)); DEL Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory"); DEL } DEL CON }
<<<<<<< SEARCH } public static void main(String[] args) throws ClassNotFoundException { System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v)); Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory"); } } ======= } } >>>>>>> REPLACE
ruma/ruma
bb52edf1e0cf0f2232d725af7afb69fb1ebba7e8
src/r0/media/get_content.rs
rust
mit
Add allow_remote parameter to content fetching endpoint. Fixes #92.
//! Endpoints for the media repository. //! [GET /_matrix/media/r0/download/{serverName}/{mediaId}](https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-media-r0-download-servername-mediaid) use ruma_api::ruma_api; ruma_api! { metadata { description: "Retrieve content from the media store.", method: GET, name: "get_media_content", path: "/_matrix/media/r0/download/:server_name/:media_id", rate_limited: false, requires_authentication: false, } request { /// The media ID from the mxc:// URI (the path component). #[ruma_api(path)] pub media_id: String, /// The server name from the mxc:// URI (the authoritory component). #[ruma_api(path)] pub server_name: String, } response { /// The content that was previously uploaded. #[ruma_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[ruma_api(header = CONTENT_TYPE)] pub content_type: String, /// The name of the file that was previously uploaded, if set. #[ruma_api(header = CONTENT_DISPOSITION)] pub content_disposition: String, } }
//! Endpoints for the media repository. //! [GET /_matrix/media/r0/download/{serverName}/{mediaId}](https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-media-r0-download-servername-mediaid) use ruma_api::ruma_api; ruma_api! { metadata { description: "Retrieve content from the media store.", method: GET, name: "get_media_content", path: "/_matrix/media/r0/download/:server_name/:media_id", rate_limited: false, requires_authentication: false, } request { /// The media ID from the mxc:// URI (the path component). #[ruma_api(path)] pub media_id: String, /// The server name from the mxc:// URI (the authoritory component). #[ruma_api(path)] pub server_name: String, /// Whether to fetch media deemed remote. /// Used to prevent routing loops. Defaults to `true`. #[ruma_api(query)] pub allow_remote: Option<bool>, } response { /// The content that was previously uploaded. #[ruma_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[ruma_api(header = CONTENT_TYPE)] pub content_type: String, /// The name of the file that was previously uploaded, if set. #[ruma_api(header = CONTENT_DISPOSITION)] pub content_disposition: String, } }
4
0
1
add_only
--- a/src/r0/media/get_content.rs +++ b/src/r0/media/get_content.rs @@ -23,2 +23,6 @@ pub server_name: String, + /// Whether to fetch media deemed remote. + /// Used to prevent routing loops. Defaults to `true`. + #[ruma_api(query)] + pub allow_remote: Option<bool>, }
--- a/src/r0/media/get_content.rs +++ b/src/r0/media/get_content.rs @@ ... @@ pub server_name: String, + /// Whether to fetch media deemed remote. + /// Used to prevent routing loops. Defaults to `true`. + #[ruma_api(query)] + pub allow_remote: Option<bool>, }
--- a/src/r0/media/get_content.rs +++ b/src/r0/media/get_content.rs @@ -23,2 +23,6 @@ CON pub server_name: String, ADD /// Whether to fetch media deemed remote. ADD /// Used to prevent routing loops. Defaults to `true`. ADD #[ruma_api(query)] ADD pub allow_remote: Option<bool>, CON }
<<<<<<< SEARCH #[ruma_api(path)] pub server_name: String, } ======= #[ruma_api(path)] pub server_name: String, /// Whether to fetch media deemed remote. /// Used to prevent routing loops. Defaults to `true`. #[ruma_api(query)] pub allow_remote: Option<bool>, } >>>>>>> REPLACE
wbond/oscrypto
3410fba1c8a39156def029eac9c7ff9f779832e6
dev/ci.py
python
mit
Fix CI to ignore system install of asn1crypto
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In case any of the deps are installed system-wide sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
2
0
1
add_only
--- a/dev/ci.py +++ b/dev/ci.py @@ -14,2 +14,4 @@ site.addsitedir(deps_dir) + # In case any of the deps are installed system-wide + sys.path.insert(0, deps_dir)
--- a/dev/ci.py +++ b/dev/ci.py @@ ... @@ site.addsitedir(deps_dir) + # In case any of the deps are installed system-wide + sys.path.insert(0, deps_dir)
--- a/dev/ci.py +++ b/dev/ci.py @@ -14,2 +14,4 @@ CON site.addsitedir(deps_dir) ADD # In case any of the deps are installed system-wide ADD sys.path.insert(0, deps_dir) CON
<<<<<<< SEARCH if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: ======= if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In case any of the deps are installed system-wide sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: >>>>>>> REPLACE
mrkirby153/KirBot
6c052090669a87e71a0682ea91087905a90f8e44
src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt
kotlin
mit
Add support for changing volume by an amount Instead of setting the volume, prefixing the volume with "+" will increase the volume by that amount, "-" will decrease the volume
package me.mrkirby153.KirBot.command.executors.music import me.mrkirby153.KirBot.command.Command import me.mrkirby153.KirBot.user.Clearance import net.dv8tion.jda.core.entities.Message @Command(name = "volume", description = "Change the volume of the robot", clearance = Clearance.BOT_MANAGER) class CommandVolume : MusicCommand() { override fun exec(message: Message, args: Array<String>) { if(args.isEmpty()){ message.send().error("Please specify a volume!").queue() return } val volume = Math.min(150, Math.max(args[0].toInt(), 0)) server.musicManager.audioPlayer.volume = volume message.send().info("Set volume to __**$volume**__").queue() } }
package me.mrkirby153.KirBot.command.executors.music import me.mrkirby153.KirBot.command.Command import me.mrkirby153.KirBot.user.Clearance import net.dv8tion.jda.core.entities.Message @Command(name = "volume", description = "Change the volume of the robot", clearance = Clearance.BOT_MANAGER) class CommandVolume : MusicCommand() { override fun exec(message: Message, args: Array<String>) { val audioPlayer = server.musicManager.audioPlayer if (args.isEmpty()) { message.send().info("Current Volume: **${audioPlayer.volume}**").queue() return } var add = false var sub = false var num = args[0] if (num.startsWith("+")) { num = num.substring(1) add = true } else if (num.startsWith("-")) { num = num.substring(1) sub = true } val volume = Math.min(150, Math.max(num.toInt(), 0)) if (add) { audioPlayer.volume += volume } else if (sub) { audioPlayer.volume -= volume } else { audioPlayer.volume = volume } message.send().info("Set volume to __**${audioPlayer.volume}**__").queue() } }
25
5
2
mixed
--- a/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt +++ b/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt @@ -10,4 +10,5 @@ override fun exec(message: Message, args: Array<String>) { - if(args.isEmpty()){ - message.send().error("Please specify a volume!").queue() + val audioPlayer = server.musicManager.audioPlayer + if (args.isEmpty()) { + message.send().info("Current Volume: **${audioPlayer.volume}**").queue() return @@ -15,6 +16,25 @@ - val volume = Math.min(150, Math.max(args[0].toInt(), 0)) + var add = false + var sub = false - server.musicManager.audioPlayer.volume = volume - message.send().info("Set volume to __**$volume**__").queue() + var num = args[0] + if (num.startsWith("+")) { + num = num.substring(1) + add = true + } else if (num.startsWith("-")) { + num = num.substring(1) + sub = true + } + + val volume = Math.min(150, Math.max(num.toInt(), 0)) + + if (add) { + audioPlayer.volume += volume + } else if (sub) { + audioPlayer.volume -= volume + } else { + + audioPlayer.volume = volume + } + message.send().info("Set volume to __**${audioPlayer.volume}**__").queue() }
--- a/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt +++ b/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt @@ ... @@ override fun exec(message: Message, args: Array<String>) { - if(args.isEmpty()){ - message.send().error("Please specify a volume!").queue() + val audioPlayer = server.musicManager.audioPlayer + if (args.isEmpty()) { + message.send().info("Current Volume: **${audioPlayer.volume}**").queue() return @@ ... @@ - val volume = Math.min(150, Math.max(args[0].toInt(), 0)) + var add = false + var sub = false - server.musicManager.audioPlayer.volume = volume - message.send().info("Set volume to __**$volume**__").queue() + var num = args[0] + if (num.startsWith("+")) { + num = num.substring(1) + add = true + } else if (num.startsWith("-")) { + num = num.substring(1) + sub = true + } + + val volume = Math.min(150, Math.max(num.toInt(), 0)) + + if (add) { + audioPlayer.volume += volume + } else if (sub) { + audioPlayer.volume -= volume + } else { + + audioPlayer.volume = volume + } + message.send().info("Set volume to __**${audioPlayer.volume}**__").queue() }
--- a/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt +++ b/src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandVolume.kt @@ -10,4 +10,5 @@ CON override fun exec(message: Message, args: Array<String>) { DEL if(args.isEmpty()){ DEL message.send().error("Please specify a volume!").queue() ADD val audioPlayer = server.musicManager.audioPlayer ADD if (args.isEmpty()) { ADD message.send().info("Current Volume: **${audioPlayer.volume}**").queue() CON return @@ -15,6 +16,25 @@ CON DEL val volume = Math.min(150, Math.max(args[0].toInt(), 0)) ADD var add = false ADD var sub = false CON DEL server.musicManager.audioPlayer.volume = volume DEL message.send().info("Set volume to __**$volume**__").queue() ADD var num = args[0] ADD if (num.startsWith("+")) { ADD num = num.substring(1) ADD add = true ADD } else if (num.startsWith("-")) { ADD num = num.substring(1) ADD sub = true ADD } ADD ADD val volume = Math.min(150, Math.max(num.toInt(), 0)) ADD ADD if (add) { ADD audioPlayer.volume += volume ADD } else if (sub) { ADD audioPlayer.volume -= volume ADD } else { ADD ADD audioPlayer.volume = volume ADD } ADD message.send().info("Set volume to __**${audioPlayer.volume}**__").queue() CON }
<<<<<<< SEARCH override fun exec(message: Message, args: Array<String>) { if(args.isEmpty()){ message.send().error("Please specify a volume!").queue() return } val volume = Math.min(150, Math.max(args[0].toInt(), 0)) server.musicManager.audioPlayer.volume = volume message.send().info("Set volume to __**$volume**__").queue() } } ======= override fun exec(message: Message, args: Array<String>) { val audioPlayer = server.musicManager.audioPlayer if (args.isEmpty()) { message.send().info("Current Volume: **${audioPlayer.volume}**").queue() return } var add = false var sub = false var num = args[0] if (num.startsWith("+")) { num = num.substring(1) add = true } else if (num.startsWith("-")) { num = num.substring(1) sub = true } val volume = Math.min(150, Math.max(num.toInt(), 0)) if (add) { audioPlayer.volume += volume } else if (sub) { audioPlayer.volume -= volume } else { audioPlayer.volume = volume } message.send().info("Set volume to __**${audioPlayer.volume}**__").queue() } } >>>>>>> REPLACE
cryvate/project-euler
853d2907432a8d7fbedbed12ff28efbe520d4c80
project_euler/library/number_theory/continued_fractions.py
python
mit
Make continued fractions sqrt much faster
from fractions import Fraction from math import sqrt from itertools import chain, cycle from typing import Generator, Iterable, List, Tuple def convergent_sequence(generator: Iterable[int]) -> \ Generator[Fraction, None, None]: h = (0, 1) k = (1, 0) for a in generator: h = h[1], a * h[1] + h[0] k = k[1], a * k[1] + k[0] yield Fraction(h[-1], k[-1]) def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: remainders = [] continued_fraction = [] remainder = (Fraction(1), Fraction(0)) # remainder is sqrt(n) + 0. sqrt_n = sqrt(n) while remainder not in remainders: remainders.append(remainder) a = int(remainder[0] * sqrt_n + remainder[1]) continued_fraction.append(a) norm = (remainder[1] - a) ** 2 - remainder[0] ** 2 * n remainder = (-remainder[0] / norm, (remainder[1] - a) / norm) index = remainders.index(remainder) return continued_fraction[:index], continued_fraction[index:] def convergents_sqrt(n: int) -> Generator[Fraction, None, None]: initial, repeat = continued_fraction_sqrt(n) convergents = convergent_sequence(chain(initial, cycle(repeat))) yield from convergents
from fractions import Fraction from math import sqrt from itertools import chain, cycle from typing import Generator, Iterable, List, Tuple from .gcd import gcd from ..sqrt import fsqrt def convergent_sequence(generator: Iterable[int]) -> \ Generator[Fraction, None, None]: h = (0, 1) k = (1, 0) for a in generator: h = h[1], a * h[1] + h[0] k = k[1], a * k[1] + k[0] yield Fraction(h[-1], k[-1]) def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: sqrt_n = sqrt(n) remainders = [] remainder = (0, 1) # remainder is an + (sqrt(n) - p) / q and these are initial. continued_fraction = [] while remainder not in remainders: remainders.append(remainder) p, q = remainder q = (n - (p * p)) // q a = int((sqrt_n + p) / q) p = a * q - p continued_fraction.append(a) remainder = (p, q) index = remainders.index(remainder) return continued_fraction[1:index], continued_fraction[index:] def convergents_sqrt(n: int) -> Generator[Fraction, None, None]: initial, repeat = continued_fraction_sqrt(n) convergents = convergent_sequence(chain(initial, cycle(repeat))) yield from convergents
13
7
4
mixed
--- a/project_euler/library/number_theory/continued_fractions.py +++ b/project_euler/library/number_theory/continued_fractions.py @@ -5,2 +5,5 @@ from typing import Generator, Iterable, List, Tuple + +from .gcd import gcd +from ..sqrt import fsqrt @@ -20,7 +23,7 @@ def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: + sqrt_n = sqrt(n) remainders = [] + remainder = (0, 1) + # remainder is an + (sqrt(n) - p) / q and these are initial. continued_fraction = [] - remainder = (Fraction(1), Fraction(0)) # remainder is sqrt(n) + 0. - - sqrt_n = sqrt(n) @@ -28,8 +31,11 @@ remainders.append(remainder) + p, q = remainder - a = int(remainder[0] * sqrt_n + remainder[1]) + q = (n - (p * p)) // q + a = int((sqrt_n + p) / q) + p = a * q - p + continued_fraction.append(a) - norm = (remainder[1] - a) ** 2 - remainder[0] ** 2 * n - remainder = (-remainder[0] / norm, (remainder[1] - a) / norm) + remainder = (p, q) @@ -37,3 +43,3 @@ - return continued_fraction[:index], continued_fraction[index:] + return continued_fraction[1:index], continued_fraction[index:]
--- a/project_euler/library/number_theory/continued_fractions.py +++ b/project_euler/library/number_theory/continued_fractions.py @@ ... @@ from typing import Generator, Iterable, List, Tuple + +from .gcd import gcd +from ..sqrt import fsqrt @@ ... @@ def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: + sqrt_n = sqrt(n) remainders = [] + remainder = (0, 1) + # remainder is an + (sqrt(n) - p) / q and these are initial. continued_fraction = [] - remainder = (Fraction(1), Fraction(0)) # remainder is sqrt(n) + 0. - - sqrt_n = sqrt(n) @@ ... @@ remainders.append(remainder) + p, q = remainder - a = int(remainder[0] * sqrt_n + remainder[1]) + q = (n - (p * p)) // q + a = int((sqrt_n + p) / q) + p = a * q - p + continued_fraction.append(a) - norm = (remainder[1] - a) ** 2 - remainder[0] ** 2 * n - remainder = (-remainder[0] / norm, (remainder[1] - a) / norm) + remainder = (p, q) @@ ... @@ - return continued_fraction[:index], continued_fraction[index:] + return continued_fraction[1:index], continued_fraction[index:]
--- a/project_euler/library/number_theory/continued_fractions.py +++ b/project_euler/library/number_theory/continued_fractions.py @@ -5,2 +5,5 @@ CON from typing import Generator, Iterable, List, Tuple ADD ADD from .gcd import gcd ADD from ..sqrt import fsqrt CON @@ -20,7 +23,7 @@ CON def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: ADD sqrt_n = sqrt(n) CON remainders = [] ADD remainder = (0, 1) ADD # remainder is an + (sqrt(n) - p) / q and these are initial. CON continued_fraction = [] DEL remainder = (Fraction(1), Fraction(0)) # remainder is sqrt(n) + 0. DEL DEL sqrt_n = sqrt(n) CON @@ -28,8 +31,11 @@ CON remainders.append(remainder) ADD p, q = remainder CON DEL a = int(remainder[0] * sqrt_n + remainder[1]) ADD q = (n - (p * p)) // q ADD a = int((sqrt_n + p) / q) ADD p = a * q - p ADD CON continued_fraction.append(a) CON DEL norm = (remainder[1] - a) ** 2 - remainder[0] ** 2 * n DEL remainder = (-remainder[0] / norm, (remainder[1] - a) / norm) ADD remainder = (p, q) CON @@ -37,3 +43,3 @@ CON DEL return continued_fraction[:index], continued_fraction[index:] ADD return continued_fraction[1:index], continued_fraction[index:] CON
<<<<<<< SEARCH from typing import Generator, Iterable, List, Tuple ======= from typing import Generator, Iterable, List, Tuple from .gcd import gcd from ..sqrt import fsqrt >>>>>>> REPLACE <<<<<<< SEARCH def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: remainders = [] continued_fraction = [] remainder = (Fraction(1), Fraction(0)) # remainder is sqrt(n) + 0. sqrt_n = sqrt(n) while remainder not in remainders: remainders.append(remainder) a = int(remainder[0] * sqrt_n + remainder[1]) continued_fraction.append(a) norm = (remainder[1] - a) ** 2 - remainder[0] ** 2 * n remainder = (-remainder[0] / norm, (remainder[1] - a) / norm) index = remainders.index(remainder) return continued_fraction[:index], continued_fraction[index:] ======= def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: sqrt_n = sqrt(n) remainders = [] remainder = (0, 1) # remainder is an + (sqrt(n) - p) / q and these are initial. continued_fraction = [] while remainder not in remainders: remainders.append(remainder) p, q = remainder q = (n - (p * p)) // q a = int((sqrt_n + p) / q) p = a * q - p continued_fraction.append(a) remainder = (p, q) index = remainders.index(remainder) return continued_fraction[1:index], continued_fraction[index:] >>>>>>> REPLACE
samkelleher/cordova-plugin-applepay
ee7dff37f9186900b588e2918399415d5a80d583
www/applepay.js
javascript
apache-2.0
Correct status variable. All methods now return promises, as well as execute the callback.
var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); var ApplePay = { canMakePayments: function(successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'canMakePayments', []); }, makePaymentRequest: function(order, successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'makePaymentRequest', [order]); }, completeLastTransaction: function(status, successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'completeLastTransaction', [order]); } }; module.exports = ApplePay;
var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); var ApplePay = { canMakePayments: function(successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'canMakePayments', []); }); }, makePaymentRequest: function(order, successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'makePaymentRequest', [order]); }); }, completeLastTransaction: function(status, successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'completeLastTransaction', [status]); }); } }; module.exports = ApplePay;
33
4
2
mixed
--- a/www/applepay.js +++ b/www/applepay.js @@ -8,7 +8,26 @@ canMakePayments: function(successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'canMakePayments', []); - }, + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'canMakePayments', []); + }); + + }, makePaymentRequest: function(order, successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'makePaymentRequest', [order]); + + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'makePaymentRequest', [order]); + }); + }, @@ -16,3 +35,13 @@ completeLastTransaction: function(status, successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'completeLastTransaction', [order]); + + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'completeLastTransaction', [status]); + }); + }
--- a/www/applepay.js +++ b/www/applepay.js @@ ... @@ canMakePayments: function(successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'canMakePayments', []); - }, + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'canMakePayments', []); + }); + + }, makePaymentRequest: function(order, successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'makePaymentRequest', [order]); + + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'makePaymentRequest', [order]); + }); + }, @@ ... @@ completeLastTransaction: function(status, successCallback, errorCallback) { - exec(successCallback, errorCallback, 'ApplePay', 'completeLastTransaction', [order]); + + return new Promise(function(resolve, reject) { + exec(function(message) { + successCallback(message); + resolve(message); + }, function(message) { + errorCallback(message); + reject(message); + }, 'ApplePay', 'completeLastTransaction', [status]); + }); + }
--- a/www/applepay.js +++ b/www/applepay.js @@ -8,7 +8,26 @@ CON canMakePayments: function(successCallback, errorCallback) { DEL exec(successCallback, errorCallback, 'ApplePay', 'canMakePayments', []); DEL }, ADD return new Promise(function(resolve, reject) { ADD exec(function(message) { ADD successCallback(message); ADD resolve(message); ADD }, function(message) { ADD errorCallback(message); ADD reject(message); ADD }, 'ApplePay', 'canMakePayments', []); ADD }); ADD ADD }, CON CON makePaymentRequest: function(order, successCallback, errorCallback) { DEL exec(successCallback, errorCallback, 'ApplePay', 'makePaymentRequest', [order]); ADD ADD return new Promise(function(resolve, reject) { ADD exec(function(message) { ADD successCallback(message); ADD resolve(message); ADD }, function(message) { ADD errorCallback(message); ADD reject(message); ADD }, 'ApplePay', 'makePaymentRequest', [order]); ADD }); ADD CON }, @@ -16,3 +35,13 @@ CON completeLastTransaction: function(status, successCallback, errorCallback) { DEL exec(successCallback, errorCallback, 'ApplePay', 'completeLastTransaction', [order]); ADD ADD return new Promise(function(resolve, reject) { ADD exec(function(message) { ADD successCallback(message); ADD resolve(message); ADD }, function(message) { ADD errorCallback(message); ADD reject(message); ADD }, 'ApplePay', 'completeLastTransaction', [status]); ADD }); ADD CON }
<<<<<<< SEARCH canMakePayments: function(successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'canMakePayments', []); }, makePaymentRequest: function(order, successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'makePaymentRequest', [order]); }, completeLastTransaction: function(status, successCallback, errorCallback) { exec(successCallback, errorCallback, 'ApplePay', 'completeLastTransaction', [order]); } ======= canMakePayments: function(successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'canMakePayments', []); }); }, makePaymentRequest: function(order, successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'makePaymentRequest', [order]); }); }, completeLastTransaction: function(status, successCallback, errorCallback) { return new Promise(function(resolve, reject) { exec(function(message) { successCallback(message); resolve(message); }, function(message) { errorCallback(message); reject(message); }, 'ApplePay', 'completeLastTransaction', [status]); }); } >>>>>>> REPLACE
minecraft-dev/MinecraftDev
62ddda99ef7ce1482aba4f967b0c496d43b15fff
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt
kotlin
mit
mixin: Allow using array types instead of varargs for injectors
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.injector import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.isErasureEquivalentTo import com.intellij.psi.PsiParameter data class ParameterGroup(val parameters: List<Parameter>?, val required: Boolean = parameters != null, val default: Boolean = required) { val size get() = this.parameters?.size ?: 0 val wildcard get() = this.parameters == null fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean { if (this.parameters == null) { // Wildcard parameter groups always match return true } // Check if remaining parameter count is enough if (currentPosition + size > parameters.size) { return false } var pos = currentPosition // Check parameter types for ((_, type) in this.parameters) { if (!type.isErasureEquivalentTo(parameters[pos++].type)) { return false } } return true } }
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.injector import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.isErasureEquivalentTo import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiEllipsisType import com.intellij.psi.PsiParameter data class ParameterGroup(val parameters: List<Parameter>?, val required: Boolean = parameters != null, val default: Boolean = required) { val size get() = this.parameters?.size ?: 0 fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean { if (this.parameters == null) { // Wildcard parameter groups always match return true } // Check if remaining parameter count is enough if (currentPosition + size > parameters.size) { return false } var pos = currentPosition // Check parameter types for ((_, type) in this.parameters) { val expectedType = parameters[pos++].type if (!type.isErasureEquivalentTo(expectedType)) { // Allow using array instead of varargs if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) { return false } } } return true } }
8
5
3
mixed
--- a/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt +++ b/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt @@ -14,2 +14,4 @@ import com.demonwav.mcdev.util.isErasureEquivalentTo +import com.intellij.psi.PsiArrayType +import com.intellij.psi.PsiEllipsisType import com.intellij.psi.PsiParameter @@ -22,5 +24,2 @@ get() = this.parameters?.size ?: 0 - - val wildcard - get() = this.parameters == null @@ -41,4 +40,8 @@ for ((_, type) in this.parameters) { - if (!type.isErasureEquivalentTo(parameters[pos++].type)) { - return false + val expectedType = parameters[pos++].type + if (!type.isErasureEquivalentTo(expectedType)) { + // Allow using array instead of varargs + if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) { + return false + } }
--- a/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt +++ b/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt @@ ... @@ import com.demonwav.mcdev.util.isErasureEquivalentTo +import com.intellij.psi.PsiArrayType +import com.intellij.psi.PsiEllipsisType import com.intellij.psi.PsiParameter @@ ... @@ get() = this.parameters?.size ?: 0 - - val wildcard - get() = this.parameters == null @@ ... @@ for ((_, type) in this.parameters) { - if (!type.isErasureEquivalentTo(parameters[pos++].type)) { - return false + val expectedType = parameters[pos++].type + if (!type.isErasureEquivalentTo(expectedType)) { + // Allow using array instead of varargs + if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) { + return false + } }
--- a/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt +++ b/src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/injector/ParameterGroup.kt @@ -14,2 +14,4 @@ CON import com.demonwav.mcdev.util.isErasureEquivalentTo ADD import com.intellij.psi.PsiArrayType ADD import com.intellij.psi.PsiEllipsisType CON import com.intellij.psi.PsiParameter @@ -22,5 +24,2 @@ CON get() = this.parameters?.size ?: 0 DEL DEL val wildcard DEL get() = this.parameters == null CON @@ -41,4 +40,8 @@ CON for ((_, type) in this.parameters) { DEL if (!type.isErasureEquivalentTo(parameters[pos++].type)) { DEL return false ADD val expectedType = parameters[pos++].type ADD if (!type.isErasureEquivalentTo(expectedType)) { ADD // Allow using array instead of varargs ADD if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) { ADD return false ADD } CON }
<<<<<<< SEARCH import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.isErasureEquivalentTo import com.intellij.psi.PsiParameter ======= import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.isErasureEquivalentTo import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiEllipsisType import com.intellij.psi.PsiParameter >>>>>>> REPLACE <<<<<<< SEARCH val size get() = this.parameters?.size ?: 0 val wildcard get() = this.parameters == null fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean { ======= val size get() = this.parameters?.size ?: 0 fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean { >>>>>>> REPLACE <<<<<<< SEARCH // Check parameter types for ((_, type) in this.parameters) { if (!type.isErasureEquivalentTo(parameters[pos++].type)) { return false } } ======= // Check parameter types for ((_, type) in this.parameters) { val expectedType = parameters[pos++].type if (!type.isErasureEquivalentTo(expectedType)) { // Allow using array instead of varargs if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) { return false } } } >>>>>>> REPLACE
RealGeeks/asyncmongo
7955e777d6ba3bbbd104bd3916f131ab7fa8f8b5
asyncmongo/__init__.py
python
apache-2.0
Support Sort Order For TEXT Index
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
2
0
1
add_only
--- a/asyncmongo/__init__.py +++ b/asyncmongo/__init__.py @@ -35,2 +35,4 @@ """Index specifier for a 2-dimensional `geospatial index`""" +TEXT = '{ $meta: "textScore" }' +"""TEXT Index sort order."""
--- a/asyncmongo/__init__.py +++ b/asyncmongo/__init__.py @@ ... @@ """Index specifier for a 2-dimensional `geospatial index`""" +TEXT = '{ $meta: "textScore" }' +"""TEXT Index sort order."""
--- a/asyncmongo/__init__.py +++ b/asyncmongo/__init__.py @@ -35,2 +35,4 @@ CON """Index specifier for a 2-dimensional `geospatial index`""" ADD TEXT = '{ $meta: "textScore" }' ADD """TEXT Index sort order.""" CON
<<<<<<< SEARCH GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, ======= GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = '{ $meta: "textScore" }' """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, >>>>>>> REPLACE
FilipNest/stripytext
5e19ad66bcdb4985acb3a21ed894708e93a55a3d
stripytext.js
javascript
mit
Hide stripes from screen readers
var stripy = function (element, stripes) { element.style.position = "relative"; element.style.display = "block"; var text = element.innerHTML; var newstripe = function (size, name) { var stripe = document.createElement("span"); stripe.setAttribute("data-stripe", name); stripe.style.position = "absolute"; stripe.style.height = size + "%"; stripe.style.overflow = "hidden"; stripe.innerHTML = text; return stripe; }; var percent = 100 / stripes; var current = 0; var i = 0; while (current < 100) { current += percent; current = Math.floor(current); element.insertBefore(newstripe(current, i), element.firstChild); i += 1; }; };
var stripy = function (element, stripes) { element.style.position = "relative"; element.style.display = "block"; var text = element.innerHTML; var newstripe = function (size, name) { var stripe = document.createElement("span"); stripe.setAttribute("data-stripe", name); stripe.setAttribute("aria-hidden", "true"); stripe.style.position = "absolute"; stripe.style.height = size + "%"; stripe.style.overflow = "hidden"; stripe.innerHTML = text; return stripe; }; var percent = 100 / stripes; var current = 0; var i = 0; while (current < 100) { current += percent; current = Math.floor(current); element.insertBefore(newstripe(current, i), element.firstChild); i += 1; }; };
2
0
1
add_only
--- a/stripytext.js +++ b/stripytext.js @@ -12,2 +12,4 @@ stripe.setAttribute("data-stripe", name); + + stripe.setAttribute("aria-hidden", "true");
--- a/stripytext.js +++ b/stripytext.js @@ ... @@ stripe.setAttribute("data-stripe", name); + + stripe.setAttribute("aria-hidden", "true");
--- a/stripytext.js +++ b/stripytext.js @@ -12,2 +12,4 @@ CON stripe.setAttribute("data-stripe", name); ADD ADD stripe.setAttribute("aria-hidden", "true"); CON
<<<<<<< SEARCH stripe.setAttribute("data-stripe", name); stripe.style.position = "absolute"; ======= stripe.setAttribute("data-stripe", name); stripe.setAttribute("aria-hidden", "true"); stripe.style.position = "absolute"; >>>>>>> REPLACE
kylewlacy/glitter
11d3c647b045db9f9c6628374695a07d54951a51
src/index_data.rs
rust
apache-2.0
Add impl of `IndexData` for arrays of `IndexDatum`s
pub use std::mem; pub use std::slice; pub enum IndexDatumType { UnsignedByte, UnsignedShort } pub trait IndexData { fn index_datum_type() -> IndexDatumType; fn index_bytes(&self) -> &[u8]; fn index_elements(&self) -> usize; } pub trait IndexDatum { fn index_datum_type() -> IndexDatumType; } impl IndexDatum for u8 { fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedByte } } impl IndexDatum for u16 { fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedShort } }
pub use std::mem; pub use std::slice; pub enum IndexDatumType { UnsignedByte, UnsignedShort } pub trait IndexData { fn index_datum_type() -> IndexDatumType; fn index_bytes(&self) -> &[u8]; fn index_elements(&self) -> usize; } pub trait IndexDatum { fn index_datum_type() -> IndexDatumType; } impl IndexDatum for u8 { fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedByte } } impl IndexDatum for u16 { fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedShort } } impl<T: IndexDatum> IndexData for [T] { fn index_datum_type() -> IndexDatumType { T::index_datum_type() } fn index_bytes(&self) -> &[u8] { let size = mem::size_of::<T>() * self.len(); unsafe { slice::from_raw_parts(mem::transmute(&self[0]), size) } } fn index_elements(&self) -> usize { self.len() } }
17
0
1
add_only
--- a/src/index_data.rs +++ b/src/index_data.rs @@ -25 +25,18 @@ } + +impl<T: IndexDatum> IndexData for [T] { + fn index_datum_type() -> IndexDatumType { + T::index_datum_type() + } + + fn index_bytes(&self) -> &[u8] { + let size = mem::size_of::<T>() * self.len(); + unsafe { + slice::from_raw_parts(mem::transmute(&self[0]), size) + } + } + + fn index_elements(&self) -> usize { + self.len() + } +}
--- a/src/index_data.rs +++ b/src/index_data.rs @@ ... @@ } + +impl<T: IndexDatum> IndexData for [T] { + fn index_datum_type() -> IndexDatumType { + T::index_datum_type() + } + + fn index_bytes(&self) -> &[u8] { + let size = mem::size_of::<T>() * self.len(); + unsafe { + slice::from_raw_parts(mem::transmute(&self[0]), size) + } + } + + fn index_elements(&self) -> usize { + self.len() + } +}
--- a/src/index_data.rs +++ b/src/index_data.rs @@ -25 +25,18 @@ CON } ADD ADD impl<T: IndexDatum> IndexData for [T] { ADD fn index_datum_type() -> IndexDatumType { ADD T::index_datum_type() ADD } ADD ADD fn index_bytes(&self) -> &[u8] { ADD let size = mem::size_of::<T>() * self.len(); ADD unsafe { ADD slice::from_raw_parts(mem::transmute(&self[0]), size) ADD } ADD } ADD ADD fn index_elements(&self) -> usize { ADD self.len() ADD } ADD }
<<<<<<< SEARCH fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedShort } } ======= fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedShort } } impl<T: IndexDatum> IndexData for [T] { fn index_datum_type() -> IndexDatumType { T::index_datum_type() } fn index_bytes(&self) -> &[u8] { let size = mem::size_of::<T>() * self.len(); unsafe { slice::from_raw_parts(mem::transmute(&self[0]), size) } } fn index_elements(&self) -> usize { self.len() } } >>>>>>> REPLACE
java-opengl-labs/learn-OpenGL
6155fec1aed31c5e74d1a11b004ba8f2fb809d95
src/main/kotlin/learnOpenGL/common/glfw.kt
kotlin
mit
Add window hint to allow OpenGL 3+ on macOS How can we detect os and use forwardComp by default only on macOS?
package learnOpenGL.common import glm.vec2.Vec2i import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWErrorCallback import org.lwjgl.glfw.GLFWVidMode /** * Created by elect on 22/04/17. */ object glfw { fun init() { GLFWErrorCallback.createPrint(System.err).set() if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") } fun windowHint(block: windowHint.() -> Unit) = windowHint.block() val primaryMonitor get() = glfwGetPrimaryMonitor() val videoMode get() = glfwGetVideoMode(primaryMonitor) var start = System.nanoTime() val time get() = (System.nanoTime() - start) / 1e9f fun videoMode(monitor: Long) = glfwGetVideoMode(monitor) val resolution get() = Vec2i(videoMode.width(), videoMode.height()) var swapInterval = 0 set(value) = glfwSwapInterval(value) fun terminate() { glfwTerminate() glfwSetErrorCallback(null).free() } fun pollEvents() = glfwPollEvents() }
package learnOpenGL.common import glm.vec2.Vec2i import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWErrorCallback import org.lwjgl.glfw.GLFWVidMode /** * Created by elect on 22/04/17. */ object glfw { fun init() { GLFWErrorCallback.createPrint(System.err).set() if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") /* This window hint is required to use OpenGL 3.1+ on macOS */ windowHint { forwardComp = true } } fun windowHint(block: windowHint.() -> Unit) = windowHint.block() val primaryMonitor get() = glfwGetPrimaryMonitor() val videoMode get() = glfwGetVideoMode(primaryMonitor) var start = System.nanoTime() val time get() = (System.nanoTime() - start) / 1e9f fun videoMode(monitor: Long) = glfwGetVideoMode(monitor) val resolution get() = Vec2i(videoMode.width(), videoMode.height()) var swapInterval = 0 set(value) = glfwSwapInterval(value) fun terminate() { glfwTerminate() glfwSetErrorCallback(null).free() } fun pollEvents() = glfwPollEvents() }
5
0
1
add_only
--- a/src/main/kotlin/learnOpenGL/common/glfw.kt +++ b/src/main/kotlin/learnOpenGL/common/glfw.kt @@ -18,2 +18,7 @@ throw IllegalStateException("Unable to initialize GLFW") + + /* This window hint is required to use OpenGL 3.1+ on macOS */ + windowHint { + forwardComp = true + } }
--- a/src/main/kotlin/learnOpenGL/common/glfw.kt +++ b/src/main/kotlin/learnOpenGL/common/glfw.kt @@ ... @@ throw IllegalStateException("Unable to initialize GLFW") + + /* This window hint is required to use OpenGL 3.1+ on macOS */ + windowHint { + forwardComp = true + } }
--- a/src/main/kotlin/learnOpenGL/common/glfw.kt +++ b/src/main/kotlin/learnOpenGL/common/glfw.kt @@ -18,2 +18,7 @@ CON throw IllegalStateException("Unable to initialize GLFW") ADD ADD /* This window hint is required to use OpenGL 3.1+ on macOS */ ADD windowHint { ADD forwardComp = true ADD } CON }
<<<<<<< SEARCH if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") } ======= if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") /* This window hint is required to use OpenGL 3.1+ on macOS */ windowHint { forwardComp = true } } >>>>>>> REPLACE
google/ground-android
5ceb637b3373419e86961e236517032efac392c2
ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt
kotlin
apache-2.0
Convert to data class and replace with Result
/* * Copyright 2019 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.rx import java8.util.Optional /** The result of an operation that can return either true, false, or fail with an exception. */ class BooleanOrError private constructor(val value: Boolean?, val error: Throwable?) { /** * Returns true if the operation succeeded with a result of `true`, or false otherwise. Note that * false is also returned if the operation failed in error. */ val isTrue = value().orElse(false)!! fun value(): Optional<Boolean> = Optional.ofNullable(value) fun error(): Optional<Throwable?> = Optional.ofNullable(error) companion object { @JvmStatic fun trueValue(): BooleanOrError { return BooleanOrError(true, null) } @JvmStatic fun falseValue(): BooleanOrError { return BooleanOrError(false, null) } @JvmStatic fun error(t: Throwable?): BooleanOrError { return BooleanOrError(null, t) } } }
/* * Copyright 2019 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.rx import java8.util.Optional /** The result of an operation that can return either true, false, or fail with an exception. */ data class BooleanOrError(val result: Result<Boolean>) { /** * Returns true if the operation succeeded with a result of `true`, or false otherwise. Note that * false is also returned if the operation failed in error. */ val isTrue = value().orElse(false)!! fun value(): Optional<Boolean> = Optional.ofNullable(result.getOrNull()) fun error(): Optional<Throwable?> = Optional.ofNullable(result.exceptionOrNull()) companion object { @JvmStatic fun trueValue(): BooleanOrError { return BooleanOrError(Result.success(true)) } @JvmStatic fun falseValue(): BooleanOrError { return BooleanOrError(Result.success(false)) } @JvmStatic fun error(t: Throwable): BooleanOrError { return BooleanOrError(Result.failure(t)) } } }
7
7
5
mixed
--- a/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt +++ b/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt @@ -20,3 +20,3 @@ /** The result of an operation that can return either true, false, or fail with an exception. */ -class BooleanOrError private constructor(val value: Boolean?, val error: Throwable?) { +data class BooleanOrError(val result: Result<Boolean>) { /** @@ -27,5 +27,5 @@ - fun value(): Optional<Boolean> = Optional.ofNullable(value) + fun value(): Optional<Boolean> = Optional.ofNullable(result.getOrNull()) - fun error(): Optional<Throwable?> = Optional.ofNullable(error) + fun error(): Optional<Throwable?> = Optional.ofNullable(result.exceptionOrNull()) @@ -34,3 +34,3 @@ fun trueValue(): BooleanOrError { - return BooleanOrError(true, null) + return BooleanOrError(Result.success(true)) } @@ -39,3 +39,3 @@ fun falseValue(): BooleanOrError { - return BooleanOrError(false, null) + return BooleanOrError(Result.success(false)) } @@ -43,4 +43,4 @@ @JvmStatic - fun error(t: Throwable?): BooleanOrError { - return BooleanOrError(null, t) + fun error(t: Throwable): BooleanOrError { + return BooleanOrError(Result.failure(t)) }
--- a/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt +++ b/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt @@ ... @@ /** The result of an operation that can return either true, false, or fail with an exception. */ -class BooleanOrError private constructor(val value: Boolean?, val error: Throwable?) { +data class BooleanOrError(val result: Result<Boolean>) { /** @@ ... @@ - fun value(): Optional<Boolean> = Optional.ofNullable(value) + fun value(): Optional<Boolean> = Optional.ofNullable(result.getOrNull()) - fun error(): Optional<Throwable?> = Optional.ofNullable(error) + fun error(): Optional<Throwable?> = Optional.ofNullable(result.exceptionOrNull()) @@ ... @@ fun trueValue(): BooleanOrError { - return BooleanOrError(true, null) + return BooleanOrError(Result.success(true)) } @@ ... @@ fun falseValue(): BooleanOrError { - return BooleanOrError(false, null) + return BooleanOrError(Result.success(false)) } @@ ... @@ @JvmStatic - fun error(t: Throwable?): BooleanOrError { - return BooleanOrError(null, t) + fun error(t: Throwable): BooleanOrError { + return BooleanOrError(Result.failure(t)) }
--- a/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt +++ b/ground/src/main/java/com/google/android/ground/rx/BooleanOrError.kt @@ -20,3 +20,3 @@ CON /** The result of an operation that can return either true, false, or fail with an exception. */ DEL class BooleanOrError private constructor(val value: Boolean?, val error: Throwable?) { ADD data class BooleanOrError(val result: Result<Boolean>) { CON /** @@ -27,5 +27,5 @@ CON DEL fun value(): Optional<Boolean> = Optional.ofNullable(value) ADD fun value(): Optional<Boolean> = Optional.ofNullable(result.getOrNull()) CON DEL fun error(): Optional<Throwable?> = Optional.ofNullable(error) ADD fun error(): Optional<Throwable?> = Optional.ofNullable(result.exceptionOrNull()) CON @@ -34,3 +34,3 @@ CON fun trueValue(): BooleanOrError { DEL return BooleanOrError(true, null) ADD return BooleanOrError(Result.success(true)) CON } @@ -39,3 +39,3 @@ CON fun falseValue(): BooleanOrError { DEL return BooleanOrError(false, null) ADD return BooleanOrError(Result.success(false)) CON } @@ -43,4 +43,4 @@ CON @JvmStatic DEL fun error(t: Throwable?): BooleanOrError { DEL return BooleanOrError(null, t) ADD fun error(t: Throwable): BooleanOrError { ADD return BooleanOrError(Result.failure(t)) CON }
<<<<<<< SEARCH /** The result of an operation that can return either true, false, or fail with an exception. */ class BooleanOrError private constructor(val value: Boolean?, val error: Throwable?) { /** * Returns true if the operation succeeded with a result of `true`, or false otherwise. Note that ======= /** The result of an operation that can return either true, false, or fail with an exception. */ data class BooleanOrError(val result: Result<Boolean>) { /** * Returns true if the operation succeeded with a result of `true`, or false otherwise. Note that >>>>>>> REPLACE <<<<<<< SEARCH val isTrue = value().orElse(false)!! fun value(): Optional<Boolean> = Optional.ofNullable(value) fun error(): Optional<Throwable?> = Optional.ofNullable(error) companion object { @JvmStatic fun trueValue(): BooleanOrError { return BooleanOrError(true, null) } @JvmStatic fun falseValue(): BooleanOrError { return BooleanOrError(false, null) } @JvmStatic fun error(t: Throwable?): BooleanOrError { return BooleanOrError(null, t) } } ======= val isTrue = value().orElse(false)!! fun value(): Optional<Boolean> = Optional.ofNullable(result.getOrNull()) fun error(): Optional<Throwable?> = Optional.ofNullable(result.exceptionOrNull()) companion object { @JvmStatic fun trueValue(): BooleanOrError { return BooleanOrError(Result.success(true)) } @JvmStatic fun falseValue(): BooleanOrError { return BooleanOrError(Result.success(false)) } @JvmStatic fun error(t: Throwable): BooleanOrError { return BooleanOrError(Result.failure(t)) } } >>>>>>> REPLACE
sloede/pyglab
b870028ce8edcb5001f1a4823517d866db0324a8
pyglab/apirequest.py
python
mit
Make RequestType a normal class, not an enum. This removes the restriction of needing Python >= 3.4. RequestType is now a normal class with class variables (fixes #19).
import enum import json from pyglab.exceptions import RequestError import requests @enum.unique class RequestType(enum.Enum): GET = 1 POST = 2 PUT = 3 DELETE = 4 class ApiRequest: _request_creators = { RequestType.GET: requests.get, RequestType.POST: requests.post, RequestType.PUT: requests.put, RequestType.DELETE: requests.delete, } def __init__(self, request_type, url, token, params={}, sudo=None, page=None, per_page=None): # Build header header = {'PRIVATE-TOKEN': token} if sudo is not None: header['SUDO', sudo] # Build parameters if page is not None: params['page'] = page if per_page is not None: params['per_page'] = per_page r = self._request_creators[request_type](url, params=params, headers=header) content = json.loads(r.text) if RequestError.is_error(r.status_code): raise RequestError.error_class(r.status_code)(content) self._content = content @property def content(self): return self._content
import json from pyglab.exceptions import RequestError import requests class RequestType(object): GET = 1 POST = 2 PUT = 3 DELETE = 4 class ApiRequest: _request_creators = { RequestType.GET: requests.get, RequestType.POST: requests.post, RequestType.PUT: requests.put, RequestType.DELETE: requests.delete, } def __init__(self, request_type, url, token, params={}, sudo=None, page=None, per_page=None): # Build header header = {'PRIVATE-TOKEN': token} if sudo is not None: header['SUDO', sudo] # Build parameters if page is not None: params['page'] = page if per_page is not None: params['per_page'] = per_page r = self._request_creators[request_type](url, params=params, headers=header) content = json.loads(r.text) if RequestError.is_error(r.status_code): raise RequestError.error_class(r.status_code)(content) self._content = content @property def content(self): return self._content
1
3
2
mixed
--- a/pyglab/apirequest.py +++ b/pyglab/apirequest.py @@ -1,2 +1 @@ -import enum import json @@ -5,4 +4,3 @@ [email protected] -class RequestType(enum.Enum): +class RequestType(object): GET = 1
--- a/pyglab/apirequest.py +++ b/pyglab/apirequest.py @@ ... @@ -import enum import json @@ ... @@ [email protected] -class RequestType(enum.Enum): +class RequestType(object): GET = 1
--- a/pyglab/apirequest.py +++ b/pyglab/apirequest.py @@ -1,2 +1 @@ DEL import enum CON import json @@ -5,4 +4,3 @@ CON DEL @enum.unique DEL class RequestType(enum.Enum): ADD class RequestType(object): CON GET = 1
<<<<<<< SEARCH import enum import json from pyglab.exceptions import RequestError import requests @enum.unique class RequestType(enum.Enum): GET = 1 POST = 2 ======= import json from pyglab.exceptions import RequestError import requests class RequestType(object): GET = 1 POST = 2 >>>>>>> REPLACE
ssanderson/interface
da10b6baa19c1ef3a5f875297187e7248b7460b1
setup.py
python
apache-2.0
BLD: Use PEP 508 version markers. So that environment tooling, e.g. `pipenv` can use the python version markers when determining dependencies.
#!/usr/bin/env python from setuptools import setup, find_packages import sys long_description = '' if 'upload' in sys.argv: with open('README.rst') as f: long_description = f.read() def extras_require(): return { 'test': [ 'tox>=2.0', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def install_requires(): requires = ['six'] if sys.version_info[:2] < (3, 5): requires.append("typing>=3.5.2") if sys.version_info[0] == 2: requires.append("funcsigs>=1.0.2") return requires setup( name='python-interface', version='1.4.0', description="Pythonic Interface definitions", author="Scott Sanderson", author_email="[email protected]", packages=find_packages(), long_description=long_description, license='Apache 2.0', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Pre-processors', ], url='https://github.com/ssanderson/interface', install_requires=install_requires(), extras_require=extras_require(), )
#!/usr/bin/env python from setuptools import setup, find_packages import sys long_description = '' if 'upload' in sys.argv: with open('README.rst') as f: long_description = f.read() def extras_require(): return { 'test': [ 'tox>=2.0', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def install_requires(): return [ 'six', 'typing>=3.5.2;python_version<"3.5"', 'funcsigs>=1.0.2;python_version<"3"' ] setup( name='python-interface', version='1.4.0', description="Pythonic Interface definitions", author="Scott Sanderson", author_email="[email protected]", packages=find_packages(), long_description=long_description, license='Apache 2.0', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Pre-processors', ], url='https://github.com/ssanderson/interface', install_requires=install_requires(), extras_require=extras_require(), )
5
6
1
mixed
--- a/setup.py +++ b/setup.py @@ -23,8 +23,7 @@ def install_requires(): - requires = ['six'] - if sys.version_info[:2] < (3, 5): - requires.append("typing>=3.5.2") - if sys.version_info[0] == 2: - requires.append("funcsigs>=1.0.2") - return requires + return [ + 'six', + 'typing>=3.5.2;python_version<"3.5"', + 'funcsigs>=1.0.2;python_version<"3"' + ]
--- a/setup.py +++ b/setup.py @@ ... @@ def install_requires(): - requires = ['six'] - if sys.version_info[:2] < (3, 5): - requires.append("typing>=3.5.2") - if sys.version_info[0] == 2: - requires.append("funcsigs>=1.0.2") - return requires + return [ + 'six', + 'typing>=3.5.2;python_version<"3.5"', + 'funcsigs>=1.0.2;python_version<"3"' + ]
--- a/setup.py +++ b/setup.py @@ -23,8 +23,7 @@ CON def install_requires(): DEL requires = ['six'] DEL if sys.version_info[:2] < (3, 5): DEL requires.append("typing>=3.5.2") DEL if sys.version_info[0] == 2: DEL requires.append("funcsigs>=1.0.2") DEL return requires ADD return [ ADD 'six', ADD 'typing>=3.5.2;python_version<"3.5"', ADD 'funcsigs>=1.0.2;python_version<"3"' ADD ] CON
<<<<<<< SEARCH def install_requires(): requires = ['six'] if sys.version_info[:2] < (3, 5): requires.append("typing>=3.5.2") if sys.version_info[0] == 2: requires.append("funcsigs>=1.0.2") return requires ======= def install_requires(): return [ 'six', 'typing>=3.5.2;python_version<"3.5"', 'funcsigs>=1.0.2;python_version<"3"' ] >>>>>>> REPLACE
d-unseductable/ruru
ba2617f7dd04281b38c7c5cd581e5200de059d67
src/class/hash.rs
rust
mit
Add different trait constraints to Hash store()
use std::convert::From; use binding::hash; use types; use super::object; use super::traits::RawObject; pub struct Hash { value: types::rb_value } impl Hash { pub fn new() -> Self { Hash { value: hash::new() } } pub fn at<T: RawObject>(&self, key: T) -> object::Object { let value = hash::aref(self.value(), key.value()); object::Object::from(value) } pub fn store<T: RawObject>(&mut self, key: T, value: T) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value()); object::Object::from(value) } } impl From<types::rb_value> for Hash { fn from(value: types::rb_value) -> Self { Hash { value: value } } } impl RawObject for Hash { fn value(&self) -> types::rb_value { self.value } }
use std::convert::From; use binding::hash; use types; use super::object; use super::traits::RawObject; pub struct Hash { value: types::rb_value } impl Hash { pub fn new() -> Self { Hash { value: hash::new() } } pub fn at<T: RawObject>(&self, key: T) -> object::Object { let value = hash::aref(self.value(), key.value()); object::Object::from(value) } pub fn store<K: RawObject, V: RawObject>(&mut self, key: K, value: V) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value()); object::Object::from(value) } } impl From<types::rb_value> for Hash { fn from(value: types::rb_value) -> Self { Hash { value: value } } } impl RawObject for Hash { fn value(&self) -> types::rb_value { self.value } }
1
1
1
mixed
--- a/src/class/hash.rs +++ b/src/class/hash.rs @@ -25,3 +25,3 @@ - pub fn store<T: RawObject>(&mut self, key: T, value: T) -> object::Object { + pub fn store<K: RawObject, V: RawObject>(&mut self, key: K, value: V) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value());
--- a/src/class/hash.rs +++ b/src/class/hash.rs @@ ... @@ - pub fn store<T: RawObject>(&mut self, key: T, value: T) -> object::Object { + pub fn store<K: RawObject, V: RawObject>(&mut self, key: K, value: V) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value());
--- a/src/class/hash.rs +++ b/src/class/hash.rs @@ -25,3 +25,3 @@ CON DEL pub fn store<T: RawObject>(&mut self, key: T, value: T) -> object::Object { ADD pub fn store<K: RawObject, V: RawObject>(&mut self, key: K, value: V) -> object::Object { CON let value = hash::aset(self.value(), key.value(), value.value());
<<<<<<< SEARCH } pub fn store<T: RawObject>(&mut self, key: T, value: T) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value()); ======= } pub fn store<K: RawObject, V: RawObject>(&mut self, key: K, value: V) -> object::Object { let value = hash::aset(self.value(), key.value(), value.value()); >>>>>>> REPLACE
rca/cmdline
b5d801c561b4a73ba7ea41665b7fe756fc56689d
setup.py
python
apache-2.0
Add markdown content type for README
#!/usr/bin/env python import os from setuptools import find_packages, setup SCRIPT_DIR = os.path.dirname(__file__) if not SCRIPT_DIR: SCRIPT_DIR = os.getcwd() SRC_PREFIX = 'src' packages = find_packages(SRC_PREFIX) setup( name='cmdline', version='0.0.0', description='Utilities for consistent command line tools', author='Roberto Aguilar', author_email='[email protected]', package_dir={'': SRC_PREFIX}, packages=packages, long_description=open('README.md').read(), url='http://github.com/rca/cmdline', license='LICENSE', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Natural Language :: English', 'Topic :: Utilities' ], install_requires=[ 'PyYAML>=3', ], )
#!/usr/bin/env python import os from setuptools import find_packages, setup SCRIPT_DIR = os.path.dirname(__file__) if not SCRIPT_DIR: SCRIPT_DIR = os.getcwd() SRC_PREFIX = 'src' def readme(): with open('README.md') as f: return f.read() packages = find_packages(SRC_PREFIX) setup( name='cmdline', version='0.0.0', description='Utilities for consistent command line tools', author='Roberto Aguilar', author_email='[email protected]', package_dir={'': SRC_PREFIX}, packages=packages, long_description=readme(), long_description_content_type='text/markdown', url='http://github.com/rca/cmdline', license='LICENSE', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Natural Language :: English', 'Topic :: Utilities' ], install_requires=[ 'PyYAML>=3', ], )
7
1
2
mixed
--- a/setup.py +++ b/setup.py @@ -12,2 +12,7 @@ +def readme(): + with open('README.md') as f: + return f.read() + + packages = find_packages(SRC_PREFIX) @@ -22,3 +27,4 @@ packages=packages, - long_description=open('README.md').read(), + long_description=readme(), + long_description_content_type='text/markdown', url='http://github.com/rca/cmdline',
--- a/setup.py +++ b/setup.py @@ ... @@ +def readme(): + with open('README.md') as f: + return f.read() + + packages = find_packages(SRC_PREFIX) @@ ... @@ packages=packages, - long_description=open('README.md').read(), + long_description=readme(), + long_description_content_type='text/markdown', url='http://github.com/rca/cmdline',
--- a/setup.py +++ b/setup.py @@ -12,2 +12,7 @@ CON ADD def readme(): ADD with open('README.md') as f: ADD return f.read() ADD ADD CON packages = find_packages(SRC_PREFIX) @@ -22,3 +27,4 @@ CON packages=packages, DEL long_description=open('README.md').read(), ADD long_description=readme(), ADD long_description_content_type='text/markdown', CON url='http://github.com/rca/cmdline',
<<<<<<< SEARCH packages = find_packages(SRC_PREFIX) ======= def readme(): with open('README.md') as f: return f.read() packages = find_packages(SRC_PREFIX) >>>>>>> REPLACE <<<<<<< SEARCH package_dir={'': SRC_PREFIX}, packages=packages, long_description=open('README.md').read(), url='http://github.com/rca/cmdline', license='LICENSE', ======= package_dir={'': SRC_PREFIX}, packages=packages, long_description=readme(), long_description_content_type='text/markdown', url='http://github.com/rca/cmdline', license='LICENSE', >>>>>>> REPLACE
wakermahmud/Moretaza
30c21764723ca0878cea9f41977f756227edd51b
gulpfile.js
javascript
mit
Update and fix sass gulp path
var gulp = require('gulp'), browserSync = require('browser-sync'), sass = require('gulp-sass'), bower = require('gulp-bower'), notify = require('gulp-notify'), reload = browserSync.reload, bs = require("browser-sync").create(), Hexo = require('hexo'), hexo = new Hexo(process.cwd(), {}); var src = { scss: 'scss', css: 'source/css', ejs: 'layout' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { // init starts the server bs.init({ baseDir: "../../public" }); // hexo.call('generate', {}).then(function(){ // console.log('Generating Files'); // }); // Now call methods on bs instead of the // main browserSync module export bs.reload("*.html"); bs.reload("*.css"); }); // Compile sass into CSS gulp.task('sass', function() { gulp.src(src.scss) .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); gulp.task('sass:watch', function () { gulp.watch('./scss/**/*.scss', ['sass']); }); gulp.task('bower', function() { return bower() .pipe(gulp.dest('source/lib')) }); gulp.task('default', ['serve']);
var gulp = require('gulp'), browserSync = require('browser-sync'), sass = require('gulp-sass'), bower = require('gulp-bower'), notify = require('gulp-notify'), reload = browserSync.reload, bs = require("browser-sync").create(), Hexo = require('hexo'), hexo = new Hexo(process.cwd(), {}); var src = { scss: './scss/', css: './source/css', ejs: 'layout' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { // init starts the server bs.init({ baseDir: "../../public" }); // hexo.call('generate', {}).then(function(){ // console.log('Generating Files'); // }); // Now call methods on bs instead of the // main browserSync module export bs.reload("*.html"); bs.reload("*.css"); }); // Compile sass into CSS gulp.task('sass', function() { // gulp.src(src.scss + "/*/*.scss") gulp.src(src.scss + "{,*}/*.scss") .pipe(sass({})) // .pipe(gulp.dest(src.css)) .pipe(gulp.dest('./css/')) .pipe(reload({stream: true})); }); gulp.task('sass:watch', function () { gulp.watch('./scss/**/*.scss', ['sass']); }); gulp.task('bower', function() { return bower() .pipe(gulp.dest('source/lib')) }); gulp.task('default', ['serve']);
7
5
2
mixed
--- a/gulpfile.js +++ b/gulpfile.js @@ -12,4 +12,4 @@ var src = { - scss: 'scss', - css: 'source/css', + scss: './scss/', + css: './source/css', ejs: 'layout' @@ -37,5 +37,7 @@ gulp.task('sass', function() { - gulp.src(src.scss) - .pipe(sass().on('error', sass.logError)) - .pipe(gulp.dest(src.css)) + // gulp.src(src.scss + "/*/*.scss") + gulp.src(src.scss + "{,*}/*.scss") + .pipe(sass({})) + // .pipe(gulp.dest(src.css)) + .pipe(gulp.dest('./css/')) .pipe(reload({stream: true}));
--- a/gulpfile.js +++ b/gulpfile.js @@ ... @@ var src = { - scss: 'scss', - css: 'source/css', + scss: './scss/', + css: './source/css', ejs: 'layout' @@ ... @@ gulp.task('sass', function() { - gulp.src(src.scss) - .pipe(sass().on('error', sass.logError)) - .pipe(gulp.dest(src.css)) + // gulp.src(src.scss + "/*/*.scss") + gulp.src(src.scss + "{,*}/*.scss") + .pipe(sass({})) + // .pipe(gulp.dest(src.css)) + .pipe(gulp.dest('./css/')) .pipe(reload({stream: true}));
--- a/gulpfile.js +++ b/gulpfile.js @@ -12,4 +12,4 @@ CON var src = { DEL scss: 'scss', DEL css: 'source/css', ADD scss: './scss/', ADD css: './source/css', CON ejs: 'layout' @@ -37,5 +37,7 @@ CON gulp.task('sass', function() { DEL gulp.src(src.scss) DEL .pipe(sass().on('error', sass.logError)) DEL .pipe(gulp.dest(src.css)) ADD // gulp.src(src.scss + "/*/*.scss") ADD gulp.src(src.scss + "{,*}/*.scss") ADD .pipe(sass({})) ADD // .pipe(gulp.dest(src.css)) ADD .pipe(gulp.dest('./css/')) CON .pipe(reload({stream: true}));
<<<<<<< SEARCH var src = { scss: 'scss', css: 'source/css', ejs: 'layout' }; ======= var src = { scss: './scss/', css: './source/css', ejs: 'layout' }; >>>>>>> REPLACE <<<<<<< SEARCH // Compile sass into CSS gulp.task('sass', function() { gulp.src(src.scss) .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); ======= // Compile sass into CSS gulp.task('sass', function() { // gulp.src(src.scss + "/*/*.scss") gulp.src(src.scss + "{,*}/*.scss") .pipe(sass({})) // .pipe(gulp.dest(src.css)) .pipe(gulp.dest('./css/')) .pipe(reload({stream: true})); }); >>>>>>> REPLACE
google/android-fhir
5ee2385e7f133383b04d74353c61192dc4ac1575
datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt
kotlin
apache-2.0
Update the questionnaire item view holder type test
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture import android.os.Build import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class QuestionnaireItemViewHolderTypeTest { @Test fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(7) } @Test fun fromInt_shouldReturnQuestionnaireViewHolderType() { QuestionnaireItemViewHolderType.values().forEach { assertThat(QuestionnaireItemViewHolderType.fromInt(it.value)).isEqualTo(it) } } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture import android.os.Build import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class QuestionnaireItemViewHolderTypeTest { @Test fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(8) } @Test fun fromInt_shouldReturnQuestionnaireViewHolderType() { QuestionnaireItemViewHolderType.values().forEach { assertThat(QuestionnaireItemViewHolderType.fromInt(it.value)).isEqualTo(it) } } }
1
1
1
mixed
--- a/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt +++ b/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt @@ -30,3 +30,3 @@ fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { - assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(7) + assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(8) }
--- a/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt +++ b/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt @@ ... @@ fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { - assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(7) + assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(8) }
--- a/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt +++ b/datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemViewHolderTypeTest.kt @@ -30,3 +30,3 @@ CON fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { DEL assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(7) ADD assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(8) CON }
<<<<<<< SEARCH @Test fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(7) } ======= @Test fun size_shouldReturnNumberOfQuestionnaireViewHolderTypes() { assertThat(QuestionnaireItemViewHolderType.values().size).isEqualTo(8) } >>>>>>> REPLACE
droolsjbpm/jbpmmigration
7f7d0580617436acdbe4b922c749d9f81704c5a6
src/main/java/org/jbpm/migration/ErrorCollector.java
java
apache-2.0
Fix for ignoring BPMN validation - JBPM-4000
package org.jbpm.migration; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */ abstract class ErrorCollector<T extends Exception> { private final List<T> warningList = new ArrayList<T>(); private final List<T> errorList = new ArrayList<T>(); private final List<T> fatalList = new ArrayList<T>(); public void warning(final T ex) { warningList.add(ex); } public void error(final T ex) { errorList.add(ex); } public void fatalError(final T ex) { fatalList.add(ex); } public boolean didErrorOccur() { return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); } public List<T> getWarningList() { return warningList; } public List<T> getErrorList() { return errorList; } public List<T> getFatalList() { return fatalList; } public void logErrors(final Logger logger) { for (final T ex : warningList) { logger.warn("==>", ex); } for (final T ex : errorList) { logger.error("==>", ex); } for (final T ex : fatalList) { logger.fatal("==>", ex); } } }
package org.jbpm.migration; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */ abstract class ErrorCollector<T extends Exception> { private final List<T> warningList = new ArrayList<T>(); private final List<T> errorList = new ArrayList<T>(); private final List<T> fatalList = new ArrayList<T>(); public void warning(final T ex) { warningList.add(ex); } public void error(final T ex) { errorList.add(ex); } public void fatalError(final T ex) { fatalList.add(ex); } public boolean didErrorOccur() { // checking warnings might be too restrictive return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); } public List<T> getWarningList() { return warningList; } public List<T> getErrorList() { return errorList; } public List<T> getFatalList() { return fatalList; } public void logErrors(final Logger logger) { for (final T ex : warningList) { logger.warn("==>", ex); } for (final T ex : errorList) { logger.error("==>", ex); } for (final T ex : fatalList) { logger.fatal("==>", ex); } } }
2
1
1
mixed
--- a/src/main/java/org/jbpm/migration/ErrorCollector.java +++ b/src/main/java/org/jbpm/migration/ErrorCollector.java @@ -26,3 +26,4 @@ public boolean didErrorOccur() { - return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); + // checking warnings might be too restrictive + return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); }
--- a/src/main/java/org/jbpm/migration/ErrorCollector.java +++ b/src/main/java/org/jbpm/migration/ErrorCollector.java @@ ... @@ public boolean didErrorOccur() { - return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); + // checking warnings might be too restrictive + return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); }
--- a/src/main/java/org/jbpm/migration/ErrorCollector.java +++ b/src/main/java/org/jbpm/migration/ErrorCollector.java @@ -26,3 +26,4 @@ CON public boolean didErrorOccur() { DEL return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); ADD // checking warnings might be too restrictive ADD return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); CON }
<<<<<<< SEARCH public boolean didErrorOccur() { return !warningList.isEmpty() && !errorList.isEmpty() && !fatalList.isEmpty(); } ======= public boolean didErrorOccur() { // checking warnings might be too restrictive return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty(); } >>>>>>> REPLACE
woxtu/cargo-thank-you-stars
e488c1932930543ebc93a243bd87b18ecf9433a0
src/main.rs
rust
mit
Print errors to stderr instead of stdout
#[macro_use] extern crate error_chain; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json as json; extern crate toml; extern crate url; mod config; mod crates_io; mod errors; mod github; mod lockfile; use std::env; use crates_io::Repository; use errors::*; quick_main!(|| -> Result<()> { let home_dir = env::home_dir().expect("Cannot get home directory"); let config = config::read(&home_dir.join(".thank-you-stars.json")) .chain_err(|| "Save your configuration as `.thank-you-stars.json`")?; let lockfile = lockfile::read(&env::current_dir()?.join("Cargo.lock")) .chain_err(|| "Run `cargo install` before")?; for dependency in lockfile.root.dependencies { if dependency.is_registry() { let krate = crates_io::get(&dependency.crate_id()) .chain_err(|| "Cannot get crate data from crates.io")?; if let Repository::GitHub(repository) = krate.repository() { match github::star(&config.token, &repository) { Ok(_) => println!("Starred! https://github.com/{}", &repository), Err(e) => println!("{}", e), } } } } Ok(()) });
#[macro_use] extern crate error_chain; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json as json; extern crate toml; extern crate url; mod config; mod crates_io; mod errors; mod github; mod lockfile; use std::env; use crates_io::Repository; use errors::*; quick_main!(|| -> Result<()> { let home_dir = env::home_dir().expect("Cannot get home directory"); let config = config::read(&home_dir.join(".thank-you-stars.json")) .chain_err(|| "Save your configuration as `.thank-you-stars.json`")?; let lockfile = lockfile::read(&env::current_dir()?.join("Cargo.lock")) .chain_err(|| "Run `cargo install` before")?; for dependency in lockfile.root.dependencies { if dependency.is_registry() { let krate = crates_io::get(&dependency.crate_id()) .chain_err(|| "Cannot get crate data from crates.io")?; if let Repository::GitHub(repository) = krate.repository() { match github::star(&config.token, &repository) { Ok(_) => println!("Starred! https://github.com/{}", &repository), Err(e) => eprintln!("{}", e.to_string()), } } } } Ok(()) });
1
1
1
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -38,3 +38,3 @@ Ok(_) => println!("Starred! https://github.com/{}", &repository), - Err(e) => println!("{}", e), + Err(e) => eprintln!("{}", e.to_string()), }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ Ok(_) => println!("Starred! https://github.com/{}", &repository), - Err(e) => println!("{}", e), + Err(e) => eprintln!("{}", e.to_string()), }
--- a/src/main.rs +++ b/src/main.rs @@ -38,3 +38,3 @@ CON Ok(_) => println!("Starred! https://github.com/{}", &repository), DEL Err(e) => println!("{}", e), ADD Err(e) => eprintln!("{}", e.to_string()), CON }
<<<<<<< SEARCH match github::star(&config.token, &repository) { Ok(_) => println!("Starred! https://github.com/{}", &repository), Err(e) => println!("{}", e), } } ======= match github::star(&config.token, &repository) { Ok(_) => println!("Starred! https://github.com/{}", &repository), Err(e) => eprintln!("{}", e.to_string()), } } >>>>>>> REPLACE
superjohan/pfm
76dd762dea5e82bf3a46338d42b9b77ce95fde79
app/src/main/java/com/aerodeko/pfm/MainActivity.kt
kotlin
mit
Initialize the event manager when creating the activity. This is maybe only temporary; the event manager hits the disk (i.e. creates/gets the database) in init, so it could be good to do in a background thread. On the other hand, a synchronous API would be way better, and this only happens in launch. All other event database handling should probably happen in the background, though.
package com.aerodeko.pfm import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.action_settings) { return true } return super.onOptionsItemSelected(item) } }
package com.aerodeko.pfm import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import com.aerodeko.pfm.model.EventManager class MainActivity : AppCompatActivity() { private lateinit var eventManager: EventManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) eventManager = EventManager(this) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.action_settings) { return true } return super.onOptionsItemSelected(item) } }
7
0
1
add_only
--- a/app/src/main/java/com/aerodeko/pfm/MainActivity.kt +++ b/app/src/main/java/com/aerodeko/pfm/MainActivity.kt @@ -9,7 +9,14 @@ import android.view.MenuItem +import com.aerodeko.pfm.model.EventManager class MainActivity : AppCompatActivity() { + private lateinit var eventManager: EventManager + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + eventManager = EventManager(this) + val toolbar = findViewById(R.id.toolbar) as Toolbar
--- a/app/src/main/java/com/aerodeko/pfm/MainActivity.kt +++ b/app/src/main/java/com/aerodeko/pfm/MainActivity.kt @@ ... @@ import android.view.MenuItem +import com.aerodeko.pfm.model.EventManager class MainActivity : AppCompatActivity() { + private lateinit var eventManager: EventManager + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + eventManager = EventManager(this) + val toolbar = findViewById(R.id.toolbar) as Toolbar
--- a/app/src/main/java/com/aerodeko/pfm/MainActivity.kt +++ b/app/src/main/java/com/aerodeko/pfm/MainActivity.kt @@ -9,7 +9,14 @@ CON import android.view.MenuItem ADD import com.aerodeko.pfm.model.EventManager CON CON class MainActivity : AppCompatActivity() { ADD private lateinit var eventManager: EventManager ADD CON override fun onCreate(savedInstanceState: Bundle?) { CON super.onCreate(savedInstanceState) ADD CON setContentView(R.layout.activity_main) ADD ADD eventManager = EventManager(this) ADD CON val toolbar = findViewById(R.id.toolbar) as Toolbar
<<<<<<< SEARCH import android.view.Menu import android.view.MenuItem class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) ======= import android.view.Menu import android.view.MenuItem import com.aerodeko.pfm.model.EventManager class MainActivity : AppCompatActivity() { private lateinit var eventManager: EventManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) eventManager = EventManager(this) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) >>>>>>> REPLACE
coderly/ember-gdrive
e9211409bec3ff15041f048bf2a00bfa2742a9ff
addon/lib/serializer.js
javascript
mit
Remove superfluous fix in favor of the remaining better one
import DS from 'ember-data'; import { recordKey } from 'ember-gdrive/lib/util'; function serializeId(record, relationship) { if (!record) { return null; } if (relationship.options.polymorphic) { return { id: record.get('id'), type: recordKey(record) }; } else { return record.get('id'); } } var Serializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { if(relationship.options.serialize === false) { return; } var key = relationship.key; var rel = record.get(key); if(relationship.options.async && rel){ rel = record._relationships[key].manyArray.toArray(); } if (rel){ json[key] = rel.map(function(record) { return serializeId(record, relationship); }); } }, serializeBelongsTo: function(record, json, relationship) { if(relationship.options.serialize === false) { return; } if (relationship.options && relationship.options.async){ var key = relationship.key; var belongsTo = record._relationships[key].inverseRecord; json[key] = serializeId(belongsTo, relationship); } else { this._super(record, json, relationship); } }, normalizePayload: function(payload) { return JSON.parse(JSON.stringify(payload)); } }); export default Serializer;
import DS from 'ember-data'; import { recordKey } from 'ember-gdrive/lib/util'; function serializeId(record, relationship) { if (!record) { return null; } if (relationship.options.polymorphic) { return { id: record.get('id'), type: recordKey(record) }; } else { return record.get('id'); } } var Serializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { if(relationship.options.serialize === false) { return; } var key = relationship.key; var rel = record.get(key); if(relationship.options.async && rel){ rel = record._relationships[key].manyArray.toArray(); } if (rel){ json[key] = rel.map(function(record) { return serializeId(record, relationship); }); } }, serializeBelongsTo: function(record, json, relationship) { if(relationship.options.serialize === false) { return; } if (relationship.options && relationship.options.async){ var key = relationship.key; var belongsTo = record._relationships[key].inverseRecord; json[key] = serializeId(belongsTo, relationship); } else { this._super(record, json, relationship); } } }); export default Serializer;
0
4
1
del_only
--- a/addon/lib/serializer.js +++ b/addon/lib/serializer.js @@ -49,6 +49,2 @@ } - }, - - normalizePayload: function(payload) { - return JSON.parse(JSON.stringify(payload)); }
--- a/addon/lib/serializer.js +++ b/addon/lib/serializer.js @@ ... @@ } - }, - - normalizePayload: function(payload) { - return JSON.parse(JSON.stringify(payload)); }
--- a/addon/lib/serializer.js +++ b/addon/lib/serializer.js @@ -49,6 +49,2 @@ CON } DEL }, DEL DEL normalizePayload: function(payload) { DEL return JSON.parse(JSON.stringify(payload)); CON }
<<<<<<< SEARCH this._super(record, json, relationship); } }, normalizePayload: function(payload) { return JSON.parse(JSON.stringify(payload)); } }); ======= this._super(record, json, relationship); } } }); >>>>>>> REPLACE
zmywly8866/Algorithms
fffcd6d89bf17d6ec829859f4e5703c5294dd1a2
src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java
java
apache-2.0
Add solution to problem 70
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pedrovgs.problem70; /** * Given an integer passed as parameter, can you write a method to return the number equivalent to * the binary number with the reversed order? * * For example: * * Input = 5 = 101 * Output = 5 = 101 * * Input = 13 = 1101 * Output = 11 = 1011 * * @author Pedro Vicente Gómez Sánchez. */ public class ReverseOrderOfBinaryNumber { }
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pedrovgs.problem70; /** * Given an integer passed as parameter, can you write a method to return the number equivalent to * the binary number with the reversed order? * * For example: * * Input = 5 = 101 * Output = 5 = 101 * * Input = 13 = 1101 * Output = 11 = 1011 * * @author Pedro Vicente Gómez Sánchez. */ public class ReverseOrderOfBinaryNumber { /** * Iterative algorithm to solve this problem. Shifting the input number until the value is equals * to zero and applying a simple mask we are going to create the reverted order binary number * using a constant complexity time in space terms O(1) and a linear complexity order in time * terms O(N) where N is equals to the number of digits of the input parameter into a binary * representation. */ public int reverse(int number) { int result = 0; while (number != 0) { result <<= 1; result |= number & 1; number >>= 1; } return result; } }
16
0
1
add_only
--- a/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java +++ b/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java @@ -33,2 +33,18 @@ + /** + * Iterative algorithm to solve this problem. Shifting the input number until the value is equals + * to zero and applying a simple mask we are going to create the reverted order binary number + * using a constant complexity time in space terms O(1) and a linear complexity order in time + * terms O(N) where N is equals to the number of digits of the input parameter into a binary + * representation. + */ + public int reverse(int number) { + int result = 0; + while (number != 0) { + result <<= 1; + result |= number & 1; + number >>= 1; + } + return result; + } }
--- a/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java +++ b/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java @@ ... @@ + /** + * Iterative algorithm to solve this problem. Shifting the input number until the value is equals + * to zero and applying a simple mask we are going to create the reverted order binary number + * using a constant complexity time in space terms O(1) and a linear complexity order in time + * terms O(N) where N is equals to the number of digits of the input parameter into a binary + * representation. + */ + public int reverse(int number) { + int result = 0; + while (number != 0) { + result <<= 1; + result |= number & 1; + number >>= 1; + } + return result; + } }
--- a/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java +++ b/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java @@ -33,2 +33,18 @@ CON ADD /** ADD * Iterative algorithm to solve this problem. Shifting the input number until the value is equals ADD * to zero and applying a simple mask we are going to create the reverted order binary number ADD * using a constant complexity time in space terms O(1) and a linear complexity order in time ADD * terms O(N) where N is equals to the number of digits of the input parameter into a binary ADD * representation. ADD */ ADD public int reverse(int number) { ADD int result = 0; ADD while (number != 0) { ADD result <<= 1; ADD result |= number & 1; ADD number >>= 1; ADD } ADD return result; ADD } CON }
<<<<<<< SEARCH public class ReverseOrderOfBinaryNumber { } ======= public class ReverseOrderOfBinaryNumber { /** * Iterative algorithm to solve this problem. Shifting the input number until the value is equals * to zero and applying a simple mask we are going to create the reverted order binary number * using a constant complexity time in space terms O(1) and a linear complexity order in time * terms O(N) where N is equals to the number of digits of the input parameter into a binary * representation. */ public int reverse(int number) { int result = 0; while (number != 0) { result <<= 1; result |= number & 1; number >>= 1; } return result; } } >>>>>>> REPLACE
Axosoft/nodegit-lfs
41e00267f10eb1b7b7d4a07434832c0730c92392
src/index.js
javascript
mit
Allow passing in the node binary path on init
import initialize from './initialize'; import register from './register'; import unregister from './unregister'; import { core } from './commands/lfsCommands'; import { loadGitattributeFiltersFromRepo, repoHasLfs } from './helpers'; import checkout from './commands/checkout'; import push from './commands/push'; import track from './commands/track'; import untrack from './commands/untrack'; import version from './commands/version'; import fetch from './commands/fetch'; import prune from './commands/prune'; import list from './commands/ls'; import testPointer from './commands/pointer'; import pull from './commands/pull'; import clone from './commands/clone'; import { dependencyCheck } from './utils/checkDependencies'; function LFS(nodegit) { this.NodeGit = nodegit; } LFS.prototype = { core, checkout, clone, dependencyCheck, fetch, filters: loadGitattributeFiltersFromRepo, repoHasLfs, initialize, list, register, testPointer, track, prune, pull, push, version, unregister, untrack, }; module.exports = (nodegit) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit); module.exports = _NodeGit; return _NodeGit; };
import initialize from './initialize'; import register from './register'; import unregister from './unregister'; import { core } from './commands/lfsCommands'; import { loadGitattributeFiltersFromRepo, repoHasLfs } from './helpers'; import checkout from './commands/checkout'; import push from './commands/push'; import track from './commands/track'; import untrack from './commands/untrack'; import version from './commands/version'; import fetch from './commands/fetch'; import prune from './commands/prune'; import list from './commands/ls'; import testPointer from './commands/pointer'; import pull from './commands/pull'; import clone from './commands/clone'; import { setNodeBinaryPath } from './utils/authService'; import { dependencyCheck } from './utils/checkDependencies'; function LFS(nodegit) { this.NodeGit = nodegit; } LFS.prototype = { core, checkout, clone, dependencyCheck, fetch, filters: loadGitattributeFiltersFromRepo, repoHasLfs, initialize, list, register, testPointer, track, prune, pull, push, version, unregister, untrack, }; module.exports = (nodegit, nodeBinaryPath) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit); module.exports = _NodeGit; if (nodeBinaryPath) { setNodeBinaryPath(nodeBinaryPath); } return _NodeGit; };
7
1
3
mixed
--- a/src/index.js +++ b/src/index.js @@ -16,2 +16,3 @@ import clone from './commands/clone'; +import { setNodeBinaryPath } from './utils/authService'; import { dependencyCheck } from './utils/checkDependencies'; @@ -43,3 +44,3 @@ -module.exports = (nodegit) => { +module.exports = (nodegit, nodeBinaryPath) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle @@ -49,2 +50,7 @@ module.exports = _NodeGit; + + if (nodeBinaryPath) { + setNodeBinaryPath(nodeBinaryPath); + } + return _NodeGit;
--- a/src/index.js +++ b/src/index.js @@ ... @@ import clone from './commands/clone'; +import { setNodeBinaryPath } from './utils/authService'; import { dependencyCheck } from './utils/checkDependencies'; @@ ... @@ -module.exports = (nodegit) => { +module.exports = (nodegit, nodeBinaryPath) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle @@ ... @@ module.exports = _NodeGit; + + if (nodeBinaryPath) { + setNodeBinaryPath(nodeBinaryPath); + } + return _NodeGit;
--- a/src/index.js +++ b/src/index.js @@ -16,2 +16,3 @@ CON import clone from './commands/clone'; ADD import { setNodeBinaryPath } from './utils/authService'; CON import { dependencyCheck } from './utils/checkDependencies'; @@ -43,3 +44,3 @@ CON DEL module.exports = (nodegit) => { ADD module.exports = (nodegit, nodeBinaryPath) => { CON const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle @@ -49,2 +50,7 @@ CON module.exports = _NodeGit; ADD ADD if (nodeBinaryPath) { ADD setNodeBinaryPath(nodeBinaryPath); ADD } ADD CON return _NodeGit;
<<<<<<< SEARCH import pull from './commands/pull'; import clone from './commands/clone'; import { dependencyCheck } from './utils/checkDependencies'; ======= import pull from './commands/pull'; import clone from './commands/clone'; import { setNodeBinaryPath } from './utils/authService'; import { dependencyCheck } from './utils/checkDependencies'; >>>>>>> REPLACE <<<<<<< SEARCH }; module.exports = (nodegit) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit); module.exports = _NodeGit; return _NodeGit; }; ======= }; module.exports = (nodegit, nodeBinaryPath) => { const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit); module.exports = _NodeGit; if (nodeBinaryPath) { setNodeBinaryPath(nodeBinaryPath); } return _NodeGit; }; >>>>>>> REPLACE
maghoff/bart
d26c8525f35017e3464ce55b588617424a8593f7
libs/stach_derive/src/lib.rs
rust
mit
Use ast.generics.split_for_impl() to correctly generate impl with any generic parameters
#![feature(proc_macro)] #![feature(proc_macro_lib)] #![recursion_limit = "128"] #[macro_use] extern crate quote; extern crate proc_macro; extern crate syn; use proc_macro::TokenStream; // Yield mock generated code for template // Hello, {{name}} ({{age}}) #[proc_macro_derive(StacheDisplay)] pub fn stache_display(input: TokenStream) -> TokenStream { let s = input.to_string(); let ast = syn::parse_macro_input(&s).unwrap(); let type_name = &ast.ident; let generics = &ast.generics; let gen = quote! { impl #generics std::fmt::Display for #type_name #generics { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use display_html_safe::DisplayHtmlSafe; f.write_str("Hello, ")?; DisplayHtmlSafe::fmt(&self.name, f)?; f.write_str(" (")?; DisplayHtmlSafe::fmt(&self.age, f)?; f.write_str(")\n")?; Ok(()) } } }; gen.parse().unwrap() } #[cfg(test)] mod tests { #[test] fn it_works() { } }
#![feature(proc_macro)] #![feature(proc_macro_lib)] #![recursion_limit = "128"] #[macro_use] extern crate quote; extern crate proc_macro; extern crate syn; use proc_macro::TokenStream; // Yield mock generated code for template // Hello, {{name}} ({{age}}) #[proc_macro_derive(StacheDisplay)] pub fn stache_display(input: TokenStream) -> TokenStream { let s = input.to_string(); let ast = syn::parse_macro_input(&s).unwrap(); let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let gen = quote! { impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use display_html_safe::DisplayHtmlSafe; f.write_str("Hello, ")?; DisplayHtmlSafe::fmt(&self.name, f)?; f.write_str(" (")?; DisplayHtmlSafe::fmt(&self.age, f)?; f.write_str(")\n")?; Ok(()) } } }; gen.parse().unwrap() } #[cfg(test)] mod tests { #[test] fn it_works() { } }
3
3
1
mixed
--- a/libs/stach_derive/src/lib.rs +++ b/libs/stach_derive/src/lib.rs @@ -18,7 +18,7 @@ - let type_name = &ast.ident; - let generics = &ast.generics; + let name = &ast.ident; + let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let gen = quote! { - impl #generics std::fmt::Display for #type_name #generics { + impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
--- a/libs/stach_derive/src/lib.rs +++ b/libs/stach_derive/src/lib.rs @@ ... @@ - let type_name = &ast.ident; - let generics = &ast.generics; + let name = &ast.ident; + let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let gen = quote! { - impl #generics std::fmt::Display for #type_name #generics { + impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
--- a/libs/stach_derive/src/lib.rs +++ b/libs/stach_derive/src/lib.rs @@ -18,7 +18,7 @@ CON DEL let type_name = &ast.ident; DEL let generics = &ast.generics; ADD let name = &ast.ident; ADD let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); CON CON let gen = quote! { DEL impl #generics std::fmt::Display for #type_name #generics { ADD impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause { CON fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
<<<<<<< SEARCH let ast = syn::parse_macro_input(&s).unwrap(); let type_name = &ast.ident; let generics = &ast.generics; let gen = quote! { impl #generics std::fmt::Display for #type_name #generics { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use display_html_safe::DisplayHtmlSafe; ======= let ast = syn::parse_macro_input(&s).unwrap(); let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let gen = quote! { impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use display_html_safe::DisplayHtmlSafe; >>>>>>> REPLACE
sdroege/rsplugin
58322bcc962edfc0f772275f03bea5a2419476b6
net/hlssink3/src/lib.rs
rust
apache-2.0
Fix license in hlssink3 plugin
// // Copyright (C) 2021 Rafael Caricio <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License, v2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at // <https://mozilla.org/MPL/2.0/>. // // SPDX-License-Identifier: MPL-2.0 use glib::prelude::*; mod imp; mod playlist; glib::wrapper! { pub struct HlsSink3(ObjectSubclass<imp::HlsSink3>) @extends gst::Bin, gst::Element, gst::Object; } unsafe impl Send for HlsSink3 {} unsafe impl Sync for HlsSink3 {} pub fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "hlssink3", gst::Rank::None, HlsSink3::static_type(), )?; Ok(()) } gst::plugin_define!( hlssink3, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") );
// // Copyright (C) 2021 Rafael Caricio <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License, v2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at // <https://mozilla.org/MPL/2.0/>. // // SPDX-License-Identifier: MPL-2.0 use glib::prelude::*; mod imp; mod playlist; glib::wrapper! { pub struct HlsSink3(ObjectSubclass<imp::HlsSink3>) @extends gst::Bin, gst::Element, gst::Object; } unsafe impl Send for HlsSink3 {} unsafe impl Sync for HlsSink3 {} pub fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "hlssink3", gst::Rank::None, HlsSink3::static_type(), )?; Ok(()) } gst::plugin_define!( hlssink3, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), // FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known) "MPL", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") );
2
1
1
mixed
--- a/net/hlssink3/src/lib.rs +++ b/net/hlssink3/src/lib.rs @@ -37,3 +37,4 @@ concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), - "MIT/X11", + // FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known) + "MPL", env!("CARGO_PKG_NAME"),
--- a/net/hlssink3/src/lib.rs +++ b/net/hlssink3/src/lib.rs @@ ... @@ concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), - "MIT/X11", + // FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known) + "MPL", env!("CARGO_PKG_NAME"),
--- a/net/hlssink3/src/lib.rs +++ b/net/hlssink3/src/lib.rs @@ -37,3 +37,4 @@ CON concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), DEL "MIT/X11", ADD // FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known) ADD "MPL", CON env!("CARGO_PKG_NAME"),
<<<<<<< SEARCH plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), ======= plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), // FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known) "MPL", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), >>>>>>> REPLACE
drhee/toxoMine
4eb4250c3b71c7d687c571b784b9d66b987f0cf4
intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java
java
lgpl-2.1
Support more than one type of token. This is going to be important for producing decent perma-links to result sets, that can be reliably run at various times in the future by anyone with the link without compromising the user account of the profile involved. Former-commit-id: d0e6996717c9871224411b99f8242a101270b897
package org.intermine.webservice.server.user; import java.util.Arrays; import java.util.Map; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.webservice.server.core.JSONService; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; import org.intermine.webservice.server.output.JSONFormatter; public class TokenService extends JSONService { private static final String DENIAL_MSG = "All token requests must be authenticated."; public TokenService(InterMineAPI im) { super(im); } @Override protected void execute() throws Exception { final ProfileManager pm = im.getProfileManager(); Profile profile = getPermission().getProfile(); String token = pm.generate24hrKey(profile); output.addResultItem(Arrays.asList("\"" + token + "\"")); } @Override protected void validateState() { if (!isAuthenticated()) { throw new ServiceForbiddenException(DENIAL_MSG); } } @Override protected Map<String, Object> getHeaderAttributes() { Map<String, Object> retval = super.getHeaderAttributes(); retval.put(JSONFormatter.KEY_INTRO, "\"token\":"); return retval; } }
package org.intermine.webservice.server.user; import java.util.Arrays; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.webservice.server.core.JSONService; import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; public class TokenService extends JSONService { private static final String DENIAL_MSG = "All token requests must be authenticated."; public TokenService(InterMineAPI im) { super(im); } @Override protected void execute() throws Exception { final ProfileManager pm = im.getProfileManager(); Profile profile = getPermission().getProfile(); String tokenType = getOptionalParameter("type", "day").toLowerCase(); String token = null; if ("day".equals(tokenType)) { token = pm.generate24hrKey(profile); } else if ("perma".equals(tokenType)) { token = pm.generateReadOnlyAccessToken(profile); } else { throw new BadRequestException("Unknown token type: " + tokenType); } addResultValue(token, false); } @Override protected void validateState() { if (!isAuthenticated()) { throw new ServiceForbiddenException(DENIAL_MSG); } } @Override protected String getResultsKey() { return "token"; } }
13
10
4
mixed
--- a/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java +++ b/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java @@ -3,3 +3,2 @@ import java.util.Arrays; -import java.util.Map; @@ -9,4 +8,4 @@ import org.intermine.webservice.server.core.JSONService; +import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; -import org.intermine.webservice.server.output.JSONFormatter; @@ -25,5 +24,12 @@ Profile profile = getPermission().getProfile(); - - String token = pm.generate24hrKey(profile); - output.addResultItem(Arrays.asList("\"" + token + "\"")); + String tokenType = getOptionalParameter("type", "day").toLowerCase(); + String token = null; + if ("day".equals(tokenType)) { + token = pm.generate24hrKey(profile); + } else if ("perma".equals(tokenType)) { + token = pm.generateReadOnlyAccessToken(profile); + } else { + throw new BadRequestException("Unknown token type: " + tokenType); + } + addResultValue(token, false); } @@ -38,8 +44,5 @@ @Override - protected Map<String, Object> getHeaderAttributes() { - Map<String, Object> retval = super.getHeaderAttributes(); - retval.put(JSONFormatter.KEY_INTRO, "\"token\":"); - return retval; + protected String getResultsKey() { + return "token"; } - }
--- a/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java +++ b/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java @@ ... @@ import java.util.Arrays; -import java.util.Map; @@ ... @@ import org.intermine.webservice.server.core.JSONService; +import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; -import org.intermine.webservice.server.output.JSONFormatter; @@ ... @@ Profile profile = getPermission().getProfile(); - - String token = pm.generate24hrKey(profile); - output.addResultItem(Arrays.asList("\"" + token + "\"")); + String tokenType = getOptionalParameter("type", "day").toLowerCase(); + String token = null; + if ("day".equals(tokenType)) { + token = pm.generate24hrKey(profile); + } else if ("perma".equals(tokenType)) { + token = pm.generateReadOnlyAccessToken(profile); + } else { + throw new BadRequestException("Unknown token type: " + tokenType); + } + addResultValue(token, false); } @@ ... @@ @Override - protected Map<String, Object> getHeaderAttributes() { - Map<String, Object> retval = super.getHeaderAttributes(); - retval.put(JSONFormatter.KEY_INTRO, "\"token\":"); - return retval; + protected String getResultsKey() { + return "token"; } - }
--- a/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java +++ b/intermine/web/main/src/org/intermine/webservice/server/user/TokenService.java @@ -3,3 +3,2 @@ CON import java.util.Arrays; DEL import java.util.Map; CON @@ -9,4 +8,4 @@ CON import org.intermine.webservice.server.core.JSONService; ADD import org.intermine.webservice.server.exceptions.BadRequestException; CON import org.intermine.webservice.server.exceptions.ServiceForbiddenException; DEL import org.intermine.webservice.server.output.JSONFormatter; CON @@ -25,5 +24,12 @@ CON Profile profile = getPermission().getProfile(); DEL DEL String token = pm.generate24hrKey(profile); DEL output.addResultItem(Arrays.asList("\"" + token + "\"")); ADD String tokenType = getOptionalParameter("type", "day").toLowerCase(); ADD String token = null; ADD if ("day".equals(tokenType)) { ADD token = pm.generate24hrKey(profile); ADD } else if ("perma".equals(tokenType)) { ADD token = pm.generateReadOnlyAccessToken(profile); ADD } else { ADD throw new BadRequestException("Unknown token type: " + tokenType); ADD } ADD addResultValue(token, false); CON } @@ -38,8 +44,5 @@ CON @Override DEL protected Map<String, Object> getHeaderAttributes() { DEL Map<String, Object> retval = super.getHeaderAttributes(); DEL retval.put(JSONFormatter.KEY_INTRO, "\"token\":"); DEL return retval; ADD protected String getResultsKey() { ADD return "token"; CON } DEL CON }
<<<<<<< SEARCH import java.util.Arrays; import java.util.Map; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.webservice.server.core.JSONService; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; import org.intermine.webservice.server.output.JSONFormatter; public class TokenService extends JSONService { ======= import java.util.Arrays; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.webservice.server.core.JSONService; import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.exceptions.ServiceForbiddenException; public class TokenService extends JSONService { >>>>>>> REPLACE <<<<<<< SEARCH final ProfileManager pm = im.getProfileManager(); Profile profile = getPermission().getProfile(); String token = pm.generate24hrKey(profile); output.addResultItem(Arrays.asList("\"" + token + "\"")); } ======= final ProfileManager pm = im.getProfileManager(); Profile profile = getPermission().getProfile(); String tokenType = getOptionalParameter("type", "day").toLowerCase(); String token = null; if ("day".equals(tokenType)) { token = pm.generate24hrKey(profile); } else if ("perma".equals(tokenType)) { token = pm.generateReadOnlyAccessToken(profile); } else { throw new BadRequestException("Unknown token type: " + tokenType); } addResultValue(token, false); } >>>>>>> REPLACE <<<<<<< SEARCH @Override protected Map<String, Object> getHeaderAttributes() { Map<String, Object> retval = super.getHeaderAttributes(); retval.put(JSONFormatter.KEY_INTRO, "\"token\":"); return retval; } } ======= @Override protected String getResultsKey() { return "token"; } } >>>>>>> REPLACE
P1X-in/Tanks-of-Freedom-Server
23d50e82212eb02a3ba467ae323736e4f03f7293
tof_server/views.py
python
mit
Insert new player data into db
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) return jsonify({ 'id' : 'somestubid', 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500) finally: cursor.close()
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin)) cursor.execute(id_sql) insert_data = cursor.fetchone() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500) finally: cursor.close()
9
1
1
mixed
--- a/tof_server/views.py +++ b/tof_server/views.py @@ -24,4 +24,12 @@ + insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" + id_sql = "SELECT LAST_INSERT_ID()" + + cursor.execute(insert_sql, (new_pin)) + cursor.execute(id_sql) + + insert_data = cursor.fetchone() + return jsonify({ - 'id' : 'somestubid', + 'id' : insert_data[0], 'pin' : new_pin
--- a/tof_server/views.py +++ b/tof_server/views.py @@ ... @@ + insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" + id_sql = "SELECT LAST_INSERT_ID()" + + cursor.execute(insert_sql, (new_pin)) + cursor.execute(id_sql) + + insert_data = cursor.fetchone() + return jsonify({ - 'id' : 'somestubid', + 'id' : insert_data[0], 'pin' : new_pin
--- a/tof_server/views.py +++ b/tof_server/views.py @@ -24,4 +24,12 @@ CON ADD insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" ADD id_sql = "SELECT LAST_INSERT_ID()" ADD ADD cursor.execute(insert_sql, (new_pin)) ADD cursor.execute(id_sql) ADD ADD insert_data = cursor.fetchone() ADD CON return jsonify({ DEL 'id' : 'somestubid', ADD 'id' : insert_data[0], CON 'pin' : new_pin
<<<<<<< SEARCH new_pin = new_pin + random.SystemRandom().choice(characters_pool) return jsonify({ 'id' : 'somestubid', 'pin' : new_pin }) ======= new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin)) cursor.execute(id_sql) insert_data = cursor.fetchone() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) >>>>>>> REPLACE
stepancheg/rust-protobuf
ddb5e53c085c6b1e55b733d993c351d5c091c081
test-crates/protobuf-test/src/v3/test_optional.rs
rust
mit
Test proto3 oneof field types
use protobuf::MessageFull; use super::test_optional_pb::*; #[test] fn test() { let _message = TestOptionalProto3::new(); } #[test] fn reflect_all_oneofs() { let descriptor = TestOptionalProto3::descriptor_static(); let oneofs = descriptor.all_oneofs().collect::<Vec<_>>(); assert!(oneofs.len() > 1); assert!(!oneofs[0].is_synthetic()); for oneof in &oneofs[1..] { assert!(oneof.is_synthetic()); let mut fields = oneof.fields().collect::<Vec<_>>(); assert_eq!(1, fields.len()); let field = fields.swap_remove(0); assert_eq!(None, field.containing_oneof()); assert_eq!( Some(oneof), field.containing_oneof_including_synthetic().as_ref() ); } } #[test] fn reflect_oneofs() { let descriptor = TestOptionalProto3::descriptor_static(); let oneofs = descriptor.oneofs().collect::<Vec<_>>(); assert_eq!(1, oneofs.len()); assert!(!oneofs[0].is_synthetic()); }
use protobuf::MessageFull; use super::test_optional_pb::*; #[test] fn test() { let _message = TestOptionalProto3::new(); } #[test] fn field_types() { let message = TestOptionalProto3::new(); let _iii: &Option<i32> = &message.iii; let _sss: &Option<String> = &message.sss; } #[test] fn reflect_all_oneofs() { let descriptor = TestOptionalProto3::descriptor_static(); let oneofs = descriptor.all_oneofs().collect::<Vec<_>>(); assert!(oneofs.len() > 1); assert!(!oneofs[0].is_synthetic()); for oneof in &oneofs[1..] { assert!(oneof.is_synthetic()); let mut fields = oneof.fields().collect::<Vec<_>>(); assert_eq!(1, fields.len()); let field = fields.swap_remove(0); assert_eq!(None, field.containing_oneof()); assert_eq!( Some(oneof), field.containing_oneof_including_synthetic().as_ref() ); } } #[test] fn reflect_oneofs() { let descriptor = TestOptionalProto3::descriptor_static(); let oneofs = descriptor.oneofs().collect::<Vec<_>>(); assert_eq!(1, oneofs.len()); assert!(!oneofs[0].is_synthetic()); }
7
0
1
add_only
--- a/test-crates/protobuf-test/src/v3/test_optional.rs +++ b/test-crates/protobuf-test/src/v3/test_optional.rs @@ -7,2 +7,9 @@ let _message = TestOptionalProto3::new(); +} + +#[test] +fn field_types() { + let message = TestOptionalProto3::new(); + let _iii: &Option<i32> = &message.iii; + let _sss: &Option<String> = &message.sss; }
--- a/test-crates/protobuf-test/src/v3/test_optional.rs +++ b/test-crates/protobuf-test/src/v3/test_optional.rs @@ ... @@ let _message = TestOptionalProto3::new(); +} + +#[test] +fn field_types() { + let message = TestOptionalProto3::new(); + let _iii: &Option<i32> = &message.iii; + let _sss: &Option<String> = &message.sss; }
--- a/test-crates/protobuf-test/src/v3/test_optional.rs +++ b/test-crates/protobuf-test/src/v3/test_optional.rs @@ -7,2 +7,9 @@ CON let _message = TestOptionalProto3::new(); ADD } ADD ADD #[test] ADD fn field_types() { ADD let message = TestOptionalProto3::new(); ADD let _iii: &Option<i32> = &message.iii; ADD let _sss: &Option<String> = &message.sss; CON }
<<<<<<< SEARCH fn test() { let _message = TestOptionalProto3::new(); } ======= fn test() { let _message = TestOptionalProto3::new(); } #[test] fn field_types() { let message = TestOptionalProto3::new(); let _iii: &Option<i32> = &message.iii; let _sss: &Option<String> = &message.sss; } >>>>>>> REPLACE
MarkEWaite/git-plugin
9f835ec59fbe00cd131d7d84df47ac1e986759b2
src/main/java/hudson/plugins/git/SubmoduleConfig.java
java
mit
Return copy of String array rather than returning internal String array Findbugs correctly complains that returning the internal String array exposes internal implementation to callers.
package hudson.plugins.git; import com.google.common.base.Joiner; import java.util.regex.Pattern; public class SubmoduleConfig implements java.io.Serializable { private static final long serialVersionUID = 1L; String submoduleName; String[] branches; public String getSubmoduleName() { return submoduleName; } public void setSubmoduleName(String submoduleName) { this.submoduleName = submoduleName; } public String[] getBranches() { return branches; } public void setBranches(String[] branches) { this.branches = branches; } public boolean revisionMatchesInterest(Revision r) { for (Branch br : r.getBranches()) { if (branchMatchesInterest(br)) return true; } return false; } public boolean branchMatchesInterest(Branch br) { for (String regex : branches) { if (!Pattern.matches(regex, br.getName())) { return false; } } return true; } public String getBranchesString() { return Joiner.on(',').join(branches); } }
package hudson.plugins.git; import com.google.common.base.Joiner; import java.util.Arrays; import java.util.regex.Pattern; public class SubmoduleConfig implements java.io.Serializable { private static final long serialVersionUID = 1L; String submoduleName; String[] branches; public String getSubmoduleName() { return submoduleName; } public void setSubmoduleName(String submoduleName) { this.submoduleName = submoduleName; } public String[] getBranches() { /* findbugs correctly complains that returning branches exposes the * internal representation of the class to callers. Returning a copy * of the array does not expose internal representation, at the possible * expense of some additional memory. */ return Arrays.copyOf(branches, branches.length); } public void setBranches(String[] branches) { /* findbugs correctly complains that assign to branches exposes the * internal representation of the class to callers. Assigning a copy * of the array does not expose internal representation, at the possible * expense of some additional memory. */ this.branches = Arrays.copyOf(branches, branches.length); } public boolean revisionMatchesInterest(Revision r) { for (Branch br : r.getBranches()) { if (branchMatchesInterest(br)) return true; } return false; } public boolean branchMatchesInterest(Branch br) { for (String regex : branches) { if (!Pattern.matches(regex, br.getName())) { return false; } } return true; } public String getBranchesString() { return Joiner.on(',').join(branches); } }
13
2
3
mixed
--- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java +++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java @@ -3,2 +3,3 @@ import com.google.common.base.Joiner; +import java.util.Arrays; @@ -20,3 +21,8 @@ public String[] getBranches() { - return branches; + /* findbugs correctly complains that returning branches exposes the + * internal representation of the class to callers. Returning a copy + * of the array does not expose internal representation, at the possible + * expense of some additional memory. + */ + return Arrays.copyOf(branches, branches.length); } @@ -24,3 +30,8 @@ public void setBranches(String[] branches) { - this.branches = branches; + /* findbugs correctly complains that assign to branches exposes the + * internal representation of the class to callers. Assigning a copy + * of the array does not expose internal representation, at the possible + * expense of some additional memory. + */ + this.branches = Arrays.copyOf(branches, branches.length); }
--- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java +++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java @@ ... @@ import com.google.common.base.Joiner; +import java.util.Arrays; @@ ... @@ public String[] getBranches() { - return branches; + /* findbugs correctly complains that returning branches exposes the + * internal representation of the class to callers. Returning a copy + * of the array does not expose internal representation, at the possible + * expense of some additional memory. + */ + return Arrays.copyOf(branches, branches.length); } @@ ... @@ public void setBranches(String[] branches) { - this.branches = branches; + /* findbugs correctly complains that assign to branches exposes the + * internal representation of the class to callers. Assigning a copy + * of the array does not expose internal representation, at the possible + * expense of some additional memory. + */ + this.branches = Arrays.copyOf(branches, branches.length); }
--- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java +++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java @@ -3,2 +3,3 @@ CON import com.google.common.base.Joiner; ADD import java.util.Arrays; CON @@ -20,3 +21,8 @@ CON public String[] getBranches() { DEL return branches; ADD /* findbugs correctly complains that returning branches exposes the ADD * internal representation of the class to callers. Returning a copy ADD * of the array does not expose internal representation, at the possible ADD * expense of some additional memory. ADD */ ADD return Arrays.copyOf(branches, branches.length); CON } @@ -24,3 +30,8 @@ CON public void setBranches(String[] branches) { DEL this.branches = branches; ADD /* findbugs correctly complains that assign to branches exposes the ADD * internal representation of the class to callers. Assigning a copy ADD * of the array does not expose internal representation, at the possible ADD * expense of some additional memory. ADD */ ADD this.branches = Arrays.copyOf(branches, branches.length); CON }
<<<<<<< SEARCH import com.google.common.base.Joiner; import java.util.regex.Pattern; ======= import com.google.common.base.Joiner; import java.util.Arrays; import java.util.regex.Pattern; >>>>>>> REPLACE <<<<<<< SEARCH public String[] getBranches() { return branches; } public void setBranches(String[] branches) { this.branches = branches; } ======= public String[] getBranches() { /* findbugs correctly complains that returning branches exposes the * internal representation of the class to callers. Returning a copy * of the array does not expose internal representation, at the possible * expense of some additional memory. */ return Arrays.copyOf(branches, branches.length); } public void setBranches(String[] branches) { /* findbugs correctly complains that assign to branches exposes the * internal representation of the class to callers. Assigning a copy * of the array does not expose internal representation, at the possible * expense of some additional memory. */ this.branches = Arrays.copyOf(branches, branches.length); } >>>>>>> REPLACE
jenslind/piglet
fba1d71e583e3a539839c28f5613569da0722e3d
lib/Grunt.js
javascript
mit
Use callback instead of sync
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn global.processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) } exports.runTask = function (task, cb) { // Stop task if running if (global.processes[task]) { global.processes[task].kill() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save global.processes[task] = command cb() // Remove when done command.on('close', function () { delete global.processes[task] cb() }) }
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn global.processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { if (err) return resolve([]) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) }) } exports.runTask = function (task, cb) { // Stop task if running if (global.processes[task]) { global.processes[task].kill() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save global.processes[task] = command cb() // Remove when done command.on('close', function () { delete global.processes[task] cb() }) }
11
8
1
mixed
--- a/lib/Grunt.js +++ b/lib/Grunt.js @@ -10,13 +10,16 @@ return new Promise(function (resolve, reject) { - const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) - grunt.init(gruntfile) - let tasks = JSON.parse(grunt.getJsonTasks()) + fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { + if (err) return resolve([]) - let taskList = [] + grunt.init(gruntfile) + let tasks = JSON.parse(grunt.getJsonTasks()) - for (let task in tasks) { - taskList.push(task) - } + let taskList = [] - return resolve(taskList) + for (let task in tasks) { + taskList.push(task) + } + + return resolve(taskList) + }) })
--- a/lib/Grunt.js +++ b/lib/Grunt.js @@ ... @@ return new Promise(function (resolve, reject) { - const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) - grunt.init(gruntfile) - let tasks = JSON.parse(grunt.getJsonTasks()) + fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { + if (err) return resolve([]) - let taskList = [] + grunt.init(gruntfile) + let tasks = JSON.parse(grunt.getJsonTasks()) - for (let task in tasks) { - taskList.push(task) - } + let taskList = [] - return resolve(taskList) + for (let task in tasks) { + taskList.push(task) + } + + return resolve(taskList) + }) })
--- a/lib/Grunt.js +++ b/lib/Grunt.js @@ -10,13 +10,16 @@ CON return new Promise(function (resolve, reject) { DEL const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) DEL grunt.init(gruntfile) DEL let tasks = JSON.parse(grunt.getJsonTasks()) ADD fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { ADD if (err) return resolve([]) CON DEL let taskList = [] ADD grunt.init(gruntfile) ADD let tasks = JSON.parse(grunt.getJsonTasks()) CON DEL for (let task in tasks) { DEL taskList.push(task) DEL } ADD let taskList = [] CON DEL return resolve(taskList) ADD for (let task in tasks) { ADD taskList.push(task) ADD } ADD ADD return resolve(taskList) ADD }) CON })
<<<<<<< SEARCH exports.getTasks = function () { return new Promise(function (resolve, reject) { const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) } ======= exports.getTasks = function () { return new Promise(function (resolve, reject) { fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { if (err) return resolve([]) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) }) } >>>>>>> REPLACE
has2k1/onelib
2015233d252e625419485c269f1f70a7e0edada8
skmisc/__init__.py
python
bsd-3-clause
Fix pytest path to root of package Instead of the package init file.
from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: from skmisc.__config__ import show as show_config # noqa: F401 # try: # from skmisc.__config__ import show as show_config # noqa: F401 # except ImportError: # msg = """Error importing skmisc: you cannot import skmisc while # being in skmisc source directory; please exit the skmisc source # tree first, and relaunch your python intepreter.""" # raise ImportError(msg) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.realpath(__file__) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: try: from skmisc.__config__ import show as show_config # noqa: F401 except ImportError as err: msg = """Error importing skmisc: you cannot import skmisc while being in skmisc source directory; please exit the skmisc source tree first, and relaunch your python intepreter.""" raise ImportError('\n\n'.join([err.message, msg])) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.dirname(os.path.realpath(__file__)) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
8
9
2
mixed
--- a/skmisc/__init__.py +++ b/skmisc/__init__.py @@ -19,10 +19,9 @@ else: - from skmisc.__config__ import show as show_config # noqa: F401 - # try: - # from skmisc.__config__ import show as show_config # noqa: F401 - # except ImportError: - # msg = """Error importing skmisc: you cannot import skmisc while - # being in skmisc source directory; please exit the skmisc source - # tree first, and relaunch your python intepreter.""" - # raise ImportError(msg) + try: + from skmisc.__config__ import show as show_config # noqa: F401 + except ImportError as err: + msg = """Error importing skmisc: you cannot import skmisc while + being in skmisc source directory; please exit the skmisc source + tree first, and relaunch your python intepreter.""" + raise ImportError('\n\n'.join([err.message, msg])) @@ -43,3 +42,3 @@ raise ImportError(msg) - path = os.path.realpath(__file__) + path = os.path.dirname(os.path.realpath(__file__)) if args is None:
--- a/skmisc/__init__.py +++ b/skmisc/__init__.py @@ ... @@ else: - from skmisc.__config__ import show as show_config # noqa: F401 - # try: - # from skmisc.__config__ import show as show_config # noqa: F401 - # except ImportError: - # msg = """Error importing skmisc: you cannot import skmisc while - # being in skmisc source directory; please exit the skmisc source - # tree first, and relaunch your python intepreter.""" - # raise ImportError(msg) + try: + from skmisc.__config__ import show as show_config # noqa: F401 + except ImportError as err: + msg = """Error importing skmisc: you cannot import skmisc while + being in skmisc source directory; please exit the skmisc source + tree first, and relaunch your python intepreter.""" + raise ImportError('\n\n'.join([err.message, msg])) @@ ... @@ raise ImportError(msg) - path = os.path.realpath(__file__) + path = os.path.dirname(os.path.realpath(__file__)) if args is None:
--- a/skmisc/__init__.py +++ b/skmisc/__init__.py @@ -19,10 +19,9 @@ CON else: DEL from skmisc.__config__ import show as show_config # noqa: F401 DEL # try: DEL # from skmisc.__config__ import show as show_config # noqa: F401 DEL # except ImportError: DEL # msg = """Error importing skmisc: you cannot import skmisc while DEL # being in skmisc source directory; please exit the skmisc source DEL # tree first, and relaunch your python intepreter.""" DEL # raise ImportError(msg) ADD try: ADD from skmisc.__config__ import show as show_config # noqa: F401 ADD except ImportError as err: ADD msg = """Error importing skmisc: you cannot import skmisc while ADD being in skmisc source directory; please exit the skmisc source ADD tree first, and relaunch your python intepreter.""" ADD raise ImportError('\n\n'.join([err.message, msg])) CON @@ -43,3 +42,3 @@ CON raise ImportError(msg) DEL path = os.path.realpath(__file__) ADD path = os.path.dirname(os.path.realpath(__file__)) CON if args is None:
<<<<<<< SEARCH del _sys else: from skmisc.__config__ import show as show_config # noqa: F401 # try: # from skmisc.__config__ import show as show_config # noqa: F401 # except ImportError: # msg = """Error importing skmisc: you cannot import skmisc while # being in skmisc source directory; please exit the skmisc source # tree first, and relaunch your python intepreter.""" # raise ImportError(msg) __all__.append('show_config') ======= del _sys else: try: from skmisc.__config__ import show as show_config # noqa: F401 except ImportError as err: msg = """Error importing skmisc: you cannot import skmisc while being in skmisc source directory; please exit the skmisc source tree first, and relaunch your python intepreter.""" raise ImportError('\n\n'.join([err.message, msg])) __all__.append('show_config') >>>>>>> REPLACE <<<<<<< SEARCH msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.realpath(__file__) if args is None: args = [path] ======= msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.dirname(os.path.realpath(__file__)) if args is None: args = [path] >>>>>>> REPLACE
chimbori/crux
2f1fda990f30b7089add690599715a653da4fe6b
build.gradle.kts
kotlin
apache-2.0
Add missing dependency on `ExplicitApiMode.Strict`
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.6.20" id("com.vanniktech.maven.publish") version "0.19.0" id("com.github.ben-manes.versions") version "0.42.0" } repositories { mavenCentral() } buildscript { repositories { mavenCentral() } dependencies { classpath(kotlin("gradle-plugin", version = "1.6.20")) classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0") classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0") } } dependencies { api("org.jsoup:jsoup:1.14.3") api("com.squareup.okhttp3:okhttp:4.9.3") implementation("org.apache.commons:commons-text:1.9") testImplementation("junit:junit:4.13.2") } configurations.all { // Re-run tests every time test cases are updated, even if sources haven’t changed. resolutionStrategy.cacheChangingModulesFor(0, "seconds") } tasks.jar { archiveBaseName.set("crux") } tasks.withType<KotlinCompile>().configureEach { kotlinOptions { allWarningsAsErrors = true } } kotlin { explicitApi = Strict }
import org.jetbrains.kotlin.gradle.dsl.ExplicitApiMode.Strict import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.6.20" id("com.vanniktech.maven.publish") version "0.19.0" id("com.github.ben-manes.versions") version "0.42.0" } repositories { mavenCentral() } buildscript { repositories { mavenCentral() } dependencies { classpath(kotlin("gradle-plugin", version = "1.6.20")) classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0") classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0") } } dependencies { api("org.jsoup:jsoup:1.14.3") api("com.squareup.okhttp3:okhttp:4.9.3") implementation("org.apache.commons:commons-text:1.9") testImplementation("junit:junit:4.13.2") } configurations.all { // Re-run tests every time test cases are updated, even if sources haven’t changed. resolutionStrategy.cacheChangingModulesFor(0, "seconds") } tasks.jar { archiveBaseName.set("crux") } tasks.withType<KotlinCompile>().configureEach { kotlinOptions { allWarningsAsErrors = true } } kotlin { explicitApi = Strict }
1
0
1
add_only
--- a/build.gradle.kts +++ b/build.gradle.kts @@ -1 +1,2 @@ +import org.jetbrains.kotlin.gradle.dsl.ExplicitApiMode.Strict import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
--- a/build.gradle.kts +++ b/build.gradle.kts @@ ... @@ +import org.jetbrains.kotlin.gradle.dsl.ExplicitApiMode.Strict import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
--- a/build.gradle.kts +++ b/build.gradle.kts @@ -1 +1,2 @@ ADD import org.jetbrains.kotlin.gradle.dsl.ExplicitApiMode.Strict CON import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
<<<<<<< SEARCH import org.jetbrains.kotlin.gradle.tasks.KotlinCompile ======= import org.jetbrains.kotlin.gradle.dsl.ExplicitApiMode.Strict import org.jetbrains.kotlin.gradle.tasks.KotlinCompile >>>>>>> REPLACE