问:
Richfaces Datatable Checkbox for Selecting All Rows
I am trying to implement a checkbox header for selecting all richFaces dataTable rows.
setSelction is called but selection.size = 0;
the backing bean is an EntityHome from seam 2.2.2
Any idea why selected rows are not set into selection?

Thanks

```<code><h:form styleClass="association" id="heavyChainsChildren">

<rich:extendedDataTable
                    onRowMouseOver="this.style.backgroundColor='#F1F1F1'"
                    onRowMouseOut="this.style.backgroundColor='#{a4jSkin.tableBackgroundColor}'"
                    value="#{myEntityHome.myData}"
                    selectionMode="multi"
                    selection="#{myEntityHome.selection}"
                    var="entry"
                    rendered="#{not empty myEntityHome.myData}"
                    rowClasses="rvgRowOne,rvgRowTwo"
                    id="myDataTable">

                    <rich:column align="center" width="150px" sortable="false">
                        <f:facet name="header">
                            <h:panelGroup style="width:150px;" layout="block">
                                <script type="text/javascript">
                                    //<![CDATA[
                                    function checkAllCheckboxesInTable(inputId, state) {
                                        var commonIdPart = inputId.substr(0, inputId.lastIndexOf(':'));
                                        var tableId = commonIdPart + ':tu'
                                        var tableElement = document.getElementById(tableId);
                                        var inputs = tableElement.getElementsByTagName('input');
                                        for (var i = 0; i <= inputs.length; i++) {
                                            var input = inputs[i];
                                            if (input.getAttribute('type') == 'checkbox' && state) {
                                                input.setAttribute('checked', state);
                                            } else {
                                                input.removeAttribute('checked');
                                            }
                                        }
                                    }
                                    //]]>
                                </script>
                                <h:selectBooleanCheckbox id="checkAll" title="#{bundle.CHECK_ALL}" onclick="checkAllCheckboxesInTable(this.id, this.checked);">
                                    <a:support event="onchange" reRender="myDataTable"
                                               />
                                </h:selectBooleanCheckbox>
                                <h:outputText value="#{bundle.IDENTITY_CHECKBOX_SELECT_ALL}"/>
                            </h:panelGroup>
                        </f:facet>
                        <h:selectBooleanCheckbox id="checkEntry" value="#{entry.selected}" disabled="false"/>
                    </rich:column>
</code>```

bean:

```<code>@Name("myEntityHome")
public class MyEntityHome extends EntityHome<MyEntity> {

private static final Logger log = LoggerFactory.getLogger(MyEntityHome.class);
private SimpleSelection selection;

public SimpleSelection getSelection() {
    log.info("getSelection called ....");
    return selection;
}

public void setSelection(SimpleSelection selection) {
    log.info("setSelection called ...");
    this.selection = selection;
}
</code>```

答:
You can take advantage of this page.There are more examples richfaces datatable Download war file and import your local workspace.

http://balusc.omnifaces.org/2006/06/using-datatables.html#DownloadWAR

You can do test when you run project in eclipse java platform you can call this url as your local port number. If you don't have java platform you can decompile war file and take neccessary file and crud.jsp

http://localhost:8083/UsingDatatables/crud/crud.jsf

You should look at MyCrudBean.java and crud.jsp files. These codes will handle your problem.

MyCrudBean:

```<code>  private Map<Integer, Boolean> selectedRows = new HashMap<Integer, Boolean>();
  private List<MyData> dataList;

  /**
 * Select all items.
 */
public void actionSelectAll() {

    // Toggle.
    selectAll = !selectAll;

    // Radio buttons doesn't allow multiple selections. Switch to checkboxes.
    if (selectAll) {
        selectMultiple = true;
    }

    // Set selection.
    for (int index = 0; index < dataList.size(); index++) {
        selectedRows.put(index, selectAll);
    }

    log(selectedRows);
}
</code>```

crud.jsp

```<code>                <h:column>
                    <f:facet name="header"><h:outputText value="#{myCrudBundle.headerColumnRowNumber}" /></f:facet>
                    <h:outputText value="#{myCrudBean.dataTable.rowIndex + 1}" />
                </h:column>

                <h:column>
                    <f:facet name="header">
                        <h:commandLink action="#{myCrudBean.actionToggleSelect}" disabled="#{myCrudBean.editMode}" title="#{myCrudBundle.titleToggleSelect}">
                            <h:outputText value="#{myCrudBundle.headerColumnSelect}" />
                        </h:commandLink>
                    </f:facet>
                    <h:selectBooleanCheckbox value="#{myCrudBean.selectedRow}" disabled="#{myCrudBean.editMode}" rendered="#{myCrudBean.selectMultiple}" />
                    <h:selectOneRadio valueChangeListener="#{myCrudBean.setSelectedItem}" disabled="#{myCrudBean.editMode}" rendered="#{!myCrudBean.selectMultiple}" onchange="dataTableSelectOneRadio(this);">
                        <f:selectItem itemValue="null" />
                    </h:selectOneRadio>
                </h:column>

                    <h:column>
                    <f:facet name="header">
                        <h:panelGroup>
                            <h:commandLink actionListener="#{myCrudBean.actionSort}" disabled="#{myCrudBean.editMode}" title="#{myCrudBundle.titleSortName}">
                                <f:attribute name="sortField" value="name" />
                                <h:outputText value="#{myCrudBundle.headerColumnName}" />
                            </h:commandLink>
                            <h:outputText value=" ▲" escape="false" rendered="#{myCrudBean.sortField == 'name' && !myCrudBean.sortAscending}" />
                            <h:outputText value=" ▼" escape="false" rendered="#{myCrudBean.sortField == 'name' && myCrudBean.sortAscending}" />
                        </h:panelGroup>
                    </f:facet>
                    <h:outputText value="#{dataItem.name}" rendered="#{!myCrudBean.editModeRow}" />
                    <h:inputText id="name" value="#{dataItem.name}" rendered="#{myCrudBean.editModeRow}" label="Row ##{myCrudBean.dataTable.rowIndex + 1} Name" required="#{!empty param['crud:table:save']}" styleClass="input" size="15" />
                </h:column>

                <f:facet name="footer">
                    <h:panelGrid columns="4">

                        <h:panelGroup>
                            <h:commandButton value="#{myCrudBundle.buttonSelectAll}" action="#{myCrudBean.actionSelectAll}" rendered="#{!myCrudBean.editMode && !myCrudBean.selectAll}" styleClass="input" />
                            <h:commandButton value="#{myCrudBundle.buttonUnselectAll}" action="#{myCrudBean.actionSelectAll}" rendered="#{!myCrudBean.editMode && myCrudBean.selectAll}" styleClass="input" />

                        </h:panelGroup>
                    </h:panelGrid>
                </f:facet>
            </h:dataTable>

        </h:form>
</code>```

Body:
I am trying to implement a checkbox header for selecting all richFaces dataTable rows.
setSelction is called but selection.size = 0;
the backing bean is an EntityHome from seam 2.2.2
Any idea why selected rows are not set into selection?

Thanks

<h:form styleClass="association" id="heavyChainsChildren">

<rich:extendedDataTable
                    onRowMouseOver="this.style.backgroundColor='#F1F1F1'"
                    onRowMouseOut="this.style.backgroundColor='#{a4jSkin.tableBackgroundColor}'"
                    value="#{myEntityHome.myData}"
                    selectionMode="multi"
                    selection="#{myEntityHome.selection}"
                    var="entry"
                    rendered="#{not empty myEntityHome.myData}"
                    rowClasses="rvgRowOne,rvgRowTwo"
                    id="myDataTable">

                    <rich:column align="center" width="150px" sortable="false">
                        <f:facet name="header">
                            <h:panelGroup style="width:150px;" layout="block">

                                <h:selectBooleanCheckbox id="checkAll" title="#{bundle.CHECK_ALL}" onclick="checkAllCheckboxesInTable(this.id, this.checked);">

                                </h:selectBooleanCheckbox>
                                <h:outputText value="#{bundle.IDENTITY_CHECKBOX_SELECT_ALL}"/>
                            </h:panelGroup>
                        </f:facet>
                        <h:selectBooleanCheckbox id="checkEntry" value="#{entry.selected}" disabled="false"/>
                    </rich:column>

bean:

@Name("myEntityHome")
public class MyEntityHome extends EntityHome<MyEntity> {

private static final Logger log = LoggerFactory.getLogger(MyEntityHome.class);
private SimpleSelection selection;

public SimpleSelection getSelection() {
    log.info("getSelection called ....");
    return selection;
}

public void setSelection(SimpleSelection selection) {
    log.info("setSelection called ...");
    this.selection = selection;
}

Body:
You can take advantage of this page.There are more examples richfaces datatable Download war file and import your local workspace.

http://balusc.omnifaces.org/2006/06/using-datatables.html#DownloadWAR

You can do test when you run project in eclipse java platform you can call this url as your local port number. If you don't have java platform you can decompile war file and take neccessary file and crud.jsp

http://localhost:8083/UsingDatatables/crud/crud.jsf

You should look at MyCrudBean.java and crud.jsp files. These codes will handle your problem.

MyCrudBean:

  private Map<Integer, Boolean> selectedRows = new HashMap<Integer, Boolean>();
  private List<MyData> dataList;

  /**
 * Select all items.
 */
public void actionSelectAll() {

    // Toggle.
    selectAll = !selectAll;

    // Radio buttons doesn't allow multiple selections. Switch to checkboxes.
    if (selectAll) {
        selectMultiple = true;
    }

    // Set selection.
    for (int index = 0; index < dataList.size(); index++) {
        selectedRows.put(index, selectAll);
    }

    log(selectedRows);
}

crud.jsp

                <h:column>
                    <f:facet name="header"><h:outputText value="#{myCrudBundle.headerColumnRowNumber}" /></f:facet>
                    <h:outputText value="#{myCrudBean.dataTable.rowIndex + 1}" />
                </h:column>

