问:
Rendering raw html with reactjs
So is this the only way to render raw html with reactjs?

```<code>// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
      </div>
    );
  }
});
</code>```

I know there are some cool ways to markup stuff with JSX, but I am mainly interested in being able to render raw html (with all the classes, inline styles, etc..). Something complicated like this:

```<code><!-- http://getbootstrap.com/components/#dropdowns-example -->
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
</code>```

I would not want to have to rewrite all of that in JSX.

Maybe I am thinking about this all wrong. Please correct me.

答:
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

It is better/safer to sanitise your raw HTML (using e.g., DOMPurify) before injecting it into the DOM via dangerouslySetInnerHTML.

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.

Example:

```<code>import React from 'react'
import createDOMPurify from 'dompurify'
import { JSDOM } from 'jsdom'

const window = (new JSDOM('')).window
const DOMPurify = createDOMPurify(window)

const rawHTML = `
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
`

const YourComponent = () => (
  <div>
    { <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML) }} /> }
  </div>
)

export default YourComponent
</code>```

Title: Rendering raw html with reactjs

Body:
So is this the only way to render raw html with reactjs?

// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (

          {this.props.author}

    );
  }
});

I know there are some cool ways to markup stuff with JSX, but I am mainly interested in being able to render raw html (with all the classes, inline styles, etc..). Something complicated like this:

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown

  </button>

Action

Another action

Something else here

Separated link

I would not want to have to rewrite all of that in JSX.

Maybe I am thinking about this all wrong. Please correct me.

Body:
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

It is better/safer to sanitise your raw HTML (using e.g., DOMPurify) before injecting it into the DOM via dangerouslySetInnerHTML.

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.

Example:

import React from 'react'
import createDOMPurify from 'dompurify'
import { JSDOM } from 'jsdom'

const window = (new JSDOM('')).window
const DOMPurify = createDOMPurify(window)

const rawHTML = `
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
`

const YourComponent = () => (
  <div>
    { <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML) }} /> }
  </div>
)

export default YourComponent


来源: stackexchange

问:
Count frequency of text in list in dataframe
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

```<code>(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]
</code>```

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

```<code>mike: 2, peter: 3, simon: 1
</code>```

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot

答:
```<code>from collections import Counter

invitees = [["mike", "peter"],["peter"],["simon", "mike", "peter"]]
name = ["birthday party","Retirement","office opening"]

new_df = pd.DataFrame(data={"name":name,"invitees":invitees})

all_invitees = []
for i,row in new_df.iterrows():
    invitees.extend(row[1])

invitees_count = dict(Counter(all_invities))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

mike: 2, peter: 3, simon: 1

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot


问:
Evaluating javascript using a java code
This might not be practical, but I have it as a task.
I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the javascript result to the browser. So this way, I would be evaluating the javascript on the server side. So I want what is inside
to be evaluated.

I tried this to test, it worked but it has some issues, for example it prints the message to System.out. And engine.eval("print('Welocme to java worldddd')"); does not return a String so that I can output it to the outputstream of the socket:

```<code>import javax.script.*;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
     // evaluate JavaScript code from String
     engine.eval("print('Welocme to java worldddd')");
     //engine.eval("a");
} catch (ScriptException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

答:
```<code>public static String convertEnumToJson(Class<? extends Enum<?>> cls) throws ScriptException, NoSuchMethodException, IllegalAccessException {
    List<Map<String, Object>> map = createMap(Colors.class);
    return createJson(map);
}

public static List<Map<String, Object>> createMap(Class<? extends Enum<?>> cls) throws IllegalAccessException {
    List<Map<String, Object>> res = new ArrayList<>();

    for (Enum<?> item : cls.getEnumConstants()) {
        Map<String, Object> map = new LinkedHashMap<>();

        for (Field field : item.getClass().getDeclaredFields()) {
            if (field.getType() != item.getClass() && !"$VALUES".equals(field.getName())) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(item));
            }
        }

        res.add(map);
    }

    return res;
}

// It's better to use Jackson or similar lib for read/write json
public static <T> String createJson(T obj) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.eval("function sum(a){ return a;}");
    return ((Invocable)engine).invokeFunction("sum", obj).toString();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Evaluating javascript using a java code

Body:
This might not be practical, but I have it as a task.
I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the javascript result to the browser. So this way, I would be evaluating the javascript on the server side. So I want what is inside
to be evaluated.

I tried this to test, it worked but it has some issues, for example it prints the message to System.out. And engine.eval("print('Welocme to java worldddd')"); does not return a String so that I can output it to the outputstream of the socket:

import javax.script.*;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
     // evaluate JavaScript code from String
     engine.eval("print('Welocme to java worldddd')");
     //engine.eval("a");
} catch (ScriptException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
}


问:
How to use callback with useState hook in react
I am using functional component with hooks. I need to update state in parent from a child. I am using a prop function in Parent.
All works fine except my prop function is getting the previous state and not the current state. My prop function gets executed before useState hook setting current state.
How can I can I wait for my call back function to be executed after useState call. I am looking for something like setState(state,callback) from class based components.

Here is the code snippet:

```<code>function Parent() {
  const [Name, setName] = useState("");
  getChildChange = getChildChange.bind(this);
  function getChildChange(value) {
    setName(value);
  }

  return <div> {Name} :
    <Child getChildChange={getChildChange} ></Child>
  </div>
}

function Child(props) {
  const [Name, setName] = useState("");
  handleChange = handleChange.bind(this);

  function handleChange(ele) {
    setName(ele.target.value);
    props.getChildChange(collectState());
  }

  function collectState() {
    return Name;
  }

  return (<div>
    <input onChange={handleChange} value={Name}></input>
  </div>);
}
</code>```

答:
You can use useEffect/useLayoutEffect to achieve this:

```<code>const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

If you want to prevent the callback from running on first render, adjust the previous version:

```<code>const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  const didMount = React.useRef(false);

  React.useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;
      return;
    }

    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

More about it over here.

Body:
I am using functional component with hooks. I need to update state in parent from a child. I am using a prop function in Parent.
All works fine except my prop function is getting the previous state and not the current state. My prop function gets executed before useState hook setting current state.
How can I can I wait for my call back function to be executed after useState call. I am looking for something like setState(state,callback) from class based components.

Here is the code snippet:

function Parent() {
  const [Name, setName] = useState("");
  getChildChange = getChildChange.bind(this);
  function getChildChange(value) {
    setName(value);
  }

  return
 {Name} :
    <Child getChildChange={getChildChange} ></Child>

}

function Child(props) {
  const [Name, setName] = useState("");
  handleChange = handleChange.bind(this);

  function handleChange(ele) {
    setName(ele.target.value);
    props.getChildChange(collectState());
  }

  function collectState() {
    return Name;
  }

  return (

    <input onChange={handleChange} value={Name}></input>

);
}

Body:
You can use useEffect/useLayoutEffect to achieve this:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

If you want to prevent the callback from running on first render, adjust the previous version:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  const didMount = React.useRef(false);

  React.useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;
      return;
    }

    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

More about it over here.


问:
Angular Material Table change specific row content
I have Angular 7 with Material table:

```<code><mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="Extension">
        <mat-header-cell *matHeaderCellDef (click)="sortData('agentExtn')" class="pointer" [ngClass]="getSortClass('agentExtn')" id="ExtnHeader" >
        {{ ExtnHeader | translate }} <div></div >
        </mat-header-cell> <mat-cell *matCellDef="let element" class="ExtnCol"> {{ element.Extn }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Play">
        <mat-header-cell *matHeaderCellDef>{{ 'MAIN.PLAY' | translate }}</mat-header-cell>
        <mat-cell *matCellDef="let element">
            <button id="play" class="float-right icon-link" mat-icon-button matTooltip="{{ 'MAIN.PLAY' | translate }}" (click)="    $event.stopPropagation(); playRecord(element.recordId)" >
                <i class="fa fa-play" aria-hidden="true"></i>
            </button>
        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

    <mat-row *matRowDef="let row; columns: displayedColumns" [ngClass]="{ 'highlight-row': selectedRow == row.MediaRecord.$.recordId, pointer: true }" (click)="showRecordDetailsDialog(row)">
    </mat-row>
</mat-table>
</code>```

So rows looks similar to following:

On the click of the Play icon, an audio element is displayed somewhere else on the screen.

Now, I want the Play icon of that particular row to replaced by Pause icon. Also, if the user clicks Play icon of another row, the previous row with Pause icon should be replaced by Play icon.

How can I do this? How can I get reference to the particular rows and replace those particular icons?

答:
I would suggest do put an ui layer on top of each row entry.

For example, you have the element Audio

```<code>interface Audio {
    name: string;
    song: any;
}
</code>```

Then extend Audio like:

```<code>interface UIAudio extends Audio {
    isPlaying: boolean;
}
</code>```

Map the dataSource

```<code>dataSource = dataSource as UIAudio[];
</code>```

Now you can check in the template for isPlaying, like:

Html:

```<code><ng-container matColumnDef="Play">
    <mat-header-cell *matHeaderCellDef>{{ 'MAIN.PLAY' | translate }}</mat-header-cell>
    <mat-cell *matCellDef="let element">
        <button id="play" class="float-right icon-link" mat-icon-button matTooltip="{{ 'MAIN.PLAY' | translate }}" (click)="    $event.stopPropagation(); playRecord(element)" >
            <i class="fa fa-{{element.isPlaying ? 'pause' : 'play'}}" aria-hidden="true"></i>
        </button>
    </mat-cell>
</ng-container>
</code>```

TS

```<code>playRecord(element) {
    element.isPlaying = true;
}
</code>```

You could also create a Component for Audio.

Body:
I have Angular 7 with Material table:

<mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="Extension">
        <mat-header-cell *matHeaderCellDef (click)="sortData('agentExtn')" class="pointer" [ngClass]="getSortClass('agentExtn')" id="ExtnHeader" >
        {{ ExtnHeader | translate }}

        </mat-header-cell> <mat-cell *matCellDef="let element" class="ExtnCol"> {{ element.Extn }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Play">
        <mat-header-cell *matHeaderCellDef>{{ 'MAIN.PLAY' | translate }}</mat-header-cell>
        <mat-cell *matCellDef="let element">
            <button id="play" class="float-right icon-link" mat-icon-button matTooltip="{{ 'MAIN.PLAY' | translate }}" (click)="    $event.stopPropagation(); playRecord(element.recordId)" >

            </button>
        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

    <mat-row *matRowDef="let row; columns: displayedColumns" [ngClass]="{ 'highlight-row': selectedRow == row.MediaRecord.$.recordId, pointer: true }" (click)="showRecordDetailsDialog(row)">
    </mat-row>
</mat-table>

So rows looks similar to following:

On the click of the Play icon, an audio element is displayed somewhere else on the screen.

Now, I want the Play icon of that particular row to replaced by Pause icon. Also, if the user clicks Play icon of another row, the previous row with Pause icon should be replaced by Play icon.

How can I do this? How can I get reference to the particular rows and replace those particular icons?

Body:
I would suggest do put an ui layer on top of each row entry.

For example, you have the element Audio

interface Audio {
    name: string;
    song: any;
}

Then extend Audio like:

interface UIAudio extends Audio {
    isPlaying: boolean;
}

Map the dataSource

dataSource = dataSource as UIAudio[];

Now you can check in the template for isPlaying, like:

Html:

<ng-container matColumnDef="Play">
    <mat-header-cell *matHeaderCellDef>{{ 'MAIN.PLAY' | translate }}</mat-header-cell>
    <mat-cell *matCellDef="let element">
        <button id="play" class="float-right icon-link" mat-icon-button matTooltip="{{ 'MAIN.PLAY' | translate }}" (click)="    $event.stopPropagation(); playRecord(element)" >
            <i class="fa fa-{{element.isPlaying ? 'pause' : 'play'}}" aria-hidden="true"></i>
        </button>
    </mat-cell>
</ng-container>

TS

playRecord(element) {
    element.isPlaying = true;
}

You could also create a Component for Audio.


问:
Does the internal service call need to go through the API gateway, such as zuul?
I have used eureka as service discovery. If all internal services call each other go through the API gateway, I can't use ribbon-backed RestTemplate or feign client any more.

Is it necessary or some option?

答:
No. Zuul is a gatekeeper. You need it to pass requests from the UI. Internal communication should not pass through a gateway.

Just for reference:

https://medium.com/microservices-in-practice/service-mesh-vs-api-gateway-a6d814b9bf56

You can also find more info in Ken Finnigan's book "Enterprise java microservices" (https://www.manning.com/books/enterprise-java-microservices)


问:
Promise not working in React useEffect in combination with Firebase
I want to get data from firebase inside a useEffect function like this:

```<code>  useEffect(() => {
   /** nope */
   async function fetchData() {
     let dataObject = {};
     let dataArray = [];
     setAttendees({});

     // You can await here
     if (newData[listRedux]) {
       const request = await Object.keys(newData[listRedux] .
       [1].attendees).map(
         user => {
           usersRef.child(user).on('value', snap => {
             dataObject[snap.key] = snap.val();
             setAttendees(dataObject);
             console.log(dataObject);
             let comp = (
               <Avatar
                 key={snap.key}
                 size="small"
                 source={snap.val().avatar}
                 alt={snap.val().name}
               />
             );
             dataArray.push(comp);
             setAttendeesComp(dataArray);
           });
         }
       );

       // Wait for all requests, and then setState
       await Promise.all(request).then(() => {
         console.log('done');
       });
     }
   }
   fetchData();
 }, [newData, listRedux]);
</code>```

Now the second console.log inside the promise all will first show then the first console.log, meaning the request was not done yet.
How can i improve my code so the request and the states are first being set and then continue with the rest?

答:
```<code>export default function Example() {
    const [data, dataSet] = useState(false)
    const [attendees, setAttendees] = useState(false)

    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await res.json()
      console.log(response);
      dataSet(response)
    }

 useEffect(() => {
      if (!attendees) return
      fetchMyAPI();
    }, [attendees, newData, listRedux]);

useEffect(() => {
     setAttendees({})
  }, [])
</code>```

More examples here:

Body:
I want to get data from firebase inside a useEffect function like this:

  useEffect(() => {
   /** nope */
   async function fetchData() {
     let dataObject = {};
     let dataArray = [];
     setAttendees({});

     // You can await here
     if (newData[listRedux]) {
       const request = await Object.keys(newData[listRedux] .
       [1].attendees).map(
         user => {
           usersRef.child(user).on('value', snap => {
             dataObject[snap.key] = snap.val();
             setAttendees(dataObject);
             console.log(dataObject);
             let comp = (
               <Avatar
                 key={snap.key}
                 size="small"
                 source={snap.val().avatar}
                 alt={snap.val().name}
               />
             );
             dataArray.push(comp);
             setAttendeesComp(dataArray);
           });
         }
       );

       // Wait for all requests, and then setState
       await Promise.all(request).then(() => {
         console.log('done');
       });
     }
   }
   fetchData();
 }, [newData, listRedux]);

Now the second console.log inside the promise all will first show then the first console.log, meaning the request was not done yet.
How can i improve my code so the request and the states are first being set and then continue with the rest?

Body:
export default function Example() {
    const [data, dataSet] = useState(false)
    const [attendees, setAttendees] = useState(false)

    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await res.json()
      console.log(response);
      dataSet(response)
    }

 useEffect(() => {
      if (!attendees) return
      fetchMyAPI();
    }, [attendees, newData, listRedux]);

useEffect(() => {
     setAttendees({})
  }, [])

More examples here:


问:
should i do commit after every execute or after loop
I have 2000 inserts in a loop
I do execute sql

My question is: should i do commit after every execute or after loop in order to minimise my affect on locking table and don't care about buffer?

the problem: my script sending to much queries and they stand in wait

I don't ask about limits of sql for x rows in commit and not about rollback in code. My question is about queue that standing half day in oracle server inactive and some waiting and prevent to new one proccess to run.

答:
2000 inserts is close to nothing. Though, it would be far better if you could insert them at once, using a single INSERT statement, than doing it in a loop.

Generally speaking, commit once you're done with the transaction. It is most probably not ended at every turn of the loop, is it? Besides, committing in a loop (frequently) leads to ORA-01555 snapshot too old error.

Saying that "your script sends many queries" - what kind of them? SELECTs aren't blocked by anything. INSERTs aren't blocked either (I guess you don't lock the whole table, do you)? If you're trying to update rows locked by other user(s), that - obviously - won't work until they are released. The question is: why do those queries wait half a day? Smells like bad management.


问:
Bin size in Matplotlib (Histogram)
I'm using matplotlib to make a histogram.

Is there any way to manually set the size of the bins as opposed to the number of bins?

答:
I use quantiles to do bins uniform and fitted to sample:

```<code>bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
</code>```

Title: Bin size in Matplotlib (Histogram)

Body:
I use quantiles to do bins uniform and fitted to sample:

bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')


问:
Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"?
To prevent actions from happening, I frequently type

```<code>function(){return false;}
</code>```

Is there a shortcut?

答:
I often have a "no op" function defined at the top of my common js file:

```<code>function nop() { return false }
</code>```

I use it whenever I need a "do nothing" or a "cancel event" handler (eg div.oncontextmenu = nop). In IE this has the added benefit that memory does not leak when creating similar [anonymous] functions on the fly and assigning them to event handlers. At least that's what IE Drip tells me.

OwnerDisplayName: Steven Noble

Body:
To prevent actions from happening, I frequently type

function(){return false;}

Is there a shortcut?

Body:
I often have a "no op" function defined at the top of my common js file:

function nop() { return false }

I use it whenever I need a "do nothing" or a "cancel event" handler (eg div.oncontextmenu = nop). In IE this has the added benefit that memory does not leak when creating similar [anonymous] functions on the fly and assigning them to event handlers. At least that's what IE Drip tells me.

ContentLicense: CC BY-SA 2.5


问:
UIGesturerecognizer is not working on UIView
When I am tapping on UIView but Gesture is not working.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

</code>```

I just want to perform this action on UIView tap.

答:
First of all you code doesn't compile. The handleTap(_:) signature must be like:

```<code>@objc func handleTap(_ sender: UITapGestureRecognizer) {
    print("---------View Tapped--------")
}
</code>```

Secondly, you need to first try with the minimal code in a separate project. And by minimal code I mean what you've added in the question.

```<code>class ViewController: UIViewController {
    @IBOutlet weak var viewForSHadow: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.addGestureRecognizer(tap)
    }

    @objc func handleTap(_ sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
    }
}
</code>```

Try with just the above code and see if you can get it working. The above code is working well at my end without any delegate or numberOfTaps.

Body:
When I am tapping on UIView but Gesture is not working.

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

I just want to perform this action on UIView tap.

Body:
First of all you code doesn't compile. The handleTap(_:) signature must be like:

@objc func handleTap(_ sender: UITapGestureRecognizer) {
    print("---------View Tapped--------")
}

Secondly, you need to first try with the minimal code in a separate project. And by minimal code I mean what you've added in the question.

class ViewController: UIViewController {
    @IBOutlet weak var viewForSHadow: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.addGestureRecognizer(tap)
    }

    @objc func handleTap(_ sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
    }
}

Try with just the above code and see if you can get it working. The above code is working well at my end without any delegate or numberOfTaps.


问:
Maven javadoc Search redirects to "/undefined/.." url
I have generated javadoc with javadoc maven plugin 3.0.1 and Java 9. However, when I use the new Search capability and pick a class, it redirects to "File not found"...

There is undefined in the url (e.g. "../target/site/apidocs/undefined/com/mycompany/MyClass.html"), which if removed, loads the page correctly.

Could you please help me with the right configuration to generate java doc (get rid of this undefined), so the search capability load the html page fine?

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>${version.maven-javadoc-plugin}</version>
        <executions>
            <execution>
                <id>javadoc</id>
                <goals>
                    <goal>javadoc</goal>
                </goals>
                <phase>prepare-package</phase>
                <configuration>
                    <doclint>none</doclint>
                    <dependencySourceIncludes>
                       <dependencySourceInclude>com.some:some</dependencySourceInclude>
                    </dependencySourceIncludes>
                    <doctitle>Title - ${project.version}</doctitle>
                    <includeDependencySources>true</includeDependencySources>
                    <windowtitle>Title</windowtitle>
                </configuration>
            </execution>
        </executions>
</code>```

答:
This indeed resolves the «Search» linking to ../undefined/... problem. There is however a nasty side effect: Links to standard classes or interfaces directing towards e.g. https://docs.oracle.com/en/java/javase/12/docs/api/... will be broken due to missing module names.

Consider e.g. links to java.lang.String now incorrectly pointing to https://docs.oracle.com/en/java/javase/12/docs/api/java/lang/String.html rather than towards https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html.

Body:
I have generated javadoc with javadoc maven plugin 3.0.1 and Java 9. However, when I use the new Search capability and pick a class, it redirects to "File not found"...

There is undefined in the url (e.g. "../target/site/apidocs/undefined/com/mycompany/MyClass.html"), which if removed, loads the page correctly.

Could you please help me with the right configuration to generate java doc (get rid of this undefined), so the search capability load the html page fine?

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>${version.maven-javadoc-plugin}</version>
        <executions>
            <execution>
                <id>javadoc</id>
                <goals>
                    <goal>javadoc</goal>
                </goals>
                <phase>prepare-package</phase>
                <configuration>
                    <doclint>none</doclint>
                    <dependencySourceIncludes>
                       <dependencySourceInclude>com.some:some</dependencySourceInclude>
                    </dependencySourceIncludes>
                    <doctitle>Title - ${project.version}</doctitle>
                    <includeDependencySources>true</includeDependencySources>
                    <windowtitle>Title</windowtitle>
                </configuration>
            </execution>
        </executions>


问:
autofocus not working after remove and adding again to the dom
I trying to set focus on show:

```<code><div>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <div *ngIf="!inEdit">
      bla
    </div>
    <mat-form-field *ngIf="inEdit">
      <input (blur)="inEdit=false"
      autofocus matInput >
    </mat-form-field>
  </div>
</div>
</code>```

it is work only on first click.

stackbliz

答:
You can programmatically call a focus method of HTML element whenever you need!

Try this:

Template:

```<code><div>
   <button mat-raised-button color="primary" (click)="inEdit=true;focus()">Edit</button>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <mat-form-field *ngIf="inEdit">
      <input #ref matInput >
    </mat-form-field>
  </div>
</div>
</code>```

TS:

```<code>import {Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'input-overview-example',
  styleUrls: ['input-overview-example.css'],
  templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample {

  @ViewChild("ref",null) refField: ElementRef;

  focus(): void {
    setTimeout(() => {
      this.refField.nativeElement.focus();
    }, 100);
  }
}
</code>```

Body:
I trying to set focus on show:

      bla

    <mat-form-field *ngIf="inEdit">
      <input (blur)="inEdit=false"
      autofocus matInput >
    </mat-form-field>

it is work only on first click.

stackbliz

Body:
You can programmatically call a focus method of HTML element whenever you need!

Try this:

Template:

<div>
   <button mat-raised-button color="primary" (click)="inEdit=true;focus()">Edit</button>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <mat-form-field *ngIf="inEdit">
      <input #ref matInput >
    </mat-form-field>
  </div>
</div>

TS:

import {Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'input-overview-example',
  styleUrls: ['input-overview-example.css'],
  templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample {

  @ViewChild("ref",null) refField: ElementRef;

  focus(): void {
    setTimeout(() => {
      this.refField.nativeElement.focus();
    }, 100);
  }
}


问:
Understand WorkManager's WorkSpec table
I have been using workManager in my app. I have seen that it creates a database with one of the table called workSpec. I have all the workers information is stored in it. I would like to understand about the columns of the table like what state, run attempt count, period_start_time etc.

NOTE :

WorkManager Version : 1.0.1

device is always connected to the charge source hence there no chance
of going it into doze.

Other questions I have :

How can I reduce the size of the database as I have seen it is growing like crazy and the old unused items are not removed.

In the same worker shown in the image, it was scheduled with periodicRequest which is to run every 1 hour but it has run only once and never came again. Why?

code for periodic requests

```<code> public WorkRequest createWorkRequest(int interval, String tagName) {
    if (tagName.endsWith(Task.TAG_SUFFIX)) {
        return new PeriodicWorkRequest.Builder(CommonWorker.class, interval, TimeUnit.SECONDS)
                .addTag(tagName)
                .build();
    }

    return new OneTimeWorkRequest.Builder(CommonWorker.class)
            .setInitialDelay(interval, TimeUnit.SECONDS)
            .addTag(tagName)
            .build();
}
</code>```

And

```<code> private void triggerSchedulerFor(int interval, String tagName) {
    WorkRequest workRequest = zdsWorkRequest.createWorkRequest(interval, tagName);
    Operation operation;
    if (tagName.endsWith(Task.TAG_SUFFIX)) {
        operation = workManager.enqueueUniquePeriodicWork(tagName,
                ExistingPeriodicWorkPolicy.REPLACE,
                (PeriodicWorkRequest) workRequest);

    } else {
        operation = workManager.enqueueUniqueWork(tagName, ExistingWorkPolicy.REPLACE,
                (OneTimeWorkRequest) workRequest);

    }
    Log.i(TAG, "State for Tag = " + tagName + "  is = " + operation.getState().getValue());
}
</code>```

There was another worker has to run every 15 mins periodically but I have seen a pattern that it triggers exactly every 15 mins but after every 1 hour the 15 mins worker triggers with delay of 11min i.e below is log trace

Line 2614: 05-30 09:41:28.876 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 6359: 05-30 09:56:28.907 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 9081: 05-30
  10:11:52.355 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 12991: 05-30 10:26:28.901 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 17115: 05-30 10:50:03.389 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 18727: 05-30
  10:56:28.881 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 20945: 05-30 11:11:28.907 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 23068: 05-30 11:26:28.909 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 26932: 05-30
  11:52:40.685 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 27598: 05-30 11:56:28.903 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 29724: 05-30 12:11:28.896 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 31790: 05-30
  12:26:28.902 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 34414: 05-30 12:46:14.844 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 36131: 05-30 12:56:28.902 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 38692: 05-30
  13:11:28.881 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 41469: 05-30 13:26:28.902 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC

答:
Regarding the workSpec table format, this is obviously an implementation details that may change in the future. I would avoid to make any changes directly to it or to assume that some particular information is stored in a particular format.

What it's currently stored there can be seen from WorkSpec source. Some of these information are accessible through WorkManager's API. As an example, you can access the attempt count both inside your Worker (ListenableWorker#getRunAttemptCount()) and through WorkInfo (WorkManager v2.1.0-alpha01 added `WorkInfo#getRunAttemptCount()'.

But again, you should never do any changes directly to WorkManager's tables or rely on its particular format.

For your other questions:

Reduce WorkManager's DB size

When you create your WorkRequest, you can specify for how long you need to keep this workRequest in the DB using keepResultsForAtLeast(). Keep in mind that once the WorkRequest is pruned from the DB you cannot get any more information on it.
Another, more drastic and dangerous, option is to use WorkManager#pruneWork(). In this case WorkManager prunes from the DB all the finished work. Again, after this operation it's not possible anymore to access the WorkRequest's WorkInfo.

PeriodicWorker non repeated

Would be useful to see how you create the WorkRequest and the Worker code, on which device/OS have you seen this behavior and which WorkManager version are you using.

Non precise interval for PeriodicWorker

WorkManager tries to respect the WorkRequest parameters compatibly with the Android OS battery optimization strategies (mainly Doze mode). This may result in the Worker being shifted in the nearest maintenance window.

Title: Understand WorkManager's WorkSpec table

Body:
I have been using workManager in my app. I have seen that it creates a database with one of the table called workSpec. I have all the workers information is stored in it. I would like to understand about the columns of the table like what state, run attempt count, period_start_time etc.

NOTE :

WorkManager Version : 1.0.1

device is always connected to the charge source hence there no chance
of going it into doze.

Other questions I have :

How can I reduce the size of the database as I have seen it is growing like crazy and the old unused items are not removed.

In the same worker shown in the image, it was scheduled with periodicRequest which is to run every 1 hour but it has run only once and never came again. Why?

code for periodic requests

 public WorkRequest createWorkRequest(int interval, String tagName) {
    if (tagName.endsWith(Task.TAG_SUFFIX)) {
        return new PeriodicWorkRequest.Builder(CommonWorker.class, interval, TimeUnit.SECONDS)
                .addTag(tagName)
                .build();
    }

    return new OneTimeWorkRequest.Builder(CommonWorker.class)
            .setInitialDelay(interval, TimeUnit.SECONDS)
            .addTag(tagName)
            .build();
}

And

 private void triggerSchedulerFor(int interval, String tagName) {
    WorkRequest workRequest = zdsWorkRequest.createWorkRequest(interval, tagName);
    Operation operation;
    if (tagName.endsWith(Task.TAG_SUFFIX)) {
        operation = workManager.enqueueUniquePeriodicWork(tagName,
                ExistingPeriodicWorkPolicy.REPLACE,
                (PeriodicWorkRequest) workRequest);

    } else {
        operation = workManager.enqueueUniqueWork(tagName, ExistingWorkPolicy.REPLACE,
                (OneTimeWorkRequest) workRequest);

    }
    Log.i(TAG, "State for Tag = " + tagName + "  is = " + operation.getState().getValue());
}

There was another worker has to run every 15 mins periodically but I have seen a pattern that it triggers exactly every 15 mins but after every 1 hour the 15 mins worker triggers with delay of 11min i.e below is log trace

Line 2614: 05-30 09:41:28.876 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 6359: 05-30 09:56:28.907 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 9081: 05-30
  10:11:52.355 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 12991: 05-30 10:26:28.901 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 17115: 05-30 10:50:03.389 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 18727: 05-30
  10:56:28.881 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 20945: 05-30 11:11:28.907 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 23068: 05-30 11:26:28.909 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 26932: 05-30
  11:52:40.685 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 27598: 05-30 11:56:28.903 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 29724: 05-30 12:11:28.896 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 31790: 05-30
  12:26:28.902 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 34414: 05-30 12:46:14.844 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC    Line 36131: 05-30 12:56:28.902 17609 17609
  I TaskPlannerImpl: onTaskTimerElapsed 900_SEC     Line 38692: 05-30
  13:11:28.881 17609 17609 I TaskPlannerImpl: onTaskTimerElapsed 900_SEC
    Line 41469: 05-30 13:26:28.902 17609 17609 I TaskPlannerImpl:
  onTaskTimerElapsed 900_SEC


问:
how to split multiple valued single row into multiple individual rows
I have CSV file which has multiple "values" in complex form for single "id" and
i want that multiple values to split in different rows with respect to its "id".

My CSV file:

```<code># To read df1=pandas.read_csv('krish.csv',encoding="ISO-8859-1")
# File have data even like 1.50% (P,KR,AU) 0.2¢/kg (AX,AU)
id  value
100.3   Free (A+,BH,CA) 0.1¢/kg (AX)
200.1   Free (MA, MX,OM)
321.5   Free (BH,CA) 1.70% (P) 7% (PE) 12.3% (KR)
</code>```

OUTPUT I WANT FOR MY INPUT GIVEN ABOVE :

OUTPUT WHICH GOT ON MY CODE AND FOR WHAT I TRIED

答:
I'm pretty sure there are more efficient/elegant ways, but this should work

def split_elements(s):
    elements = s[s.find('(')+1:-1].split(',')
    key = s[:s.find('(')]
    return ['{} ({})'.format(key, el) for el in elements]

input_data = {'values': ['Free (A+,BH,CA) 0.1¢/kg (AX)', 'Free (MA, MX,OM)', 'Free (BH,CA) 1.70% (P) 7% (PE) 12.3% (KR)'], 'ids': [100.3, 200.1, 321.5]}
df = pd.DataFrame(input_data)

temp_values = []
temp_ids = []
# iterate through rows
for idr, r in df.iterrows():
    # extract elements
    elements = [el.strip()+')' for el in r['values'].split(')') if el != '']
    # split subelements
    for element in elements:
        split_el = split_elements(element)
        temp_values.extend(split_el)
        temp_ids.extend([r['ids']]*len(split_el))
# create dataset
df1 = pd.DataFrame({'ids': temp_ids, 'values': temp_values})
df1.set_index('ids')
```

<p>Which gives</p>

<pre class="lang-sh prettyprint-override"><code>ids     values
100.3   Free (A+)
100.3   Free (BH)
100.3   Free (CA)
100.3   0.1¢/kg (AX)
200.1   Free (MA)
200.1   Free ( MX)
200.1   Free (OM)
321.5   Free (BH)
321.5   Free (CA)
321.5   1.70% (P)
321.5   7% (PE)
321.5   12.3% (KR)
</code>```

Body:
I have CSV file which has multiple "values" in complex form for single "id" and
i want that multiple values to split in different rows with respect to its "id".

My CSV file:

# To read df1=pandas.read_csv('krish.csv',encoding="ISO-8859-1")
# File have data even like 1.50% (P,KR,AU) 0.2¢/kg (AX,AU)
id  value
100.3   Free (A+,BH,CA) 0.1¢/kg (AX)
200.1   Free (MA, MX,OM)
321.5   Free (BH,CA) 1.70% (P) 7% (PE) 12.3% (KR)

OUTPUT I WANT FOR MY INPUT GIVEN ABOVE :

OUTPUT WHICH GOT ON MY CODE AND FOR WHAT I TRIED

Body:
I'm pretty sure there are more efficient/elegant ways, but this should work

def split_elements(s):
    elements = s[s.find('(')+1:-1].split(',')
    key = s[:s.find('(')]
    return ['{} ({})'.format(key, el) for el in elements]

input_data = {'values': ['Free (A+,BH,CA) 0.1¢/kg (AX)', 'Free (MA, MX,OM)', 'Free (BH,CA) 1.70% (P) 7% (PE) 12.3% (KR)'], 'ids': [100.3, 200.1, 321.5]}
df = pd.DataFrame(input_data)

temp_values = []
temp_ids = []
# iterate through rows
for idr, r in df.iterrows():
    # extract elements
    elements = [el.strip()+')' for el in r['values'].split(')') if el != '']
    # split subelements
    for element in elements:
        split_el = split_elements(element)
        temp_values.extend(split_el)
        temp_ids.extend([r['ids']]*len(split_el))
# create dataset
df1 = pd.DataFrame({'ids': temp_ids, 'values': temp_values})
df1.set_index('ids')

Which gives

ids     values
100.3   Free (A+)
100.3   Free (BH)
100.3   Free (CA)
100.3   0.1¢/kg (AX)
200.1   Free (MA)
200.1   Free ( MX)
200.1   Free (OM)
321.5   Free (BH)
321.5   Free (CA)
321.5   1.70% (P)
321.5   7% (PE)
321.5   12.3% (KR)


问:
F#: Rule of thumb to use specific types / aliased types?
I am creating a sort of "envelope" to keep track of what (Commands and Events) I am sending over RabbitMQ in an application as follows:

type Envelope<'T> = {
    Id: Guid
    CausationId: Guid
    CorrelationId: Guid
    Payload: 'T
    Timestamp: DateTimeOffset
}
```

<p><code>'T</code> being usually a command or event of the form:</p>

<pre class="lang-ml prettyprint-override"><code>type Commands =
    | DoA of Stuff
    | DoB of Stuff
    | DoC of Stuff

type Events =
    | AHappened of Stuff
    | BHappened of Stuff
    | CHappened of Stuff
</code>```

Note: I purposefully use relatively generic names

However, I could also have used specific types:

type CausationId = CausationId of Guid
type CorrelationId = CorrelationId of Guid
type CommandId = CommandId of Guid
type EventId = EventId of Guid
type Timestamp = Timestamp of DateTimeOffset

type DataToDoA = DataToDoA of Stuff
type DataToDoB = DataToDoB of Stuff
type DataToDoC = DataToDoC of Stuff

type Commands =
    | DoA of DataToDoA
    | DoB of DataToDoB
    | DoC of DataToDoC

type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff
type DataLeftByC = DataLeftByC of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB
    | CHappened of DataLeftByC
```

<p>Which would have led to:</p>

<pre class="lang-ml prettyprint-override"><code>type CommandEnvelope<`T> = {
    Id: CommandId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

type EventEnvelope<`T> = {
    Id: EventId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}
</code>```

Is there a rule of thumb to decide when to use those specific types / aliases-ish?

答:
Scott Wlaschin of F# for Fun and Profit talks a bit about this in his "Designing with Types" series. In the post on Single Case Union Types, he explains that one of the main reasons for using single-case union-types is when you want to add some validation logic. This allows you to refine your type a bit more.

The example he gives is email. You could have type Person = { ... Email: string ... } but this does not provide any guarantee that the string is an email address. Making a newtype for it type EmailAddress = Email of string you can then you can only create email addresses from functions which validate it first. This can be a good sanity check and helps make sure you don't assign email addresses to things which aren't addresses/links.

TL;DR Single-case union types are useful for whenever you want to add further semantics/validation to your code.

Body:
I am creating a sort of "envelope" to keep track of what (Commands and Events) I am sending over RabbitMQ in an application as follows:

type Envelope<'T> = {
    Id: Guid
    CausationId: Guid
    CorrelationId: Guid
    Payload: 'T
    Timestamp: DateTimeOffset
}

'T being usually a command or event of the form:

type Commands =
    | DoA of Stuff
    | DoB of Stuff
    | DoC of Stuff

type Events =
    | AHappened of Stuff
    | BHappened of Stuff
    | CHappened of Stuff

Note: I purposefully use relatively generic names

However, I could also have used specific types:

type CausationId = CausationId of Guid
type CorrelationId = CorrelationId of Guid
type CommandId = CommandId of Guid
type EventId = EventId of Guid
type Timestamp = Timestamp of DateTimeOffset

type DataToDoA = DataToDoA of Stuff
type DataToDoB = DataToDoB of Stuff
type DataToDoC = DataToDoC of Stuff

type Commands =
    | DoA of DataToDoA
    | DoB of DataToDoB
    | DoC of DataToDoC

type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff
type DataLeftByC = DataLeftByC of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB
    | CHappened of DataLeftByC

Which would have led to:

type CommandEnvelope<`T> = {
    Id: CommandId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

type EventEnvelope<`T> = {
    Id: EventId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

Is there a rule of thumb to decide when to use those specific types / aliases-ish?


问:
Typescript file change does not recognized by Visual Studio build and thinks all up to date
I am using TypeScript in ASP.NET Core 3 (preview 5) project, with the latest VS 2019 16.1.1 (tsc: 3.4)

All my TypeScript files are compile fine when I use "Rebuild All" or touch any C# files, or touch tsconfig.json.

However when I modify any of my .ts files, save then "Build" VS 2019 says all up to date, and does nothing.

What I've tried so far:

I changed the order of compileOnSave and compilerOptions, it does not matter

I tried to set compileOnSave true or false it does not help. Btw compileOnSave true does nothing, I do not care, to much (I am not insatiable, it would be enough for me to compile on build :-), but may have diagnostic value.

tsconfig.json:

```<code>"compileOnSave": false, // does not matter if true or false
"compilerOptions": {
  "module": "none",
  "noImplicitAny": true,
  "noEmitOnError": true,
  "sourceMap": true,
  "experimentalDecorators": true,
  "emitDecoratorMetadata": true,
  "target": "es2015",
  "lib": [
    "es2015",
    "es5",
    "dom"
  ],
  "outDir": "wwwroot/js/gen-ts",
  "typeRoots": [
    "./wwwroot/lib/@types"
  ]
},
"include": [
  "./Scripts"
]
</code>```

答:
Thanks for sharing your project. I reproduced similar issue on my side.

Here are the suggestions which may help:

1.Move your .ts files from Common folder to Scripts folder since content of your tsconfig.json is:

```<code>"include": [
  "./Scripts"
</code>```

2.Go=>Tools=>Options=>Projects and Solutions=>.net core=>Up-To-Date Checks=>> make sure we've checked the Don't call msbuild if a project appears to be up-to-date.

3.Delete the bin and obj folder and rebuild the solution.

(Not sure which steps above really help, though in some aspects I've resolved the issue, I can't figure out what really works since I've done too many changes and tests)

4.After that, the build output will display successful build most of the time though we don't make changes.

But i think it just displays Successful build message(It actually doesn't build those files):

1.If I change xx.ts, only xx.js will be regenerated.(You can compare the modified time of the .js files)

2.If I do some change in xx.cs file, only the .dll and some files will be regenerated but not the xx.js file.

I think now the build behavior is actually mostly normal except its wrong build output which may mislead us. For this aspect, you can report this issue by Help menu=>Send Feedback=>Report a problem to report it.

Hope I didn't misunderstood something:( Please feel free to correct me if something is wrong in my answer.

Body:
I am using TypeScript in ASP.NET Core 3 (preview 5) project, with the latest VS 2019 16.1.1 (tsc: 3.4)

All my TypeScript files are compile fine when I use "Rebuild All" or touch any C# files, or touch tsconfig.json.

However when I modify any of my .ts files, save then "Build" VS 2019 says all up to date, and does nothing.

What I've tried so far:

I changed the order of compileOnSave and compilerOptions, it does not matter

I tried to set compileOnSave true or false it does not help. Btw compileOnSave true does nothing, I do not care, to much (I am not insatiable, it would be enough for me to compile on build :-), but may have diagnostic value.

tsconfig.json:

"compileOnSave": false, // does not matter if true or false
"compilerOptions": {
  "module": "none",
  "noImplicitAny": true,
  "noEmitOnError": true,
  "sourceMap": true,
  "experimentalDecorators": true,
  "emitDecoratorMetadata": true,
  "target": "es2015",
  "lib": [
    "es2015",
    "es5",
    "dom"
  ],
  "outDir": "wwwroot/js/gen-ts",
  "typeRoots": [
    "./wwwroot/lib/@types"
  ]
},
"include": [
  "./Scripts"
]

Body:
Thanks for sharing your project. I reproduced similar issue on my side.

Here are the suggestions which may help:

1.Move your .ts files from Common folder to Scripts folder since content of your tsconfig.json is:

"include": [
  "./Scripts"

2.Go=>Tools=>Options=>Projects and Solutions=>.net core=>Up-To-Date Checks=>> make sure we've checked the Don't call msbuild if a project appears to be up-to-date.

3.Delete the bin and obj folder and rebuild the solution.

(Not sure which steps above really help, though in some aspects I've resolved the issue, I can't figure out what really works since I've done too many changes and tests)

4.After that, the build output will display successful build most of the time though we don't make changes.

But i think it just displays Successful build message(It actually doesn't build those files):

1.If I change xx.ts, only xx.js will be regenerated.(You can compare the modified time of the .js files)

2.If I do some change in xx.cs file, only the .dll and some files will be regenerated but not the xx.js file.

I think now the build behavior is actually mostly normal except its wrong build output which may mislead us. For this aspect, you can report this issue by Help menu=>Send Feedback=>Report a problem to report it.

Hope I didn't misunderstood something:( Please feel free to correct me if something is wrong in my answer.


问:
TTNavigator keeps going to the wildcard page. Any idea what happens?
My iPhone TTNavigator keeps loading the wildcard page even though the URL (i.e. 'tt://root') is valid

```<code>@synthesize navigator;

//
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    navigator = [TTNavigator navigator];
    [navigator setWindow:window];

    // Routing Table
    TTURLMap *map = navigator.URLMap;
    [map from:@"*" toViewController:[TTWebController class]];
    [map from:@"tt://root" toViewController:[MainTabBarController class]];
    [map from:@"tt://newsfeed" toViewController:[NewsFeedViewController class]];

    // First stop
    if (![navigator restoreViewControllers]) {
        [navigator openURLAction:[TTURLAction actionWithURLPath:@"tt://root"]];
    }
}
</code>```

When I comment out the wildcard section that redirects to the WebView, it will load the "tt://root" when the app starts.

Any idea what I'm missing out?

Cheers,
Mickey

答:
The restoreViewControllers message restores cached view controllers. It may be that the wildcard mapping is the last view you navigated to and is therefore on top of the cached navigation stack.

I would first try deleting the app from the simulator/device, cleaning the project, rebuilding, and deploying onto the simulator/device.

Body:
My iPhone TTNavigator keeps loading the wildcard page even though the URL (i.e. 'tt://root') is valid

@synthesize navigator;

//
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    navigator = [TTNavigator navigator];
    [navigator setWindow:window];

    // Routing Table
    TTURLMap *map = navigator.URLMap;
    [map from:@"*" toViewController:[TTWebController class]];
    [map from:@"tt://root" toViewController:[MainTabBarController class]];
    [map from:@"tt://newsfeed" toViewController:[NewsFeedViewController class]];

    // First stop
    if (![navigator restoreViewControllers]) {
        [navigator openURLAction:[TTURLAction actionWithURLPath:@"tt://root"]];
    }
}

When I comment out the wildcard section that redirects to the WebView, it will load the "tt://root" when the app starts.

Any idea what I'm missing out?

Cheers,
Mickey


问:
Access element
 with jQuery
I've this code:

```<code><div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="#" data-action="copy-link">Copy link</a>
    </div>
    ```
        Lorem ipsum...
    ```
</div>
</code>```

How can I access to ```</code> tag ?</p>

<p>What I've tried:</p>

```$('[data-action="copy-link"]').on('click', function(event) {
    var code = $(this).find('pre').css('color', 'red');
});
```

Thanks.

答:
You have to add .closest('.modal-body') since your pre is not a child off data-action="copy-link"

Also, please note that var code = makes little sense to in front, at the current state.

$('[data-action="copy-link"]').on('click', function(event) {
    $(this).closest('.modal-body').find('pre').css('color', 'red');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        Copy link
    </div>
    ```
        Lorem ipsum...
    ```
</div></code>```

Title: Access element <pre> with jQuery

Body:
I've this code:

...

        Copy link

        Lorem ipsum...

How can I access to
 tag ?

What I've tried:

$('[data-action="copy-link"]').on('click', function(event) {
    var code = $(this).find('pre').css('color', 'red');
});

Thanks.

Body:
You have to add .closest('.modal-body') since your pre is not a child off data-action="copy-link"

Also, please note that var code = makes little sense to in front, at the current state.

$('[data-action="copy-link"]').on('click', function(event) {
    $(this).closest('.modal-body').find('pre').css('color', 'red');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body">
    <p class="m-b-lg">...</p>
    <div class="text-right fz-sm">
        <a href="#" data-action="copy-link">Copy link</a>
    </div>
    <pre>
        Lorem ipsum...
    </pre>
</div>


问:
Cloudinary API transformation issues
I'm using Cloudinary as a image storage for my app but I'm having issues to transform my images.

What I would like to achieve is:

if an image is bigger than 1920px width (considering it like a landscape image): width should be crop to 1920px (maintaining the ratio);

if an image is bigger than 1920px height (considering it like a portrait image): height should be crop to 1920px (maintaining the ratio);

format to be always jpg;

quality reduced to 80 to decrease image weight.

my current integration is:

```<code>const transformation = {
  width: 1920, max_height: 1920, format: 'jpg', quality: 80
};
</code>```

But unfortunately this output is a squared image...

I'm trying to use if but I don't understand how should be used... it looks like that writing documentations is always the hardest thing to do...

I hope you can help me to find the right approach. I'm using the SDK, so all plain javascript.

答:
There isn't a max_height parameter in the SDK when creating transformations, but you can achieve what you're looking for by setting both width and height to the maximum value you want to allow.

If you're getting a square output, it's because the default crop/resize mode is scale, which produces an output in exactly the dimensions requested, but may result in the image being 'squashed' or 'stretched'.

What I think you're looking for here is something like this:

```<code>const transformation = {
  width: 1920, height: 1920, format: 'jpg', quality: 'auto', crop: 'limit'
};
</code>```

Which gives you a URL like this:
https://res.cloudinary.com/demo/image/upload/w_1920,h_1920,f_jpg,q_auto,c_limit/bike.jpg

The 'limit' crop mode will scale the image down (not up) until it's smaller than 1920x1920, and will keep the original aspect ratio

Title: Cloudinary API transformation issues

Body:
I'm using Cloudinary as a image storage for my app but I'm having issues to transform my images.

What I would like to achieve is:

if an image is bigger than 1920px width (considering it like a landscape image): width should be crop to 1920px (maintaining the ratio);

if an image is bigger than 1920px height (considering it like a portrait image): height should be crop to 1920px (maintaining the ratio);

format to be always jpg;

quality reduced to 80 to decrease image weight.

my current integration is:

const transformation = {
  width: 1920, max_height: 1920, format: 'jpg', quality: 80
};

But unfortunately this output is a squared image...

I'm trying to use if but I don't understand how should be used... it looks like that writing documentations is always the hardest thing to do...

I hope you can help me to find the right approach. I'm using the SDK, so all plain javascript.

Body:
There isn't a max_height parameter in the SDK when creating transformations, but you can achieve what you're looking for by setting both width and height to the maximum value you want to allow.

If you're getting a square output, it's because the default crop/resize mode is scale, which produces an output in exactly the dimensions requested, but may result in the image being 'squashed' or 'stretched'.

What I think you're looking for here is something like this:

const transformation = {
  width: 1920, height: 1920, format: 'jpg', quality: 'auto', crop: 'limit'
};

Which gives you a URL like this:
https://res.cloudinary.com/demo/image/upload/w_1920,h_1920,f_jpg,q_auto,c_limit/bike.jpg

The 'limit' crop mode will scale the image down (not up) until it's smaller than 1920x1920, and will keep the original aspect ratio


问:
How can I find the current function's closure when debugging JavaScript in vscode
I am debugging a React JS application through VSCode and Chrome. At a breakpoint a variable I am interested in is visible in the Closure section of the variables list. At other levels of the stack trace the variable is not available. The function is defined at the top level of its JS file, and I can't see where the closure is defined, and in particular where the variable is first assigned. Called from elsewhere the closure scoped variable is different and I can't see why.

Is there any way in VS Code Debugging or Chrome Dev Tools to see where the closure scope was defined?

As a simple example, if debugging the JS code below and hitting a breakpoint at a=1 is there any way to identify the closureScope variable in which a is defined? In the real example the function and closure scoped variables are not obviously contained in any other functions or blocks, but my understanding of modern JS and closures is limited and I may be missing something obvious.

```<code>function main() {
  let closureScope = (
    function() {
    var a = 0;
    return {
      inside1: function() {
        a = 1;
      },
      inside2: function() {
        a = 2;
      }
    };
  })();

  closureScope.inside1();
  closureScope.inside2();
}

main();
</code>```

答: This is the alternative with Chrome dev tools

Body:
I am debugging a React JS application through VSCode and Chrome. At a breakpoint a variable I am interested in is visible in the Closure section of the variables list. At other levels of the stack trace the variable is not available. The function is defined at the top level of its JS file, and I can't see where the closure is defined, and in particular where the variable is first assigned. Called from elsewhere the closure scoped variable is different and I can't see why.

Is there any way in VS Code Debugging or Chrome Dev Tools to see where the closure scope was defined?

As a simple example, if debugging the JS code below and hitting a breakpoint at a=1 is there any way to identify the closureScope variable in which a is defined? In the real example the function and closure scoped variables are not obviously contained in any other functions or blocks, but my understanding of modern JS and closures is limited and I may be missing something obvious.

function main() {
  let closureScope = (
    function() {
    var a = 0;
    return {
      inside1: function() {
        a = 1;
      },
      inside2: function() {
        a = 2;
      }
    };
  })();

  closureScope.inside1();
  closureScope.inside2();
}

main();


问:
jstl how to get each element json string
I have the following json string

```<code>[{"nombre":"Estadias Taller serieLoc. 251","array":[{"valores":

[{"nombre":"LUGO DE LLANERA","valor":1.89}],"ejeX":"IB1"},{"valores":[{"nombre":"LUGO DE LLANERA","valor":3.32}],"ejeX":"IB2"},{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.29},{"nombre":"LUGO DE LLANERA","valor":1.41},{"nombre":"TARRAGONA","valor":3.51}],"ejeX":"IS"}]},
{"nombre":"Estadias Taller serieLoc. 252 Merc","array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.31}],"ejeX":"ES1"}]}]
</code>```

This json string has two elements. The first is

```<code> [{"nombre":"Estadias Taller serieLoc. 251","array":[{"valores":[{"nombre":"LUGO DE LLANERA","valor":1.89}],"ejeX":"IB1"},{"valores":[{"nombre":"LUGO DE LLANERA","valor":3.32}],"ejeX":"IB2"},{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.29},{"nombre":"LUGO DE LLANERA","valor":1.41},{"nombre":"TARRAGONA","valor":3.51}],"ejeX":"IS"}]}
</code>```

The second one is

```<code>{"nombre":"Estadias Taller serieLoc. 252 Merc","array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.31}],"ejeX":"ES1"}]}]
</code>```

I want to get these two elements using jstl

I have the following for each

```<code><c:forEach items="${vgraficas}" var="grafica"  >
        <p> grafica xxxx <c:out value="${grafica}" /></p>

</c:forEach>
</code>```

But this loop gets every element in the string, not only two

```<code>grafica xxxx [{"nombre":"Estadias Taller serieLoc. 251"

grafica xxxx "array":[{"valores":[{"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":1.89}]

grafica xxxx "ejeX":"IB1"}

grafica xxxx {"valores":[{"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":3.32}]

grafica xxxx "ejeX":"IB2"}

grafica xxxx {"valores":[{"nombre":"BARCELONA CAN TUNIS"

grafica xxxx "valor":2.29}

grafica xxxx {"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":1.41}

grafica xxxx {"nombre":"TARRAGONA"

grafica xxxx "valor":3.51}]

grafica xxxx "ejeX":"IS"}]}

grafica xxxx {"nombre":"Estadias Taller serieLoc. 252 Merc"

grafica xxxx "array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS"

grafica xxxx "valor":2.31}]

grafica xxxx "ejeX":"ES1"}]}]
</code>```

How can I get the two elements of this json array?

答:
Assuming vgraficas value's type in java is String.

Use the JavaScript function JSON.parse() to convert String into a JavaScript object. suppose it is obj.

Now this obj is basically array of objects. so the outer List will hold the array of Object (i.e. Object[]) which needs to be iterated again to fetch each object element one by one.

```<code><c:forEach items="${obj}" var="outerVar">
      <c:forEach items="${outerVar}" var="innerVar"> // outerVar will hold your object array
         <c:out value="${innerVar}" /> // iterating the object array
      </c:forEach>
  </c:forEach>
</code>```

Body:
I have the following json string

[{"nombre":"Estadias Taller serieLoc. 251","array":[{"valores":

[{"nombre":"LUGO DE LLANERA","valor":1.89}],"ejeX":"IB1"},{"valores":[{"nombre":"LUGO DE LLANERA","valor":3.32}],"ejeX":"IB2"},{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.29},{"nombre":"LUGO DE LLANERA","valor":1.41},{"nombre":"TARRAGONA","valor":3.51}],"ejeX":"IS"}]},
{"nombre":"Estadias Taller serieLoc. 252 Merc","array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.31}],"ejeX":"ES1"}]}]

This json string has two elements. The first is

 [{"nombre":"Estadias Taller serieLoc. 251","array":[{"valores":[{"nombre":"LUGO DE LLANERA","valor":1.89}],"ejeX":"IB1"},{"valores":[{"nombre":"LUGO DE LLANERA","valor":3.32}],"ejeX":"IB2"},{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.29},{"nombre":"LUGO DE LLANERA","valor":1.41},{"nombre":"TARRAGONA","valor":3.51}],"ejeX":"IS"}]}

The second one is

{"nombre":"Estadias Taller serieLoc. 252 Merc","array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS","valor":2.31}],"ejeX":"ES1"}]}]

I want to get these two elements using jstl

I have the following for each

<c:forEach items="${vgraficas}" var="grafica"  >

 grafica xxxx <c:out value="${grafica}" />

</c:forEach>

But this loop gets every element in the string, not only two

grafica xxxx [{"nombre":"Estadias Taller serieLoc. 251"

grafica xxxx "array":[{"valores":[{"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":1.89}]

grafica xxxx "ejeX":"IB1"}

grafica xxxx {"valores":[{"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":3.32}]

grafica xxxx "ejeX":"IB2"}

grafica xxxx {"valores":[{"nombre":"BARCELONA CAN TUNIS"

grafica xxxx "valor":2.29}

grafica xxxx {"nombre":"LUGO DE LLANERA"

grafica xxxx "valor":1.41}

grafica xxxx {"nombre":"TARRAGONA"

grafica xxxx "valor":3.51}]

grafica xxxx "ejeX":"IS"}]}

grafica xxxx {"nombre":"Estadias Taller serieLoc. 252 Merc"

grafica xxxx "array":[{"valores":[{"nombre":"BARCELONA CAN TUNIS"

grafica xxxx "valor":2.31}]

grafica xxxx "ejeX":"ES1"}]}]

How can I get the two elements of this json array?

Body:
Assuming vgraficas value's type in java is String.

Use the JavaScript function JSON.parse() to convert String into a JavaScript object. suppose it is obj.

Now this obj is basically array of objects. so the outer List will hold the array of Object (i.e. Object[]) which needs to be iterated again to fetch each object element one by one.

<c:forEach items="${obj}" var="outerVar">
      <c:forEach items="${outerVar}" var="innerVar"> // outerVar will hold your object array
         <c:out value="${innerVar}" /> // iterating the object array
      </c:forEach>
  </c:forEach>


问:
How to ensure referential integrity which relies on values
Suppose I have a table Level1:

```<code>Id int PK
Deleted bit
</code>```

and another table Level2:

```<code>Id int
Deleted bit
Level1id int
</code>```

I can add a FK to Level2 to match the Level1id with Level1.Id That works fine in ensuring the parent exists.

However, what If I want to ensure that records can only be INSERTed in Level2 when the matching record in Level1 has Deleted bit = 0 ?

Furthermore, how can I prevent the Deleted flag in Level1 from being set = 1 when any child records in Level2 have their Deleted bit = 0 ?
i.e. all child records must have Deleted = 1 before the Parent record can have Deleted = 1

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

答:
You can do this with a foreign key constraint, but you need to add some more information.

First a unique constraint that includes the bit:

```<code>alter table level1 add constraint unq_level1_id, deleted
    unique (delete, id);
</code>```

Then, add a constant 0 value to level2

```<code>alter table level2 add (cast(0 as bit)) as deleted_0 persisted;
</code>```

Then, add in the foreign key constraint:

```<code>alter table level2 add constraint fk_level2_id_deleted
    foreign key (level1id, deleted) references table1(id, deleted);
</code>```

Body:
Suppose I have a table Level1:

Id int PK
Deleted bit

and another table Level2:

Id int
Deleted bit
Level1id int

I can add a FK to Level2 to match the Level1id with Level1.Id That works fine in ensuring the parent exists.

However, what If I want to ensure that records can only be INSERTed in Level2 when the matching record in Level1 has Deleted bit = 0 ?

Furthermore, how can I prevent the Deleted flag in Level1 from being set = 1 when any child records in Level2 have their Deleted bit = 0 ?
i.e. all child records must have Deleted = 1 before the Parent record can have Deleted = 1

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

Body:
You can do this with a foreign key constraint, but you need to add some more information.

First a unique constraint that includes the bit:

alter table level1 add constraint unq_level1_id, deleted
    unique (delete, id);

Then, add a constant 0 value to level2

alter table level2 add (cast(0 as bit)) as deleted_0 persisted;

Then, add in the foreign key constraint:

alter table level2 add constraint fk_level2_id_deleted
    foreign key (level1id, deleted) references table1(id, deleted);


问:
how to be sure in Linq to SQL that record has been added successfully or not?
I am just learning Linq to SQL and don't know much. Kindly guide and help me.

I am adding a new record by using a SubmitChanges();  How I can be confirmed that record has been added? For example, in using stored procedures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.

答:
You could do something like this;

```<code>public void Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here.
    try
    {
        db.SubmitChanges();
    }
    catch (Exception err)
    {
        //Log error
    }
}
</code>```

If no exception is thrown you can assume the data is saved correct. Though another option is something like this.

```<code>public bool Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here.
    try
    {
        db.SubmitChanges();
        return true;
    }
    catch (Exception e)
    {
        //Log the error
        return false;
    }
}
</code>```

True will be returned if save succeeds, otherwise false will be returned

Body:
You could do something like this;

public void Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here.
    try
    {
        db.SubmitChanges();
    }
    catch (Exception err)
    {
        //Log error
    }
}

If no exception is thrown you can assume the data is saved correct. Though another option is something like this.

public bool Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here.
    try
    {
        db.SubmitChanges();
        return true;
    }
    catch (Exception e)
    {
        //Log the error
        return false;
    }
}