                <h:column>
                    <f:facet name="header">
                        <h:commandLink action="#{myCrudBean.actionToggleSelect}" disabled="#{myCrudBean.editMode}" title="#{myCrudBundle.titleToggleSelect}">
                            <h:outputText value="#{myCrudBundle.headerColumnSelect}" />
                        </h:commandLink>
                    </f:facet>
                    <h:selectBooleanCheckbox value="#{myCrudBean.selectedRow}" disabled="#{myCrudBean.editMode}" rendered="#{myCrudBean.selectMultiple}" />
                    <h:selectOneRadio valueChangeListener="#{myCrudBean.setSelectedItem}" disabled="#{myCrudBean.editMode}" rendered="#{!myCrudBean.selectMultiple}" onchange="dataTableSelectOneRadio(this);">
                        <f:selectItem itemValue="null" />
                    </h:selectOneRadio>
                </h:column>

                    <h:column>
                    <f:facet name="header">
                        <h:panelGroup>
                            <h:commandLink actionListener="#{myCrudBean.actionSort}" disabled="#{myCrudBean.editMode}" title="#{myCrudBundle.titleSortName}">
                                <f:attribute name="sortField" value="name" />
                                <h:outputText value="#{myCrudBundle.headerColumnName}" />
                            </h:commandLink>
                            <h:outputText value="&#0160;&#9650;" escape="false" rendered="#{myCrudBean.sortField == 'name' && !myCrudBean.sortAscending}" />
                            <h:outputText value="&#0160;&#9660;" escape="false" rendered="#{myCrudBean.sortField == 'name' && myCrudBean.sortAscending}" />
                        </h:panelGroup>
                    </f:facet>
                    <h:outputText value="#{dataItem.name}" rendered="#{!myCrudBean.editModeRow}" />
                    <h:inputText id="name" value="#{dataItem.name}" rendered="#{myCrudBean.editModeRow}" label="Row ##{myCrudBean.dataTable.rowIndex + 1} Name" required="#{!empty param['crud:table:save']}" styleClass="input" size="15" />
                </h:column>

                <f:facet name="footer">
                    <h:panelGrid columns="4">

                        <h:panelGroup>
                            <h:commandButton value="#{myCrudBundle.buttonSelectAll}" action="#{myCrudBean.actionSelectAll}" rendered="#{!myCrudBean.editMode && !myCrudBean.selectAll}" styleClass="input" />
                            <h:commandButton value="#{myCrudBundle.buttonUnselectAll}" action="#{myCrudBean.actionSelectAll}" rendered="#{!myCrudBean.editMode && myCrudBean.selectAll}" styleClass="input" />

                        </h:panelGroup>
                    </h:panelGrid>
                </f:facet>
            </h:dataTable>

        </h:form>


来源: stackexchange

问:
How to make an infinite stream of x and sin(x) in scheme?
i would like to make an infinite stream (x, f(x), f(f(x),f(f(f(x))),...) and the procedure should take x as an value and f as an procedure. I tried the following code but i don't know if it is true... how can i improve my code? </p>

```<code>(define (f_stream x f) (cons-stream x (f_stream (f x) (lambda (x)
(sin x)) (f x)))) (sin x)) (f x))))

(define (f x) (sin x))
</code>```

答:
What did you is close, but you put extra stuff about 'sin' into it while it should be generic. All you needed was this:

```<code>(define (f_stream x f) (cons-stream x (f_stream (f x) f)))
</code>```

notice f is passed as a function instead of using lambda.

ContentLicense: CC BY-SA 4.0

Body:
i would like to make an infinite stream (x, f(x), f(f(x),f(f(f(x))),...) and the procedure should take x as an value and f as an procedure. I tried the following code but i don't know if it is true... how can i improve my code?

(define (f_stream x f) (cons-stream x (f_stream (f x) (lambda (x)
(sin x)) (f x)))) (sin x)) (f x))))

(define (f x) (sin x))

Body:
What did you is close, but you put extra stuff about 'sin' into it while it should be generic. All you needed was this:

(define (f_stream x f) (cons-stream x (f_stream (f x) f)))

notice f is passed as a function instead of using lambda.


问:
Switch statement using substring of a user's input
Objective: I am trying to ouput a message based on a user's input.

Situation: Basically a user will input a few characters like 5r (5 Red) or 8y (8 Yellow). The notation expected is a digit first and a character after but it is possible that the user doesn't follow the rule.

I used switch statements (part of the exercise) but the output doesn't give me what I expect

Code:

```<code>        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0,1);
        String secondChar = input.substring(1);
        String answer = "";

        switch(firstChar)
        {
            case "0":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "Zero Blue";
                    case "r":
                        answer = "Zero Red";
                    case "g":
                        answer = "Zero Green";
                    case "y":
                        answer = "Zero Yellow";
                }
            }
            case "1":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "One Blue";
                    case "r":
                        answer = "One Red";
                    case "g":
                        answer = "One Green";
                    case "y":
                        answer = "One Yellow";
                }
            }
           ... other case statements....
           default:
              answer = "not valid";
</code>```

When the user writes 0b, my output should be "Zero Blue" but currently it is displaying "not valid". Why?

答:
I suggest not using swich case at all, use hash maps:

```<code>package mypackage;

import java.util.*;

public class MyComputingClass {

    private static Map<Character, String> firstCharMapping;
    private static Map<Character, String> secondCharMapping;

    public static void main(String[] args) {
        initCharMappers();

        System.out.println("Mapping of 0Y : " + mapStuff("0Y"));
        System.out.println("Mapping of 0y : " + mapStuff("0y"));
        System.out.println("Mapping of 0YJ : " + mapStuff("0YJ"));
        System.out.println("Mapping of 2B : " + mapStuff("2B"));
        System.out.println("Mapping of eB : " + mapStuff("eB"));
    }

    private static void initCharMappers() {
        firstCharMapping = new HashMap<>();
        secondCharMapping = new TreeMap<>(Comparator.comparing(Character::toLowerCase));

        firstCharMapping.put('0', "Zero");
        firstCharMapping.put('1', "One");
        firstCharMapping.put('2', "Two");

        secondCharMapping.put('Y', "Yellow");
        secondCharMapping.put('B', "Blue");
        secondCharMapping.put('G', "Green");
    }

    private static String mapStuff(String str) {
        String INVALID_INPUT = "Invalid input";
        if (!str.matches("\\d[a-zA-Z]")) {
            return INVALID_INPUT;
        }

        Character firstChar = str.toCharArray()[0];
        Character secondChar = str.toCharArray()[1];

        if (!firstCharMapping.containsKey(firstChar) || !secondCharMapping.containsKey(secondChar)) {
            return INVALID_INPUT;
        }

        return firstCharMapping.get(firstChar) + " " + secondCharMapping.get(secondChar);
    }
}
</code>```

Output :

```<code>Mapping of 0Y : Zero Yellow
Mapping of 0y : Zero Yellow
Mapping of 0YJ : Invalid input
Mapping of 2B : Two Blue
Mapping of eB : Invalid input
</code>```

Body:
Objective: I am trying to ouput a message based on a user's input.

Situation: Basically a user will input a few characters like 5r (5 Red) or 8y (8 Yellow). The notation expected is a digit first and a character after but it is possible that the user doesn't follow the rule.

I used switch statements (part of the exercise) but the output doesn't give me what I expect

Code:

        String input = reader.nextLine().toLowerCase();
        String firstChar = input.substring(0,1);
        String secondChar = input.substring(1);
        String answer = "";

        switch(firstChar)
        {
            case "0":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "Zero Blue";
                    case "r":
                        answer = "Zero Red";
                    case "g":
                        answer = "Zero Green";
                    case "y":
                        answer = "Zero Yellow";
                }
            }
            case "1":
            {
                switch(secondChar)
                {
                    case "b":
                        answer = "One Blue";
                    case "r":
                        answer = "One Red";
                    case "g":
                        answer = "One Green";
                    case "y":
                        answer = "One Yellow";
                }
            }
           ... other case statements....
           default:
              answer = "not valid";

When the user writes 0b, my output should be "Zero Blue" but currently it is displaying "not valid". Why?

Body:
I suggest not using swich case at all, use hash maps:

package mypackage;

import java.util.*;

public class MyComputingClass {

    private static Map<Character, String> firstCharMapping;
    private static Map<Character, String> secondCharMapping;

    public static void main(String[] args) {
        initCharMappers();

        System.out.println("Mapping of 0Y : " + mapStuff("0Y"));
        System.out.println("Mapping of 0y : " + mapStuff("0y"));
        System.out.println("Mapping of 0YJ : " + mapStuff("0YJ"));
        System.out.println("Mapping of 2B : " + mapStuff("2B"));
        System.out.println("Mapping of eB : " + mapStuff("eB"));
    }

    private static void initCharMappers() {
        firstCharMapping = new HashMap<>();
        secondCharMapping = new TreeMap<>(Comparator.comparing(Character::toLowerCase));

        firstCharMapping.put('0', "Zero");
        firstCharMapping.put('1', "One");
        firstCharMapping.put('2', "Two");

        secondCharMapping.put('Y', "Yellow");
        secondCharMapping.put('B', "Blue");
        secondCharMapping.put('G', "Green");
    }

    private static String mapStuff(String str) {
        String INVALID_INPUT = "Invalid input";
        if (!str.matches("\\d[a-zA-Z]")) {
            return INVALID_INPUT;
        }

        Character firstChar = str.toCharArray()[0];
        Character secondChar = str.toCharArray()[1];

        if (!firstCharMapping.containsKey(firstChar) || !secondCharMapping.containsKey(secondChar)) {
            return INVALID_INPUT;
        }

        return firstCharMapping.get(firstChar) + " " + secondCharMapping.get(secondChar);
    }
}

Output :

Mapping of 0Y : Zero Yellow
Mapping of 0y : Zero Yellow
Mapping of 0YJ : Invalid input
Mapping of 2B : Two Blue
Mapping of eB : Invalid input


问:
Sort data from a MutableList in Kotlin
I'm new to Kotlin and need to ask some questions about ordering a MutableList<MyObject>. As I understand it, I can do a myMutableList.sortBy {it.int} and a myMutableList.sortByDescending {it.int} for both Int and String. But return is always a Unit and not a MutableList.

Where am I going wrong and how do I proceed?

答:
You can do something like this with the properties of the object inside the list, so let's say you have an object with a string and a number

```<code>data class MyObject(var name:String,var number:Int)
</code>```

add some values to it

```<code> val myObjectList: MutableList<MyObject>? = mutableListOf()
 myObjectList!!.add(MyObject("C",3))
 myObjectList.add(MyObject("B",1))
 myObjectList.add(MyObject("A",2))
</code>```

And then you can sort it by either one of its properties, it'll return a mutable list with the sorted values

```<code>var sortedByName =  myObjectList.sortedBy { myObject -> myObject.name }
var sortedByNumber =  myObjectList.sortedBy { myObject -> myObject.number }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sort data from a MutableList in Kotlin

Body:
You can do something like this with the properties of the object inside the list, so let's say you have an object with a string and a number

data class MyObject(var name:String,var number:Int)

add some values to it

 val myObjectList: MutableList<MyObject>? = mutableListOf()
 myObjectList!!.add(MyObject("C",3))
 myObjectList.add(MyObject("B",1))
 myObjectList.add(MyObject("A",2))

And then you can sort it by either one of its properties, it'll return a mutable list with the sorted values

var sortedByName =  myObjectList.sortedBy { myObject -> myObject.name }
var sortedByNumber =  myObjectList.sortedBy { myObject -> myObject.number }


问:
Dataprotection - iPhone
Have any one worked on data protection in iPhone - iOS. Can you share the details with me regarding that?</p>

答:
For anti-piracy measures, I should redirect you to the following stackoverflow question:

reducing piracy of iphone applications

Though some of the techniques described there are outdated. For instance, it is no longer useful to just check SignerIdentity key in your Info.plist.

If you want more advanced stuff, take a look at this thread:

http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/36330-iphone-piracy-protection-code-2-another-tutorial.html

Title: Dataprotection - iPhone


问:
How to add RTL support for Material UI React
I'm building an LTR application and I want to add RTL support.
The application is based on top of Material UI React.
I'm able to rotate the application to RTL since I'm using CSS Flex Box, just by adding dir="rtl" to the body. I also added direction="rtl" to the theme as mentioned here.

However not everything was changed.

Let's take this as an example :

As you can see here I have padding left to the text element.
In the RTL version, since everything was reversed the padding left has no effect in the UI, I mean it must be padding right to show the small space between the two element :

It seems that I'm doing something wrong because in Material UI documentation here this feature must be out of the box after adding this snippet and wrap the component around it.

This is my Parent component App :

```<code>import React, { PureComponent } from "react";
import { theme } from "./styling/theme";
import Routes from "./Routes";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";
// CSS
import { MuiThemeProvider } from "@material-ui/core/styles";
// import { ThemeProvider } from "@material-ui/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
// import { StylesProvider, jssPreset } from "@material-ui/styles";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";
import { themeObject, colors } from "./styling/theme";
// Helpers
import get from "lodash/get";

// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

function RTL(props) {
  return (
    <JssProvider jss={jss} generateClassName={generateClassName}>
      {
        props.children
      }
    </JssProvider>
  );
}

class App extends PureComponent {
  render() {
    const isRtl = get(store, "classified.language.rtl", false);
    return (
      <Provider store={store}>
        <RTL>
          <MuiThemeProvider
            theme={
              isRtl
                ? { ...theme, direction: "rtl" }
                : { ...theme, direction: "ltr" }
            }
          >
            <LoadingBar
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </MuiThemeProvider>
        </RTL>
      </Provider>
    );
  }
}

export default App;
</code>```

And this is an example of my components (The one in the pictures above : CLList) :

```<code>import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
// Helpers
import isFunction from "lodash/isFunction";
import cloneDeep from "lodash/cloneDeep";

import styles from "./CLList.styles";

const defaultImg = "IMAGE_URL_HERE";
class CLList extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        img: PropTypes.string,
        name: PropTypes.string
      })
    ).isRequired,
    onClick: PropTypes.func
  };
  render() {
    const { classes, items, onClick } = this.props;
    return (
      <ul className={classes.list}>
        {items.map((item, key) => (
          <li
            className={classes.item}
            onClick={() => isFunction(onClick) && onClick(cloneDeep(item))}
            key={key}
          >
            <img
              className={classes.image}
              src={item.img || defaultImg}
              alt={item.name}
              title={item.name}
            />
            <span className={classes.label}>{item.name}</span>
          </li>
        ))}
      </ul>
    );
  }
}

export default withStyles(styles)(CLList);
</code>```

And the last file is the CSS for CLList :

```<code>import { colors } from "../..";
const styles = theme => ({
  list: {
    display: "flex",
    flexDirection: "column",
    listStyle: "none",
    padding: 5,
    margin: 0,
    "& > li:not(:last-child)": {
      marginBottom: 10
    }
  },
  item: {
    flex: 1,
    display: "flex",
    cursor: "pointer",
    "&:hover": {
      backgroundColor: colors.primary[50]
    }
  },
  image: {
    flex: "0 0 15%",
    maxWidth: "40px",
    maxHeight: "40px"
  },
  label: {
    flex: "1",
    alignSelf: "center",
    paddingLeft: 20
  }
});

export default styles;
</code>```

I'm expecting that paddingLeft of label to be => paddingRight. Is this possible ? Is it a feature out of the box ? Or should I just use RTL-CSS-JS and wrap all my styles object when the body contains dir="RTL" to change automatically the style ?

I'm also so confused between these two libraries :

@material-ui/core/styles

@material-ui/styles

Should I use the first or the second one ? What is the difference ?

Thanks for you time.

EDIT 1 :

I used rtlCSSJS on my CSS Object and I get the expected result. But I'm not sure if this is the best way to do it.
The CSS of CLList now look like this :

```<code>import rtlCSSJS from "rtl-css-js";
import { colors } from "../..";
const defaultDir = document.body.getAttribute("dir");
const styles = theme =>
  defaultDir === 'rtl' ? rtlCSSJS({...CSS_HERE....}) : {...CSS_HERE....};
export default styles;
</code>```

答:
I think I found a solution to my own question, however feel free to add any enhancement or better solution.

Material UI is using jss-rtl by default and this last one is a wrapper for rtl-css-js. So there is no need to use rtl-css-js directly in since Material UI will do the job.

I changed my Parent App component to :

```<code>import React, { PureComponent } from "react";
import Routes from "./Routes";
import RTL from "./RTL";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";

import { themeObject, colors } from "./styling/theme";

class App extends PureComponent {
  render() {
    return (
      <Provider store={store}>
        <RTL>
          <>
            <LoadingBar
              // className="loading"
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </>
        </RTL>
      </Provider>
    );
  }
}

export default App;
</code>```

And I added RTL component which will connect to Redux to define the correct theme with the right direction. I'm saving the language data in Redux, and according the this data I will define the theme provided for my application.

This is the RTL component :

```<code>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
// Redux
import { connect } from "react-redux";
// CSS
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";

// Theme
import { themeObject } from "./styling/theme";

// Helpers
import get from "lodash/get";
// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

const G_isRtl = document.body.getAttribute("dir") === "rtl";

class RTL extends PureComponent {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.node
    ]),
    language: PropTypes.object
  };

  render() {
    const { children, language } = this.props;
    const isRtl = get(language, "rtl", G_isRtl);

    const theme = createMuiTheme({
      ...themeObject,
      direction: isRtl ? "rtl" : "ltr"
    });

    return (
      <JssProvider jss={jss} generateClassName={generateClassName}>
        <MuiThemeProvider theme={theme}>{children}</MuiThemeProvider>
      </JssProvider>
    );
  }
}