True will be returned if save succeeds, otherwise false will be returned


问:
How to find if we have two or more equal minimum values in specific columns
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

```<code>head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")
</code>```

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

```<code>head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")
</code>```

Thank you in advance.

答:
Here's a purrr solution. I create the data frame.

# Define data frame
df <- read.table(text = " t1  a1  a2  a3  a4
                  34  NA  NA  NA  NA
                  26  10  15  250 150
                  34  20  20  100 30
                  35  5   5   10  5
                  25  45  100 3   45
                  31 400 310 500 310 ", header = TRUE)
```

<p>Next, I load the library.</p>

<pre class="lang-r prettyprint-override"><code># Load library
library(purrr)
</code>```

Then, I create the flag, running through each row using pmap_lgl, which returns a logical. This line checks if there is more than one minimum value and that the minimum is below 200. The first column is omitted from the calculation. If there are NA values in each row, an NA will be created.

# Create flag
df$flag <- pmap_lgl(df, function(...)(sum(c(...)[-1] == min(c(...)[-1])) > 1) & min(c(...)[-1]) < 200)
```

<p>This gives the following:</p>

<pre class="lang-r prettyprint-override"><code># Examine result
df
#>   t1  a1  a2  a3  a4  flag
#> 1 34  NA  NA  NA  NA    NA
#> 2 26  10  15 250 150 FALSE
#> 3 34  20  20 100  30  TRUE
#> 4 35   5   5  10   5  TRUE
#> 5 25  45 100   3  45 FALSE
#> 6 31 400 310 500 310 FALSE
</code>```

Created on 2019-05-31 by the reprex package (v0.3.0)

Body:
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")

Thank you in advance.

Body:
Here's a purrr solution. I create the data frame.

# Define data frame
df <- read.table(text = " t1  a1  a2  a3  a4
                  34  NA  NA  NA  NA
                  26  10  15  250 150
                  34  20  20  100 30
                  35  5   5   10  5
                  25  45  100 3   45
                  31 400 310 500 310 ", header = TRUE)

Next, I load the library.

# Load library
library(purrr)

Then, I create the flag, running through each row using pmap_lgl, which returns a logical. This line checks if there is more than one minimum value and that the minimum is below 200. The first column is omitted from the calculation. If there are NA values in each row, an NA will be created.

# Create flag
df$flag <- pmap_lgl(df, function(...)(sum(c(...)[-1] == min(c(...)[-1])) > 1) & min(c(...)[-1]) < 200)

This gives the following:

# Examine result
df
#>   t1  a1  a2  a3  a4  flag
#> 1 34  NA  NA  NA  NA    NA
#> 2 26  10  15 250 150 FALSE
#> 3 34  20  20 100  30  TRUE
#> 4 35   5   5  10   5  TRUE
#> 5 25  45 100   3  45 FALSE
#> 6 31 400 310 500 310 FALSE

Created on 2019-05-31 by the reprex package (v0.3.0)


问:
Any way to put an if statement in the function call argument?
I found out that we can use the ternary op inside the function call argument:

def foo(n):
    print(n)
```

<pre class="lang-py prettyprint-override"><code>a, b = 1, 2
foo(a if a>b else b)
# prints 2
</code>```

I wonder is there a way to use if without the else in the function call argument? so something like if it's true, pass a to it, if not, don't pass anything.

I've tried

foo(a if a>b else pass)
foo(a if a>b)
foo(if a>b: a)
foo(a>b and a)
```

<p>None of the above works.</p>

<p>Thanks for your help.</p>

<p>Edit-----</p>

<p>Sorry, let me rephrase my question.</p>

<p>What I'm asking for is a way to determine whether I should pass the argument based on a condition.</p>

<p>So basically I have to call a big function that takes a lot of kwargs, say:</p>

<pre class="lang-py prettyprint-override"><code># function call
thefunc(
    a=1,
    b=2,
    c=3,
    d=4,
    e=5
    #...
)
</code>```

And all of the args are options which its up to me, or in some cases, a condition.

Since the argument list is so big that writing function calls inside the if statement is not preferred, so I need to know is there a way to, say:

thefunc(
    a=1,
    #if condition: b=2,
    c=3,
    ....
)
```

So to determine whether to give the kwarg or not. Its okay if there isn't, just need to know, thanks.

答:
You can if you don't mind some ugliness... The * syntax turns a list of values into parameters, so you could use:

```<code>foo(*[a] if a > b else [])
</code>```

Whether you should is something else :-)

Body:
I found out that we can use the ternary op inside the function call argument:

def foo(n):
    print(n)

a, b = 1, 2
foo(a if a>b else b)
# prints 2

I wonder is there a way to use if without the else in the function call argument? so something like if it's true, pass a to it, if not, don't pass anything.

I've tried

foo(a if a>b else pass)
foo(a if a>b)
foo(if a>b: a)
foo(a>b and a)

None of the above works.

Thanks for your help.

Edit-----

Sorry, let me rephrase my question.

What I'm asking for is a way to determine whether I should pass the argument based on a condition.

So basically I have to call a big function that takes a lot of kwargs, say:

# function call
thefunc(
    a=1,
    b=2,
    c=3,
    d=4,
    e=5
    #...
)

And all of the args are options which its up to me, or in some cases, a condition.

Since the argument list is so big that writing function calls inside the if statement is not preferred, so I need to know is there a way to, say:

thefunc(
    a=1,
    #if condition: b=2,
    c=3,
    ....
)

So to determine whether to give the kwarg or not. Its okay if there isn't, just need to know, thanks.

Body:
You can if you don't mind some ugliness... The * syntax turns a list of values into parameters, so you could use:

foo(*[a] if a > b else [])

Whether you should is something else :-)


问:
Python function execution on iterator till empty
I have an iterator and I want to execute function on the iterator till the iterator is empty. Is my approach below correct or is there better practice? </p>

```<code>import pandas as pd

df_iter = pd.read_csv(file_path, chunksize=some_chunksize_value)

def some_function(data):
    try:
        do sth with data.__next__()
        some_function(data)
    except StopIteration:
        do sth here
        return True

some_function(df_iter )
</code>```

答:
Use a for loop. This will automatically call next() and halt on a StopIteration without you having to do anything.

```<code>for item in df_iter:
    #do something with data here
</code>```

You don't need to use recursion for this, and recursion is especially unsuitable if there is any chance your iterator has more than 1000 values. Then you'll crash with "maximum recursion depth exceeded" before reaching the end.

If you're in a functional-paradigm mood, you can use map to apply a function to an iterable without requiring an explicit for loop.

```<code>map(do_thing, df_iter)
</code>```

This will return another iterable that calls do_thing on each element of df_iter as you iterate over it. (Or, in Python 2.7, it calls do_thing on each element immediately and returns a list of all the results)

This approach is relatively rare, since for loops, list comprehensions, and/or generator expressions can do the same thing with arguably simpler syntax.

Body:
I have an iterator and I want to execute function on the iterator till the iterator is empty. Is my approach below correct or is there better practice?

import pandas as pd

df_iter = pd.read_csv(file_path, chunksize=some_chunksize_value)

def some_function(data):
    try:
        do sth with data.__next__()
        some_function(data)
    except StopIteration:
        do sth here
        return True

some_function(df_iter )

Body:
Use a for loop. This will automatically call next() and halt on a StopIteration without you having to do anything.

for item in df_iter:
    #do something with data here

You don't need to use recursion for this, and recursion is especially unsuitable if there is any chance your iterator has more than 1000 values. Then you'll crash with "maximum recursion depth exceeded" before reaching the end.

If you're in a functional-paradigm mood, you can use map to apply a function to an iterable without requiring an explicit for loop.

map(do_thing, df_iter)

This will return another iterable that calls do_thing on each element of df_iter as you iterate over it. (Or, in Python 2.7, it calls do_thing on each element immediately and returns a list of all the results)

This approach is relatively rare, since for loops, list comprehensions, and/or generator expressions can do the same thing with arguably simpler syntax.


答:
One possibility involving dplyr and purrr:

```<code>df %>%
 mutate(flag = exec(pmin, !!!.[-1]),
        flag = rowSums(.[-1] == flag) > 1 & flag < 200)

  t1  a1  a2  a3  a4  flag
1 34  NA  NA  NA  NA    NA
2 26  10  15 250 150 FALSE
3 34  20  20 100  30  TRUE
4 35   5   5  10   5  TRUE
5 25  45 100   3  45 FALSE
6 31 400 310 500 310 FALSE
</code>```

Here it checks whether the occurrence of row-wise minimum is greater than 1 and whether the row-wise minimum is below 200.

Title: How to find if we have two or more equal minimum values in specific columns

Body:
One possibility involving dplyr and purrr:

df %>%
 mutate(flag = exec(pmin, !!!.[-1]),
        flag = rowSums(.[-1] == flag) > 1 & flag < 200)

  t1  a1  a2  a3  a4  flag
1 34  NA  NA  NA  NA    NA
2 26  10  15 250 150 FALSE
3 34  20  20 100  30  TRUE
4 35   5   5  10   5  TRUE
5 25  45 100   3  45 FALSE
6 31 400 310 500 310 FALSE

Here it checks whether the occurrence of row-wise minimum is greater than 1 and whether the row-wise minimum is below 200.


问:
Combining both a text message and an HTML table in one e-mail
I have the following code which sends out an email with the cases that exceeded the threshold (those cases are inserted as an HTML object into the e-mail). Right now the code works fine, but it doesn't do one thing I want it to do.

```<code>function CheckAAShare() {
  // Fetch the monthly sales
  var Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("4. Daily Catergory Share").getRange("I2");
  var result = Range.getValue();
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("4. Email alert");
var lastRow = dataSheet.getLastRow();
var data = dataSheet.getRange(1, 1, lastRow, 6).getValues();

  var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'

  var htmltable = '<table ' + TABLEFORMAT +' ">';

for (row = 0; row<data.length; row++){

htmltable += '<tr>';

for (col = 0 ;col<data[row].length; col++){
  if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
  else
    if (row === 0)  {
      htmltable += '<th>' + data[row][col] + '</th>';
    }

  else {htmltable += '<td>' + data[row][col] + '</td>';}
}

     htmltable += '</tr>';
}

     htmltable += '</table>';
     Logger.log(data);
     Logger.log(htmltable);
  // Check totals sales
  if (result >0){
    // Fetch the email address
      var emailAddress = "ops@gmail.com";
    // Send Alert Email.
    var message = 'There are ' + result +' deviating metrics: https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698'
    + ' See the dashboard here: <Dashboard link>;
    var subject = 'Transaction Monitoring Alert';
    MailApp.sendEmail(emailAddress, subject, message, {htmlBody:htmltable});
    }
}
</code>```

As you can see from the code, I also want to attach a text message before this table in the e-mail: something like "There are 4 deviating metrics. See the dashboard here: Dashboard_link. See the summary below:" + HTML_table.

The question is: how can I combine both this text message and the HTML table in 1 e-mail? The current output looks like this:

答:
You need to write the message in both text and HTML format.</p>

```<code>var textMessage = 'There are ' + result +' deviating metrics: ' + ' See the dashboard here: https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698';
var htmlMessage = '<p>There are ' + result +' deviating metrics:' + ' See the dashboard <a href="https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698">here</a></p>';
var subject = 'Transaction Monitoring Alert';
MailApp.sendEmail(emailAddress, subject, textMessage, {htmlBody:htmlMessage + htmltable});
</code>```

Body:
I have the following code which sends out an email with the cases that exceeded the threshold (those cases are inserted as an HTML object into the e-mail). Right now the code works fine, but it doesn't do one thing I want it to do.

function CheckAAShare() {
  // Fetch the monthly sales
  var Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("4. Daily Catergory Share").getRange("I2");
  var result = Range.getValue();
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("4. Email alert");
var lastRow = dataSheet.getLastRow();
var data = dataSheet.getRange(1, 1, lastRow, 6).getValues();

  var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'

  var htmltable = '
';

for (row = 0; row<data.length; row++){

htmltable += '
';

for (col = 0 ;col<data[row].length; col++){
  if (data[row][col] === "" || 0) {htmltable += '' + 'None' + '	';}
  else
    if (row === 0)  {
      htmltable += '' + data[row][col] + '	';
    }

  else {htmltable += '' + data[row][col] + '	';}
}

     htmltable += '
';
}

     htmltable += '
';
     Logger.log(data);
     Logger.log(htmltable);
  // Check totals sales
  if (result >0){
    // Fetch the email address
      var emailAddress = "ops@gmail.com";
    // Send Alert Email.
    var message = 'There are ' + result +' deviating metrics: https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698'
    + ' See the dashboard here: <Dashboard link>;
    var subject = 'Transaction Monitoring Alert';
    MailApp.sendEmail(emailAddress, subject, message, {htmlBody:htmltable});
    }
}

As you can see from the code, I also want to attach a text message before this table in the e-mail: something like "There are 4 deviating metrics. See the dashboard here: Dashboard_link. See the summary below:" + HTML_table.

The question is: how can I combine both this text message and the HTML table in 1 e-mail? The current output looks like this:

Body:
You need to write the message in both text and HTML format.

var textMessage = 'There are ' + result +' deviating metrics: ' + ' See the dashboard here: https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698';
var htmlMessage = '<p>There are ' + result +' deviating metrics:' + ' See the dashboard <a href="https://docs.google.com/spreadsheets/d/1AQEV4Gt919TIu92Gb9TeZRD3KpSm3L_WCHgTOmw/edit#gid=1525731698">here</a></p>';
var subject = 'Transaction Monitoring Alert';
MailApp.sendEmail(emailAddress, subject, textMessage, {htmlBody:htmlMessage + htmltable});