const mapStateToProps = ({ classified }) => ({
  language: classified.language
});
export default connect(mapStateToProps)(RTL);
</code>```

All the children components now will switch between RTL and LTR according to the language and we can focus on only one layout, all the reversing job is done thanks to this Plugins.

Also I want to say folowing the instructions in the official documentation does not work for me ! Most of this solution that I found is based on the answer here.

Body:
I'm building an LTR application and I want to add RTL support.
The application is based on top of Material UI React.
I'm able to rotate the application to RTL since I'm using CSS Flex Box, just by adding dir="rtl" to the body. I also added direction="rtl" to the theme as mentioned here.

However not everything was changed.

Let's take this as an example :

As you can see here I have padding left to the text element.
In the RTL version, since everything was reversed the padding left has no effect in the UI, I mean it must be padding right to show the small space between the two element :

It seems that I'm doing something wrong because in Material UI documentation here this feature must be out of the box after adding this snippet and wrap the component around it.

This is my Parent component App :

import React, { PureComponent } from "react";
import { theme } from "./styling/theme";
import Routes from "./Routes";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";
// CSS
import { MuiThemeProvider } from "@material-ui/core/styles";
// import { ThemeProvider } from "@material-ui/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
// import { StylesProvider, jssPreset } from "@material-ui/styles";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";
import { themeObject, colors } from "./styling/theme";
// Helpers
import get from "lodash/get";

// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

function RTL(props) {
  return (
    <JssProvider jss={jss} generateClassName={generateClassName}>
      {
        props.children
      }
    </JssProvider>
  );
}

class App extends PureComponent {
  render() {
    const isRtl = get(store, "classified.language.rtl", false);
    return (
      <Provider store={store}>
        <RTL>
          <MuiThemeProvider
            theme={
              isRtl
                ? { ...theme, direction: "rtl" }
                : { ...theme, direction: "ltr" }
            }
          >
            <LoadingBar
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </MuiThemeProvider>
        </RTL>
      </Provider>
    );
  }
}

export default App;

And this is an example of my components (The one in the pictures above : CLList) :

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
// Helpers
import isFunction from "lodash/isFunction";
import cloneDeep from "lodash/cloneDeep";

import styles from "./CLList.styles";

const defaultImg = "IMAGE_URL_HERE";
class CLList extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        img: PropTypes.string,
        name: PropTypes.string
      })
    ).isRequired,
    onClick: PropTypes.func
  };
  render() {
    const { classes, items, onClick } = this.props;
    return (

        {items.map((item, key) => (

 isFunction(onClick) && onClick(cloneDeep(item))}
            key={key}
          >

            {item.name}

        ))}

    );
  }
}

export default withStyles(styles)(CLList);

And the last file is the CSS for CLList :

import { colors } from "../..";
const styles = theme => ({
  list: {
    display: "flex",
    flexDirection: "column",
    listStyle: "none",
    padding: 5,
    margin: 0,
    "& > li:not(:last-child)": {
      marginBottom: 10
    }
  },
  item: {
    flex: 1,
    display: "flex",
    cursor: "pointer",
    "&:hover": {
      backgroundColor: colors.primary[50]
    }
  },
  image: {
    flex: "0 0 15%",
    maxWidth: "40px",
    maxHeight: "40px"
  },
  label: {
    flex: "1",
    alignSelf: "center",
    paddingLeft: 20
  }
});

export default styles;

I'm expecting that paddingLeft of label to be => paddingRight. Is this possible ? Is it a feature out of the box ? Or should I just use RTL-CSS-JS and wrap all my styles object when the body contains dir="RTL" to change automatically the style ?

I'm also so confused between these two libraries :

@material-ui/core/styles

@material-ui/styles

Should I use the first or the second one ? What is the difference ?

Thanks for you time.

EDIT 1 :

I used rtlCSSJS on my CSS Object and I get the expected result. But I'm not sure if this is the best way to do it.
The CSS of CLList now look like this :

import rtlCSSJS from "rtl-css-js";
import { colors } from "../..";
const defaultDir = document.body.getAttribute("dir");
const styles = theme =>
  defaultDir === 'rtl' ? rtlCSSJS({...CSS_HERE....}) : {...CSS_HERE....};
export default styles;

Body:
I think I found a solution to my own question, however feel free to add any enhancement or better solution.

Material UI is using jss-rtl by default and this last one is a wrapper for rtl-css-js. So there is no need to use rtl-css-js directly in since Material UI will do the job.

I changed my Parent App component to :

import React, { PureComponent } from "react";
import Routes from "./Routes";
import RTL from "./RTL";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";

import { themeObject, colors } from "./styling/theme";

class App extends PureComponent {
  render() {
    return (
      <Provider store={store}>
        <RTL>
          <>
            <LoadingBar
              // className="loading"
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </>
        </RTL>
      </Provider>
    );
  }
}

export default App;

And I added RTL component which will connect to Redux to define the correct theme with the right direction. I'm saving the language data in Redux, and according the this data I will define the theme provided for my application.

This is the RTL component :

import React, { PureComponent } from "react";
import PropTypes from "prop-types";
// Redux
import { connect } from "react-redux";
// CSS
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";

// Theme
import { themeObject } from "./styling/theme";

// Helpers
import get from "lodash/get";
// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

const G_isRtl = document.body.getAttribute("dir") === "rtl";

class RTL extends PureComponent {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.node
    ]),
    language: PropTypes.object
  };

  render() {
    const { children, language } = this.props;
    const isRtl = get(language, "rtl", G_isRtl);

    const theme = createMuiTheme({
      ...themeObject,
      direction: isRtl ? "rtl" : "ltr"
    });

    return (
      <JssProvider jss={jss} generateClassName={generateClassName}>
        <MuiThemeProvider theme={theme}>{children}</MuiThemeProvider>
      </JssProvider>
    );
  }
}

const mapStateToProps = ({ classified }) => ({
  language: classified.language
});
export default connect(mapStateToProps)(RTL);

All the children components now will switch between RTL and LTR according to the language and we can focus on only one layout, all the reversing job is done thanks to this Plugins.

Also I want to say folowing the instructions in the official documentation does not work for me ! Most of this solution that I found is based on the answer here.


问:
Monitoring AWS Lambda errors
I want to view AWS lambda last hour errors of two types:

Lambda function that finished with an error

Lambda function returned http 500

How should I do that?

答: You could also try something like Logbird that processes CloudWatch streams for all errors in AWS Lambda, API Gateway and other cloud services and can trigger notifications.</p>

Title: Monitoring AWS Lambda errors


问:
API endpoint to check latest .NET Core SDK version
I'm about to write a script to remove all .NET Core SDKs, except the latest one, from the local machine , thus I was curious whether there is any RESTful API endpoint which I could call to check the latest .NET Core SDK version available

答:
Try parsing https://github.com/dotnet/core/blob/master/release-notes/releases-index.json. (Try the "Raw" button to get a plain text version).

If you need even more information, that file links to a more detailed file (like https://github.com/dotnet/core/blob/master/release-notes/2.2/releases.json) which includes things like language version and installation URLs.


问:
Maven dependency for JavaFX using OpenJDK 1.8
Environment:

OS: For developing and running the application, both Windows 10 Pro (1809) and Linux (something like Ubuntu or Debian) with OpenJDK 1.8 and Maven installed will be used.

JDK: OpenJDK 1.8

IDE: IntelliJ Ultimate

Build tool Maven (multi-module project, one module uses JavaFX)

I'd very much prefer not to use anything with a paid license (even though, for this project, I could probably use the Oracle JDK for free...).

The problem:

I know, that the JDK 1.8 is supposed to come with JavaFX included. However, for OpenJDK 1.8 this, somehow, seems not to be the case (without the Maven dependencies, IntelliJ doesn't accept import javafx.application.Application; nor any other JFX imports).

For this reason, I am trying to include it as a Maven dependency. If I use:

```<code>    <!-- JavaFX -->
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>11</version>
    </dependency>
    .
    .
    .
</code>```

I get the following error message:

```<code>Error:(3, 26) java: cannot access javafx.application.Application
   bad class file: /C:/Users/kaspa/.m2/repository/org/openjfx/javafx-
   graphics/11/javafx-graphics-11-win.jar!/javafx/application/Application.class
   class file has wrong version 54.0, should be 52.0
   Please remove or make sure it appears in the correct subdirectory of the
   classpath.
</code>```

Using <version>12</version> yields [...]wrong version 55.0, should be 52.0[...].

The lowest <version>, inside the Maven <dependency>, I am able to use seems to bo 11.

The Question:

Is there something I can add/change to my pom.xml to make my application compile and run?

Do I absolutely need to upgrade to OpenJDK 11 or 12?

答:
First, a bit of background. From Java 8 to Java 10, the Oracle JDK used to come with JavaFX. But, even in these versions, JavaFX is not part of the OpenJDK. From Java 11, JavaFx is also not part of the Oracle JDK (as was the case with OpenJDK).

So, What are you doing wrong?

You are trying to run JavaFX 11 and 12 with JDK 8. This is not possible.

What can you do?

Get the openjfx 8. You can either build them from source or install it through sudo-apt on Ubuntu.

Is JavaFX 8 available as Maven dependency?

Not that I am aware of!

My advice.. Use Oracle JDK if you want to use Java8 or upgrade to Java 11 and use openJFX as Maven dependency.

Body:
Environment:

OS: For developing and running the application, both Windows 10 Pro (1809) and Linux (something like Ubuntu or Debian) with OpenJDK 1.8 and Maven installed will be used.

JDK: OpenJDK 1.8

IDE: IntelliJ Ultimate

Build tool Maven (multi-module project, one module uses JavaFX)

I'd very much prefer not to use anything with a paid license (even though, for this project, I could probably use the Oracle JDK for free...).

The problem:

I know, that the JDK 1.8 is supposed to come with JavaFX included. However, for OpenJDK 1.8 this, somehow, seems not to be the case (without the Maven dependencies, IntelliJ doesn't accept import javafx.application.Application; nor any other JFX imports).

For this reason, I am trying to include it as a Maven dependency. If I use:

    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>11</version>
    </dependency>
    .
    .
    .

I get the following error message:

Error:(3, 26) java: cannot access javafx.application.Application
   bad class file: /C:/Users/kaspa/.m2/repository/org/openjfx/javafx-
   graphics/11/javafx-graphics-11-win.jar!/javafx/application/Application.class
   class file has wrong version 54.0, should be 52.0
   Please remove or make sure it appears in the correct subdirectory of the
   classpath.

Using <version>12</version> yields [...]wrong version 55.0, should be 52.0[...].

The lowest <version>, inside the Maven <dependency>, I am able to use seems to bo 11.

The Question:

Is there something I can add/change to my pom.xml to make my application compile and run?

Do I absolutely need to upgrade to OpenJDK 11 or 12?


问:
How to concatenate multi-indexed column dataframes
I would like to make a somewhat complex multi-indexed column pandas dataframe concatenation. This concat consists of two or more dataframes in the following format:

```<code>indicator     eps2p                         ... logreturn
stock         TIET11     ALSC3     ALPA4    ...   TIET11  ALSC3 ALPA4

date
2000-01-31       NaN       NaN       NaN    ...     NaN   NaN   NaN
2000-02-01       100       NaN       NaN    ...     NaN   NaN   NaN
2000-02-02       101       NaN       NaN    ...     NaN   NaN   NaN
2000-02-03       104       NaN       NaN    ...     NaN   NaN   NaN
2000-02-04       NaN       NaN       NaN    ...     NaN   NaN   NaN

</code>```

Now, imagine that I have two more dataframes just like the one above, but instead of eps2p and logreturn, I have ev2ebitda and logreturn, and ev2ebit and logreturn in the indicator column level. Also, imagine that not all of the dataframes have the exact same stock columns under each one of the indicators. Finally, also consider that not necessarily two dataframes with the same stock under the same indicator have the exact same index, i.e., I could have two dataframes with the column logreturn/TIET11, but with complementary data:

```<code>DATAFRAME #1
              logreturn
              TIET11
date
2000-01-31    100
2000-02-01    NaN
2000-02-02    102
</code>```

```<code>DATAFRAME #2
              logreturn
              TIET11
date
2000-01-31    100
2000-02-01    101
2000-02-02    NaN
</code>```

With that in mind, how do I concat these dataframes into a single one that has all the unique indicator columns (eps2p, ev2ebit and ev2ebitda) and the common one (logreturn) in way that I don't have repeated data or lost data from any of the concatenated dataframes?

答:
You can use update to do this:

```<code>In [11]: df1.update(df2)

In [12]: df1
Out[12]:
           logreturn
              TIET11
date
2000-01-31     100.0
2000-02-01     101.0
2000-02-02     102.0
</code>```

Since there are missing columns in df1 you can first reindex with the union:

```<code>res = df1.reindex(columns=df3.columns | df4.columns)
res.update(df2)
</code>```

Note: You may need to reindex the index too.

Body:
I would like to make a somewhat complex multi-indexed column pandas dataframe concatenation. This concat consists of two or more dataframes in the following format:

indicator     eps2p                         ... logreturn
stock         TIET11     ALSC3     ALPA4    ...   TIET11  ALSC3 ALPA4

date
2000-01-31       NaN       NaN       NaN    ...     NaN   NaN   NaN
2000-02-01       100       NaN       NaN    ...     NaN   NaN   NaN
2000-02-02       101       NaN       NaN    ...     NaN   NaN   NaN
2000-02-03       104       NaN       NaN    ...     NaN   NaN   NaN
2000-02-04       NaN       NaN       NaN    ...     NaN   NaN   NaN

Now, imagine that I have two more dataframes just like the one above, but instead of eps2p and logreturn, I have ev2ebitda and logreturn, and ev2ebit and logreturn in the indicator column level. Also, imagine that not all of the dataframes have the exact same stock columns under each one of the indicators. Finally, also consider that not necessarily two dataframes with the same stock under the same indicator have the exact same index, i.e., I could have two dataframes with the column logreturn/TIET11, but with complementary data:

DATAFRAME #1
              logreturn
              TIET11
date
2000-01-31    100
2000-02-01    NaN
2000-02-02    102

DATAFRAME #2
              logreturn
              TIET11
date
2000-01-31    100
2000-02-01    101
2000-02-02    NaN

With that in mind, how do I concat these dataframes into a single one that has all the unique indicator columns (eps2p, ev2ebit and ev2ebitda) and the common one (logreturn) in way that I don't have repeated data or lost data from any of the concatenated dataframes?

Body:
You can use update to do this:

In [11]: df1.update(df2)

In [12]: df1
Out[12]:
           logreturn
              TIET11
date
2000-01-31     100.0
2000-02-01     101.0
2000-02-02     102.0

Since there are missing columns in df1 you can first reindex with the union:

res = df1.reindex(columns=df3.columns | df4.columns)
res.update(df2)

Note: You may need to reindex the index too.


问:
I want to save a file in VB.net from the amount of tries a user has
I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say

```<code>Username          Tries
</code>```

I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.

```<code>Module Module1
    Dim Tries As String = 0
    Dim EasyNum As New Random
    Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        While Difficulty <> "easy" And Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
        ElseIf Difficulty = "hard" Then
            Hard()
        End If

    End Sub

    Dim EasyGuess1 As Integer
    Dim EasyGuess2 As Integer
    Dim X As String
    Dim Y As Integer
    Sub Easy()

        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")

        X = EasyNum.Next(1000, 9999)
        Console.WriteLine(X)
        EasyGuess1 = Console.ReadLine
        Tries = +1
        If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        End If
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Console.WriteLine("Enter a new guess")
        EasyGuess1 = Console.ReadLine
    End Sub
    Sub EasyNo()
        Dim Save As String
        Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Strings.LCase(Console.ReadLine)
        If Save = "yes" Then
            System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
        End If
    End Sub
    Sub Hard()

        Console.WriteLine("You have chosen the hard difficulty")

    End Sub
    Sub HardYes()

    End Sub
    Sub HardNo()

    End Sub

End Module
</code>```

When I try to save the tries, I get this:

System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
  InnerException
  FormatException: Input string was not in a correct format.

Which I don't understand myself.

答:
There are a lot of issues, but I don't want to spoil it for you.

I definitely recommend to put "Option Strict On" in the project settings, so you immediately see where there are conversion errors (a string assigned to a integer etc).

To save the file, it should be something like

```<code>If Save = "yes" Then
    File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test", Tries.ToString())
End If
</code>```

(there are also File.Append... functions).

The Random class is a bit tricky, this is an object that provides random values and is not yet the random value itself. Always use the same random object for all different numbers, otherwise you might get the same number:

```<code>Private Randomizer As New Random(Environment.TickCount)
Private EasyNum As Int32 = Randomizer.Next(0, 10000) '0 to 9999
Private HardNum As Int32 = Randomizer.Next(0, 100000) '0 to 99999
</code>```

The "from" value of the randomizer's Next method is always inclusive, the "to" value exclusive, for whatever reasons.

To increment a variable, the syntax is

```<code>Tries += 1
</code>```

instead of "Tries = +1"

To write a number with leading digits, use might use

```<code>Console.Out.WriteLine($"The correct solution would have been: {EasyNum:0000}")
</code>```

or

```<code>EasyNum.ToString("0000")
</code>```

Body:
I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say

Username          Tries

I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.

Module Module1
    Dim Tries As String = 0
    Dim EasyNum As New Random
    Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        While Difficulty <> "easy" And Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
        ElseIf Difficulty = "hard" Then
            Hard()
        End If

    End Sub

    Dim EasyGuess1 As Integer
    Dim EasyGuess2 As Integer
    Dim X As String
    Dim Y As Integer
    Sub Easy()

        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")

        X = EasyNum.Next(1000, 9999)
        Console.WriteLine(X)
        EasyGuess1 = Console.ReadLine
        Tries = +1
        If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        End If
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Console.WriteLine("Enter a new guess")
        EasyGuess1 = Console.ReadLine
    End Sub
    Sub EasyNo()
        Dim Save As String
        Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Strings.LCase(Console.ReadLine)
        If Save = "yes" Then
            System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
        End If
    End Sub
    Sub Hard()

        Console.WriteLine("You have chosen the hard difficulty")

    End Sub
    Sub HardYes()

    End Sub
    Sub HardNo()

    End Sub

End Module

When I try to save the tries, I get this:

System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
  InnerException
  FormatException: Input string was not in a correct format.

Which I don't understand myself.

Body:
There are a lot of issues, but I don't want to spoil it for you.

I definitely recommend to put "Option Strict On" in the project settings, so you immediately see where there are conversion errors (a string assigned to a integer etc).

To save the file, it should be something like

If Save = "yes" Then
    File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test", Tries.ToString())
End If

(there are also File.Append... functions).

The Random class is a bit tricky, this is an object that provides random values and is not yet the random value itself. Always use the same random object for all different numbers, otherwise you might get the same number:

Private Randomizer As New Random(Environment.TickCount)
Private EasyNum As Int32 = Randomizer.Next(0, 10000) '0 to 9999
Private HardNum As Int32 = Randomizer.Next(0, 100000) '0 to 99999

The "from" value of the randomizer's Next method is always inclusive, the "to" value exclusive, for whatever reasons.

To increment a variable, the syntax is

Tries += 1

instead of "Tries = +1"

To write a number with leading digits, use might use

Console.Out.WriteLine($"The correct solution would have been: {EasyNum:0000}")

or

EasyNum.ToString("0000")


问:
Why does an empty Perl hash have one key?
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

```<code>my %h = {};
print scalar (keys (%h));
</code>```

This prints '1'. I was expecting zero. On the other hand. Similarly,

```<code>my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);
</code>```

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

答:
This has bit me before too.

```<code>my %h = ();
</code>```

Note the use of () instead of {}.

Explanation: The value {} is a reference to a hash, rather than a hash itself. In Perl, a reference is a kind of scalar value, and the assignment to %h has special processing for assigning a single scalar value. It stringifies the scalar (giving you the string HASH(0x229e8) in your case), and associates that key with the value undef.

When using (), the assignment from list to hash creates key/value pairs from pairs in the list, and since () is empty, the hash %h becomes empty.

Body:
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

my %h = {};
print scalar (keys (%h));

This prints '1'. I was expecting zero. On the other hand. Similarly,

my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

Body:
This has bit me before too.

my %h = ();

Note the use of () instead of {}.

Explanation: The value {} is a reference to a hash, rather than a hash itself. In Perl, a reference is a kind of scalar value, and the assignment to %h has special processing for assigning a single scalar value. It stringifies the scalar (giving you the string HASH(0x229e8) in your case), and associates that key with the value undef.

When using (), the assignment from list to hash creates key/value pairs from pairs in the list, and since () is empty, the hash %h becomes empty.


问:
R shiny download option
I'm dealing with a problem to download user requested data. I think I don't get to understand (I'm new in R and Shiny) the downloadHandler behavior. I have no problem to plot the selected file (already stored in R as a raster file BFT_PR, YFT_PR, and FAI), but when trying to download it I always get the same downloadData.txt and Error: server problem. I`ll really appreciate any help with this.

```<code>server <- function(input, output) {

  output$range <- renderText({paste("Forecast from", timestart, "to", timeend)})

  # Reactive value for selected dataset ----

  output$model <- renderPlot({

    mapInput <- reactive({
    switch(input$model,
           "Bluefin tuna" = BFT_PR,
           "Yellowfin tuna" = YFT_PR,
           "Fishing Aptitude Index"=FAI)})

    palette <-colorRampPalette(c("blue", "#007FFF", "cyan",
                                      "#7FFF7F", "yellow", "#FF7F00", "red" ))(100)

    spplot(mapInput(), col.regions=palette, sp.layout= list(landmask_m, landmask_u, FZ),scales=list(draw = TRUE))

  })

  # Download map as geotiff  ----

  output$downloadData <- downloadHandler(

    filename = function() {paste0(input$model, ".tif")},

    content = function(file) {writeRaster(mapInput(), file)}

  )
}
</code>```

答:
Been traveling last month, sorry to answer so late. Here goes an example of my code with some dummy data</p>

```<code>r1 <- raster(matrix(sample(1:100, 100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)
r2 <- raster(matrix(sample(100:200, 100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)
r3 <- raster(matrix(sample(200:300,100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)

library(shiny)
library(raster)
library(rgdal)
library (sp)

ui <- fluidPage(

App title ----
titlePanel((p("TUNAGOM DST", style = "color:#3474A7"))),

sidebarLayout(

# Sidebar panel for inputs ----

sidebarPanel(

 helpText("Weekly forecasts.
       Bluefin and Yellowfin tuna catch per unit effort (fish/1000 hooks).
       Fishing Aptitude Index "),

# Distribution maps: Species distribution, Fishing aptitude index. Display menu

# Input: select forecast dataset

  selectInput("model", "Select Forecast:",
          choices = c("r1", "r2", "r3")),

# Download data button

  downloadButton("downloadData", "Download data")

  ),

 # Main panel for displaying outputs ----
mainPanel(

  # Temporal range (text output)

 textOutput("range"),

  # Output: maps

 plotOutput("model"))
 )
 )

 server <- function(input, output) {

 output$range <- renderText({paste("Forecast from", timestart, "to", timeend)})

 Reactive value for selected dataset ----
 output$model <- renderPlot({

 mapInput <- reactive({
  switch(input$model,
     "r1" = r1,
     "r2" = r2,
     "r3"=r3)})

 palette <-colorRampPalette(c("blue", "#007FFF", "cyan",
                         "#7FFF7F", "yellow", "#FF7F00", "red" ))(100)

 spplot(mapInput(), col.regions=palette, scales=list(draw = TRUE))
 })

 output$downloadData <- downloadHandler(

 filename = function() {paste0(input$model, ".tif")},

 content = function(file) {writeRaster(mapInput(), file, format="GTiff",
 overwrite=TRUE)}
 )
 }

 runApp(shinyApp(ui, server), launch.browser = TRUE)
</code>```

Title: R shiny download option

Body:
I'm dealing with a problem to download user requested data. I think I don't get to understand (I'm new in R and Shiny) the downloadHandler behavior. I have no problem to plot the selected file (already stored in R as a raster file BFT_PR, YFT_PR, and FAI), but when trying to download it I always get the same downloadData.txt and Error: server problem. I`ll really appreciate any help with this.

server <- function(input, output) {

  output$range <- renderText({paste("Forecast from", timestart, "to", timeend)})

  # Reactive value for selected dataset ----

  output$model <- renderPlot({

    mapInput <- reactive({
    switch(input$model,
           "Bluefin tuna" = BFT_PR,
           "Yellowfin tuna" = YFT_PR,
           "Fishing Aptitude Index"=FAI)})

    palette <-colorRampPalette(c("blue", "#007FFF", "cyan",
                                      "#7FFF7F", "yellow", "#FF7F00", "red" ))(100)

    spplot(mapInput(), col.regions=palette, sp.layout= list(landmask_m, landmask_u, FZ),scales=list(draw = TRUE))

  })

  # Download map as geotiff  ----

  output$downloadData <- downloadHandler(

    filename = function() {paste0(input$model, ".tif")},

    content = function(file) {writeRaster(mapInput(), file)}

  )
}

Body:
Been traveling last month, sorry to answer so late. Here goes an example of my code with some dummy data

r1 <- raster(matrix(sample(1:100, 100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)
r2 <- raster(matrix(sample(100:200, 100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)
r3 <- raster(matrix(sample(200:300,100),35,52), xmn= -97.75, xmx=-84.75, ymn=17.75, ymx=26.5)

library(shiny)
library(raster)
library(rgdal)
library (sp)

ui <- fluidPage(

App title ----
titlePanel((p("TUNAGOM DST", style = "color:#3474A7"))),

sidebarLayout(

# Sidebar panel for inputs ----

sidebarPanel(

 helpText("Weekly forecasts.
       Bluefin and Yellowfin tuna catch per unit effort (fish/1000 hooks).
       Fishing Aptitude Index "),

# Distribution maps: Species distribution, Fishing aptitude index. Display menu

# Input: select forecast dataset

  selectInput("model", "Select Forecast:",
          choices = c("r1", "r2", "r3")),

# Download data button

  downloadButton("downloadData", "Download data")

  ),

 # Main panel for displaying outputs ----
mainPanel(

  # Temporal range (text output)

 textOutput("range"),

  # Output: maps

 plotOutput("model"))
 )
 )

 server <- function(input, output) {

 output$range <- renderText({paste("Forecast from", timestart, "to", timeend)})

 Reactive value for selected dataset ----
 output$model <- renderPlot({

 mapInput <- reactive({
  switch(input$model,
     "r1" = r1,
     "r2" = r2,
     "r3"=r3)})

 palette <-colorRampPalette(c("blue", "#007FFF", "cyan",
                         "#7FFF7F", "yellow", "#FF7F00", "red" ))(100)

 spplot(mapInput(), col.regions=palette, scales=list(draw = TRUE))
 })

 output$downloadData <- downloadHandler(

 filename = function() {paste0(input$model, ".tif")},

 content = function(file) {writeRaster(mapInput(), file, format="GTiff",
 overwrite=TRUE)}
 )
 }

 runApp(shinyApp(ui, server), launch.browser = TRUE)


问:
Batch file to check if another batch is open and do something when it gets closed
I’m trying to get a batch-file my other program can call upon, so that when my other program is closed it deletes a temp file the other program created, the program runs a loop so I can’t just put it before an exit command within the program as it would never get to it.</p>

```<code>@echo off
Title watcher
:start
//if other .bat file is open then
goto start
Else //then when it is closed
Del file.txt
Exit
</code>```

答:
For anyone who can't use Christoph's answer, there is an incredibly slow work-around.

```<code>@echo off

:loop
set "l=0"
for /f "delims=" %%i in ('tasklist /v') do (
    for /f %%j in ('echo %%i ^| find /c "process name"') do (
        set /a l+=%%j
        goto break
    )
)
:break
cls
if %l% gtr 0 (
    echo Process is still running...
) else (
    echo Process is not running
)
goto loop
</code>```

You can change the process name of your batch file with title, or just search for the file path.

Body:
I’m trying to get a batch-file my other program can call upon, so that when my other program is closed it deletes a temp file the other program created, the program runs a loop so I can’t just put it before an exit command within the program as it would never get to it.

@echo off
Title watcher
:start
//if other .bat file is open then
goto start
Else //then when it is closed
Del file.txt
Exit

Body:
For anyone who can't use Christoph's answer, there is an incredibly slow work-around.

@echo off

:loop
set "l=0"
for /f "delims=" %%i in ('tasklist /v') do (
    for /f %%j in ('echo %%i ^| find /c "process name"') do (
        set /a l+=%%j
        goto break
    )
)
:break
cls
if %l% gtr 0 (
    echo Process is still running...
) else (
    echo Process is not running
)
goto loop

You can change the process name of your batch file with title, or just search for the file path.


问:
apply function that uses column as input on a column with conditioning
Let's say I have two groups: '1' and '2'.

```<code>ls = [
    ['1', 2],
    ['2', 7],
    ['1', 3],
    ['2',-6],
    ['1', 3],
    ['1', 5],
    ['1', 4],
    ['2', 7]
]
df = spark.createDataFrame(pd.DataFrame(ls, columns=['col1', 'col2']))
df.show()

+----+-----+
|col1| col2|
+----+-----+
|   1|    2|
|   2|    7|
|   1|    3|
|   2|   -6|
|   1|    3|
|   1|    5|
|   1|    4|
|   2|    7|
+----+-----+
</code>```

I have computed QuantileDiscretizer() for each group using:

```<code>discretizer = QuantileDiscretizer(numBuckets=3, inputCol="col2", outputCol="result")
bucketizer_1 = discretizer.fit(df.filter(col('col1')=='1'))
bucketizer_2 = discretizer.fit(df.filter(col('col1')=='2'))
</code>```

These bucketizers are stored in a list, so I can call them using indexing (bucketizers[0], bucketizers[1])

Now I'm trying to transform the data in col2 into quantiles using the bucketizers. In other words, if col1 == '1', then bucketizers[0].transform(data) -> store result in a new column of the dataframe. Same process for group '2' but with bucketizers[1].

(Let's disregard the reason why I didn't fit and transform the data in one go)

I'm struggling to write the code to obtain what I want, since transform() uses a column as input.

Can someone help?

答:
One solution I can think of is using an union:

bucketizers[0].transform(df.filter((F.col('col1')=='1'))).union(bucketizers[1].transform(df.filter(F.col('col1')=='2'))).show()
```

Body:
Let's say I have two groups: '1' and '2'.

ls = [
    ['1', 2],
    ['2', 7],
    ['1', 3],
    ['2',-6],
    ['1', 3],
    ['1', 5],
    ['1', 4],
    ['2', 7]
]
df = spark.createDataFrame(pd.DataFrame(ls, columns=['col1', 'col2']))
df.show()

+----+-----+
|col1| col2|
+----+-----+
|   1|    2|
|   2|    7|
|   1|    3|
|   2|   -6|
|   1|    3|
|   1|    5|
|   1|    4|
|   2|    7|
+----+-----+

I have computed QuantileDiscretizer() for each group using:

discretizer = QuantileDiscretizer(numBuckets=3, inputCol="col2", outputCol="result")
bucketizer_1 = discretizer.fit(df.filter(col('col1')=='1'))
bucketizer_2 = discretizer.fit(df.filter(col('col1')=='2'))

These bucketizers are stored in a list, so I can call them using indexing (bucketizers[0], bucketizers[1])

Now I'm trying to transform the data in col2 into quantiles using the bucketizers. In other words, if col1 == '1', then bucketizers[0].transform(data) -> store result in a new column of the dataframe. Same process for group '2' but with bucketizers[1].

(Let's disregard the reason why I didn't fit and transform the data in one go)

I'm struggling to write the code to obtain what I want, since transform() uses a column as input.

Can someone help?


问:
compile() missing 1 required positional argument: 'loss'
I see the above error when executing the code below to add a custom loss function.

   mymodel.add_loss(custom_loss)
   mymodel.compile(optimizer='adam')
```

error: compile() missing 1 required positional argument: 'loss'

答:
Try this:</p>

```<code>my_model.compile(loss=my_custom_loss_function(), optimizer='adam')
</code>```

Body:
I see the above error when executing the code below to add a custom loss function.

   mymodel.add_loss(custom_loss)
   mymodel.compile(optimizer='adam')

error: compile() missing 1 required positional argument: 'loss'

Body:
Try this:

my_model.compile(loss=my_custom_loss_function(), optimizer='adam')


问:
configuring "plumbing" at runtime
This is kind of a design-patterns question in Java.

I am designing a java .jar file to act as a frameworks for managing and processing a certain form of data. I want the end user to be able to dictate the "plumbing" configuration, within certain constraints, in a certain way. The pieces are producers and/or consumers, and I know how to implement them, but the connections are confusing to me... here's a nonsense example that sort of parallels my application.

Suppose I have implemented these elements:

AppleTree  => produces apples

ApplePieMaker => consumes apples,
produces apple pies

ApplePress =>
consumes apples, produces apple cider

AppleSave => stores apples,
apple pies, or apple cider into a
file

AppleLoad =>    "reconstitutes" apples, apple pies, or apple cider from a file that was produced by AppleSave

ApplePieMonitor => displays apple pies on the screen in a GUI format, as they are produced

Now I want the user to be able to specify things like:

AppleTree | ApplePress | AppleSave cider1.sav (produce apples, make them into cider, save them to a file)

AppleTree | AppleSave apple1.sav (produce apples, save them to a file)

AppleLoad apple1.sav | ApplePieMaker | ApplePieMonitor (take saved apples, make them into pies, display the results on the screen in a GUI)

(not sure how to illustrate this, but might be specified as follows)

AppleTree tree1, ApplePieMaker piemaker1 < tree1, AppleSave apples.sav < tree1, AppleSave @select(*.sav) < piemaker1, ApplePress press1 < tree1, AppleSave cider.sav < press1, ApplePieMonitor piemon1 < piemaker1

(produce apples, make them into pies and cider, save the apples, pies and cider to separate files, with the pies going to a file selected by the user at runtime and the others going to predetermine files, and also display the pies on the screen in a GUI)

So I have a rough idea of how to architect a configuration file: namely to structure the thing into elements that have at most 1 input and at most 1 output, and then for each instantiated element, name it, and if it has an input, specify the name of the element providing the input.

What I'm unclear is how to go about coupling the elements of the program when they run. Maybe the way to go is to have a number of interfaces, like AppleConsumer, ApplePieConsumer, etc. so an ApplePieMaker would implement the AppleConsumer interface (incl. method consumeApple()), and an AppleTree would implement an AppleProducer interface which can register consumers at startup, so that every time the AppleTree produces an apple, it has a list of its consumers and calls consumeApple() on each of them, which then does the right thing without the AppleTree having to know what they are doing with the apples....

Any suggestions? Does this sort of thing have a name? I'm not really that experienced in design patterns.

edit: my end users don't know and don't care about Java. They just need to be able to set up a config file (which I'm trying to make as simple as possible so I can give them some good examples) and run my program which will read the config file, construct the elements, hook them together, and go. All the elements are under my control, I don't need to support plugins, so I don't have to be super-general.

答:
I could not help it, I have to workout something for this.

So here it is.

You already have the idea about the apple producer/consumer so this is how I would do it.

Create three interfaces and implement as follows:

Product  - Either Apple, AppleCider, ApplePie,

Producer - AppleTree, ApplePress, ApplePieMaker, AppleLoad,

Consumer - ApplePress ( consumes Apples ), ApplePieMaker ( consumes Apples ) , AppleMonitor, AppleSave.

The idea is to have a generic Product, produced by generic Producers and consumed by generic  Consumers.

Once you have that, you can create the configuration file pretty much the way you describe it, and parse it to create a new instance for each element.

```<code> element1 | element2 | element3 <parameters> | element 4
</code>```

In a map you create the element name and map it to the class that will create the new instance.

Let's say

```<code>map.put( "AppleTree", YouAppleTreeClass.class );
</code>```

So each time you read an element in the configuration you create the instance:

```<code>for( String item: line )  {
    Object o = map.get( item ).newInstance();
}
</code>```

Finally you have to validate the structure of your configuration, but basically it could be like this:

The first element should be a producer

The last should be a consumer

Any intermediate should be producer-consumers

You can parse arguments needed ( file to save data for instance )

Once you have all your objects created and chained, you start producing.

There are some thing you have to workout but they're pretty easy:

Argument passing ( the file where they will be saved/loaded from)

Object re-use in different configurations ( use the same AppleTree always )

Final notes: The following code, is just an scratch, you may really consider a dependency injector to do the job, but of course it will take you a little while to learn it.

The configuration parsing should be made by hand, for the format you're using will be unique for the end-user and should be pretty simple. Still you can deliver as much complexity you want inside your jar ( using any number of frameworks you need ).

You can also take a look to the following design patterns:

Composite

Observer

Interpreter

The implementation below, is a kind of monster the these three ( I didn't compile it, just throw some code to show how the idea would look like )

I hope this helps.

```<code>/**
 * Anything. An apple, cider, pie, whatever.
 */
interface Product{}

// The kinds of products.
class Apple     implements Product{}
class ApplePies implements Product{}
class AppleCider implements Product{}

/**
 * This indicates the class will do something.
 **/
interface Producer {
    // adds a consumer to the list.
    public void addConsumer( Consumer c );
    // removes the consumer from the list.
    public void removeConsumer( Consumer c );
    // let know eveytone a product has been created.
    public void notifyProductCreation( Product someProduct );
    // You're producer? Produce then...
    public void startProduction();
}

// To avoid copy/paste all around
class AbstractProducer implements Producer {
    private List<Consumer> consumers = new ArrayList<Consumer>();
    // adds a consumer to the list.
    public void addConsumer( Consumer c ) {
        consumers.add( c );
    }
    // removes the consumer from the list.
    public void removeConsumer( Consumer c ) {
        consumers.remove( c );
    }
    public void notifyProductCreation( Product someProduct ) {
        for( Consumer c : list ) {
            c.productCreated( someProduct );
        }
    }
}

interface Consumer {
    // Callback to know a product was created
    public void productCreated( Product p );
}

class AppleTree extends AbstractProducer {
    public void startProduction() {
        // do something with earh, sun, water..
        // and from time to time:
        Product ofThisNewApple = new Apple();
        notifyProductCreation( ofThisNewApple );
    }

}
class ApplePieMaker extends AbstractProducer implements Consumer {

    // Ok, a product was created, but
    // is it the product I care?
    // check first and consume after.
    public void productCreated( Product p ){
        // Is this the kind of product I can handle..
        // well do handle
        if( p instanceof Apple ) {
            /// start producing pies..
        }
    }
    public void startProduction() {
        // collect the needed number of apples and then...
        Product ofPie = new ApplePie();
        notifyProductCreation( ofPie );
    }

}
class ApplePress extends AbstractProducer implements Consumer {
    // Yeap, something gots produced.
    // Just handle if it is an apple
    public void productCreated( Product p ) {
        if( p instanceof Apple ) {
            // start producing cider
        }
    }

    public void startProduction() {
        // collect the needed number of apples and then...
        Product ofCiderBottle = new AppleCider();
        notifyProductCreation( ofCiderBottle );
    }

}
class AppleSave implements Consumer {
    public void productCreated( Product p ) {
        file.append( p );// any one will do.
    }
}

class AppleLoad extends AbstractProducer {
    public void startProduction() {
        readFromFile();
    }
    private readFromFile() {
        for( Product p : file ) {
            notifyProductCreation( p );
        }
    }
}

class Main {
    public static void main( String [] args ) {
        Configuration conf = new Configuration();
        List<Producer> producers conf.read();
        for( Producer p : producers ) {
            // fasten your seat belts....
            p.startProduction();
        }
    }
}

/// Ahhh, pretty ugly code below this line.
// the idea is:
// Read the configuration file
// for each line split in the "|"
// for each element create a new instance
// and chain it with the next.
// producer | consumer | etc...
// Becomes....
// new Producer().addConsumer( new Consumer() );
// Return the list of create producers.
class Configuration {
    List<Producer> producers
    // read the file
    // create the instances
    // let them run.
    public List<Producer> read() {
        File file = new File(....
        // The format is:
        // producer | consumer-producer <params> | consumer
        String line = uniqueLineFrom( file );

        String [] parts = line.split("|");

        if( parts.length == 1 ) {
            System.err.println("Invalid configuration. use element | element | etc. Only one element was....");
            System.exit( 1 );
        }

        int length = parts.length;
        for( int i = 0 ; i < parts.length ; i++ ) {
            Object theInstance = implementationMap.get( parts[i] ).newInstance();
            validatePosition( i, length, theInstance , parts[i] );
        }

        List<Producer> producers = new ArrayList<Producer>();
        for( int i = 0 ; i < parts.length ; i++ ) {
            Object theInstance = getInstance( parts[i] );
            if( not( isLast( i, length ) && isProducer( theInstance ) ) {
                // the next is its consumer
                Producer producer = ( Producer ) theInstance;
                producer.addConsumer( ( Consumer )  getInstance( parts[i+1] ));
                producers.add( producer );
            }
        }
        return producers;

    }
    // creates a new instance from the implementation map.
    private Object getInstance( String key ) {
        return implementationMap.get( part[i] ).newInstance();
    }
    // validates if an element at the given position is valid or not.
    // if not, prints the message and exit.
    // the first element most be a producer
    // the last one a consumer
    // all the middle elements producer-consumer
    //
    private void validatePosition( int i, int length, Object theInstance, String element  ) {
        if( isFirst( i ) && not(isProducer(( theInstance ) ))) {
            System.err.println( "Invalid configuration: " + element + " most be a producer ( either Ap...");
            System.exit( 2 );
        } else if ( isLast( i, length ) && not( isConsumer( theInstance  ))) {
            System.err.println( "Invalid configuration: " + element + " most be a consumer ( either Ap...");
            System.exit( 3 );
        } else if ( isMiddleAndInvalid( i, length , instance ) ) {
            System.err.println( "Invalid configuration: " + element + " most be a producer-consumer ( either Ap...");
            System.exit( 4 );
        }
    }
    private static Map<String,Class> implementationMap = new HashMap<String,Class>() static {
        implementationMap.put( "AppleTree", AppleTree.class );
        implementationMap.put( "ApplePieMaker ", ApplePieMaker .class );
        implementationMap.put( "ApplePress", ApplePress.class );
        implementationMap.put( "AppleSave", AppleSave.class );
        implementationMap.put( "AppleLoad", AppleLoad.class );
        implementationMap.put( "ApplePieMonitor", ApplePieMonitor.class );
    };

    // Utility methods to read better ( hopefully ) the statements
    // If you could read the validations above you may ignore these functions.

    private boolean not( boolean value ) {
        return !value;
    }
    private boolean isFirst( int i  ) {
        return i == 0;
    }
    private boolean isLast( int i, int l ) {
        return i == l -1 ;
    }
    private boolean isProducer( Object o ) {
        return o instanceof Producer;
    }
    private boolean isConsumer( Object o ) {
        return o instanceof Consumer;
    }
    private boolean isMiddleAndInvalid( int index, int length, Object instance ) {
        return not( isFirst( index ) ) && not( isLast( index, length ) ) && not( isProducer( instance ) && isConsumer( instance ));
    }
}
</code>```

OwnerDisplayName: Jason S

ContentLicense: CC BY-SA 2.5

Title: configuring "plumbing" at runtime

LastEditorDisplayName: Jason S

Body:
I could not help it, I have to workout something for this.

So here it is.

You already have the idea about the apple producer/consumer so this is how I would do it.

Create three interfaces and implement as follows:

Product  - Either Apple, AppleCider, ApplePie,

Producer - AppleTree, ApplePress, ApplePieMaker, AppleLoad,

Consumer - ApplePress ( consumes Apples ), ApplePieMaker ( consumes Apples ) , AppleMonitor, AppleSave.

The idea is to have a generic Product, produced by generic Producers and consumed by generic  Consumers.

Once you have that, you can create the configuration file pretty much the way you describe it, and parse it to create a new instance for each element.

 element1 | element2 | element3 <parameters> | element 4

In a map you create the element name and map it to the class that will create the new instance.

Let's say

map.put( "AppleTree", YouAppleTreeClass.class );

So each time you read an element in the configuration you create the instance:

for( String item: line )  {
    Object o = map.get( item ).newInstance();
}

Finally you have to validate the structure of your configuration, but basically it could be like this:

The first element should be a producer

The last should be a consumer

Any intermediate should be producer-consumers

You can parse arguments needed ( file to save data for instance )

Once you have all your objects created and chained, you start producing.

There are some thing you have to workout but they're pretty easy:

Argument passing ( the file where they will be saved/loaded from)

Object re-use in different configurations ( use the same AppleTree always )

Final notes: The following code, is just an scratch, you may really consider a dependency injector to do the job, but of course it will take you a little while to learn it.

The configuration parsing should be made by hand, for the format you're using will be unique for the end-user and should be pretty simple. Still you can deliver as much complexity you want inside your jar ( using any number of frameworks you need ).

You can also take a look to the following design patterns:

Composite

Observer

Interpreter

The implementation below, is a kind of monster the these three ( I didn't compile it, just throw some code to show how the idea would look like )

I hope this helps.

/**
 * Anything. An apple, cider, pie, whatever.
 */
interface Product{}

// The kinds of products.
class Apple     implements Product{}
class ApplePies implements Product{}
class AppleCider implements Product{}

/**
 * This indicates the class will do something.
 **/
interface Producer {
    // adds a consumer to the list.
    public void addConsumer( Consumer c );
    // removes the consumer from the list.
    public void removeConsumer( Consumer c );
    // let know eveytone a product has been created.
    public void notifyProductCreation( Product someProduct );
    // You're producer? Produce then...
    public void startProduction();
}

// To avoid copy/paste all around
class AbstractProducer implements Producer {
    private List<Consumer> consumers = new ArrayList<Consumer>();
    // adds a consumer to the list.
    public void addConsumer( Consumer c ) {
        consumers.add( c );
    }
    // removes the consumer from the list.
    public void removeConsumer( Consumer c ) {
        consumers.remove( c );
    }
    public void notifyProductCreation( Product someProduct ) {
        for( Consumer c : list ) {
            c.productCreated( someProduct );
        }
    }
}

interface Consumer {
    // Callback to know a product was created
    public void productCreated( Product p );
}

class AppleTree extends AbstractProducer {
    public void startProduction() {
        // do something with earh, sun, water..
        // and from time to time:
        Product ofThisNewApple = new Apple();
        notifyProductCreation( ofThisNewApple );
    }

}
class ApplePieMaker extends AbstractProducer implements Consumer {

    // Ok, a product was created, but
    // is it the product I care?
    // check first and consume after.
    public void productCreated( Product p ){
        // Is this the kind of product I can handle..
        // well do handle
        if( p instanceof Apple ) {
            /// start producing pies..
        }
    }
    public void startProduction() {
        // collect the needed number of apples and then...
        Product ofPie = new ApplePie();
        notifyProductCreation( ofPie );
    }

}
class ApplePress extends AbstractProducer implements Consumer {
    // Yeap, something gots produced.
    // Just handle if it is an apple
    public void productCreated( Product p ) {
        if( p instanceof Apple ) {
            // start producing cider
        }
    }

    public void startProduction() {
        // collect the needed number of apples and then...
        Product ofCiderBottle = new AppleCider();
        notifyProductCreation( ofCiderBottle );
    }

}
class AppleSave implements Consumer {
    public void productCreated( Product p ) {
        file.append( p );// any one will do.
    }
}

class AppleLoad extends AbstractProducer {
    public void startProduction() {
        readFromFile();
    }
    private readFromFile() {
        for( Product p : file ) {
            notifyProductCreation( p );
        }
    }
}

class Main {
    public static void main( String [] args ) {
        Configuration conf = new Configuration();
        List<Producer> producers conf.read();
        for( Producer p : producers ) {
            // fasten your seat belts....
            p.startProduction();
        }
    }
}

/// Ahhh, pretty ugly code below this line.
// the idea is:
// Read the configuration file
// for each line split in the "|"
// for each element create a new instance
// and chain it with the next.
// producer | consumer | etc...
// Becomes....
// new Producer().addConsumer( new Consumer() );
// Return the list of create producers.
class Configuration {
    List<Producer> producers
    // read the file
    // create the instances
    // let them run.
    public List<Producer> read() {
        File file = new File(....
        // The format is:
        // producer | consumer-producer <params> | consumer
        String line = uniqueLineFrom( file );

        String [] parts = line.split("|");

        if( parts.length == 1 ) {
            System.err.println("Invalid configuration. use element | element | etc. Only one element was....");
            System.exit( 1 );
        }

        int length = parts.length;
        for( int i = 0 ; i < parts.length ; i++ ) {
            Object theInstance = implementationMap.get( parts[i] ).newInstance();
            validatePosition( i, length, theInstance , parts[i] );
        }

        List<Producer> producers = new ArrayList<Producer>();
        for( int i = 0 ; i < parts.length ; i++ ) {
            Object theInstance = getInstance( parts[i] );
            if( not( isLast( i, length ) && isProducer( theInstance ) ) {
                // the next is its consumer
                Producer producer = ( Producer ) theInstance;
                producer.addConsumer( ( Consumer )  getInstance( parts[i+1] ));
                producers.add( producer );
            }
        }
        return producers;

    }
    // creates a new instance from the implementation map.
    private Object getInstance( String key ) {
        return implementationMap.get( part[i] ).newInstance();
    }
    // validates if an element at the given position is valid or not.
    // if not, prints the message and exit.
    // the first element most be a producer
    // the last one a consumer
    // all the middle elements producer-consumer
    //
    private void validatePosition( int i, int length, Object theInstance, String element  ) {
        if( isFirst( i ) && not(isProducer(( theInstance ) ))) {
            System.err.println( "Invalid configuration: " + element + " most be a producer ( either Ap...");
            System.exit( 2 );
        } else if ( isLast( i, length ) && not( isConsumer( theInstance  ))) {
            System.err.println( "Invalid configuration: " + element + " most be a consumer ( either Ap...");
            System.exit( 3 );
        } else if ( isMiddleAndInvalid( i, length , instance ) ) {
            System.err.println( "Invalid configuration: " + element + " most be a producer-consumer ( either Ap...");
            System.exit( 4 );
        }
    }
    private static Map<String,Class> implementationMap = new HashMap<String,Class>() static {
        implementationMap.put( "AppleTree", AppleTree.class );
        implementationMap.put( "ApplePieMaker ", ApplePieMaker .class );
        implementationMap.put( "ApplePress", ApplePress.class );
        implementationMap.put( "AppleSave", AppleSave.class );
        implementationMap.put( "AppleLoad", AppleLoad.class );
        implementationMap.put( "ApplePieMonitor", ApplePieMonitor.class );
    };

    // Utility methods to read better ( hopefully ) the statements
    // If you could read the validations above you may ignore these functions.

    private boolean not( boolean value ) {
        return !value;
    }
    private boolean isFirst( int i  ) {
        return i == 0;
    }
    private boolean isLast( int i, int l ) {
        return i == l -1 ;
    }
    private boolean isProducer( Object o ) {
        return o instanceof Producer;
    }
    private boolean isConsumer( Object o ) {
        return o instanceof Consumer;
    }
    private boolean isMiddleAndInvalid( int index, int length, Object instance ) {
        return not( isFirst( index ) ) && not( isLast( index, length ) ) && not( isProducer( instance ) && isConsumer( instance ));
    }
}

OwnerDisplayName: Oscar Reyes


问:
How to Throttle DataStage
I work on a project where we run a number of DataStage sequences can be run in parallel, one in particular is poorly performing and takes a lot of resources, impacting the shared environment. Performance tuning initiative is in progress but will take time.

In the meantime I was hopeful that we could throttle DataStage to restrict the resources that could be used by this particular job/sequence - however I'm not personally experienced with DataStage specifically.

Can anyone comment if this facility exists in DataStage (v8.5 I believe), and point me in the direction of some further detail.

Secondly, I know that we can at the  throttle based on the user (I think this ties into AIX 'ulimit', but not sure). Is it easy/possbile to run different jobs/sequences as different users?

答:
Sequence is a collection of individual jobs.  </p>

```<code>In most cases, jobs in a sequence can be rearranged to run serially.  Please check the organisation of the sequence and do a critical path analyis to remove the jobs that need not run in parallel to critical jobs.
</code>```

Title: How to Throttle DataStage

Body:
Sequence is a collection of individual jobs.

In most cases, jobs in a sequence can be rearranged to run serially.  Please check the organisation of the sequence and do a critical path analyis to remove the jobs that need not run in parallel to critical jobs.