问:
How to create a type function that checks whether a type is empty object in TypeScript?
Is it possible to create a type function IsEmpty such that:

```<code>type a = IsEmpty<{}> // true
type b = IsEmpty<{x: 1}> // never
</code>```

答:
type IsEmpty<T> = {} extends T ? true : never;
```

see conditional type

Body:
Is it possible to create a type function IsEmpty such that:

type a = IsEmpty<{}> // true
type b = IsEmpty<{x: 1}> // never

Body:
type IsEmpty<T> = {} extends T ? true : never;

see conditional type


来源: stackexchange

问:
How to switch github account and retrospectively update commit history?
I have made several commits using a GitHub account on a private repository. I would however like to switch my github account and also transfer the commit history to the new account as-if I was always using the new account. Is there a way to accomplish this in GitHub?
I read about transferring repository but my the repository is not owned by me and also doesn't provide an option to transfer.

答:
If you can clone the repository, you need then to use newren/git-filter-repo in order to rewrite the author from your old account to your new account.

See "How to change commit author for multiple commits using filter branch?" and

"git filter-repo / User and email based filtering"

```<code>git filter-repo --mailmap my-mailmap
</code>```

with my-mailmap:

```<code>Correct Name <correct@email.com> <old@email.com>
</code>```

Then you can create a new empty repository on GitHub, and push everything to it:

```<code>git remote set-url https://github.com/<me>/newRepo>
git push --mirror
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you can clone the repository, you need then to use newren/git-filter-repo in order to rewrite the author from your old account to your new account.

See "How to change commit author for multiple commits using filter branch?" and

"git filter-repo / User and email based filtering"

git filter-repo --mailmap my-mailmap

with my-mailmap:

Correct Name <correct@email.com> <old@email.com>

Then you can create a new empty repository on GitHub, and push everything to it:

git remote set-url https://github.com/<me>/newRepo>
git push --mirror


问:
Custom text to  tag using CSS
I have a two  tags and it's HTML as below:

```<code><ul>
  <li><a href="#">This is my link</a></li>
  <li><a href="#">This is my link</a></li>
</ul>
</code>```

What I want is, to replace links text as this:

```<code><ul>
  <li><a href="#">custom 1</a></li>
  <li><a href="#">custom 2</a></li>
</ul>
</code>```

This is how I tried it using CSS. But still I couldn't figure this out.

```<code>ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul li {
  padding: 0;
  margin: 0;
}

ul li a {
  color: #fff;
  font-size: 0;
  position: relative;
}

ul li a:first-child:after {
  content: 'Custom 1';
  position: absolute;
  top: 0;
  left: 0;
}

ul li a:last-child:after {
  content: 'Custom 2';
  position: absolute;
  top: 0;
  left: 0;
}
</code>```

Hope somebody may help me out. Thank you.

答:
ul li:first-child a:before {
  content: 'Custom 1';
  position: absolute;
  color: DodgerBlue;
  background: #fff;
  width: 100px;
  text-decoration: underline;
}

ul li:last-child a:before {
  content: 'Custom 2';
  position: absolute;
  color: DodgerBlue;
  background: #fff;
  width: 100px;
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>This is my link</li>
  <li>This is my link</li>
</ul></code>```

Title: Custom text to <a> tag using CSS

Body:
I have a two  tags and it's HTML as below:

This is my link

This is my link

What I want is, to replace links text as this:

custom 1

custom 2

This is how I tried it using CSS. But still I couldn't figure this out.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul li {
  padding: 0;
  margin: 0;
}

ul li a {
  color: #fff;
  font-size: 0;
  position: relative;
}

ul li a:first-child:after {
  content: 'Custom 1';
  position: absolute;
  top: 0;
  left: 0;
}

ul li a:last-child:after {
  content: 'Custom 2';
  position: absolute;
  top: 0;
  left: 0;
}

Hope somebody may help me out. Thank you.

Body:
ul li:first-child a:before {
  content: 'Custom 1';
  position: absolute;
  color: DodgerBlue;
  background: #fff;
  width: 100px;
  text-decoration: underline;
}

ul li:last-child a:before {
  content: 'Custom 2';
  position: absolute;
  color: DodgerBlue;
  background: #fff;
  width: 100px;
  text-decoration: underline;
}

<ul>
  <li><a href="#">This is my link</a></li>
  <li><a href="#">This is my link</a></li>
</ul>


问:
Using jQuery to post back to a controller
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

```<code>$.post("Home\PostExample")
</code>```

but i would like to include a value from a dropdown menu:

```<code>@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })
</code>```

into an Actionresult:

```<code>[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}
</code>```

Any help would be appreciated.

Thanks.

答:
Adding to grega's answer, you can also make use of callback function if you want to return some data from action method and display it to user.</p>

```<code> $.post("Home/PostExample", { myString: $("#exampleCssId").val() }, function(result){
     alert(result);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

$.post("Home\PostExample")

but i would like to include a value from a dropdown menu:

@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })

into an Actionresult:

[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}

Any help would be appreciated.

Thanks.

Body:
Adding to grega's answer, you can also make use of callback function if you want to return some data from action method and display it to user.

 $.post("Home/PostExample", { myString: $("#exampleCssId").val() }, function(result){
     alert(result);
});


问:
making the whole page blur when I click on a certain button
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="phone_num d-none d-xl-block">
  {% trans 'try' %}
</div></code>```

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

答:
It depends on the browser, where the alert message appears. Usually it's somewhere on the top of the screen. If you want an actual pop-up, I would recommend creating a custom one and the simply use the JQuery functions fadeIn() and fadeOut(). This way you can also customize the place of the pop-up.

function myFunction() {
    $('body').css("filter","blur(2px)");
    alert("hello");
}```
<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="phone_num d-none d-xl-block">
  blur bg
</div></code>```

Body:
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}

  {% trans 'try' %}

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

Body:
It depends on the browser, where the alert message appears. Usually it's somewhere on the top of the screen. If you want an actual pop-up, I would recommend creating a custom one and the simply use the JQuery functions fadeIn() and fadeOut(). This way you can also customize the place of the pop-up.

function myFunction() {
    $('body').css("filter","blur(2px)");
    alert("hello");
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="phone_num d-none d-xl-block">
  <a class="boxed-btn3" href="#" onclick="myFunction()">blur bg</a>
</div>


问:
Using React Router from a non-react class
I have a manager class in my app that is just a regular JS class, it's purely logical with no view. I use an instance of it in several of my components. For one of it's actions I'd like it to change the route in my React based app. I know I can return something to each component and then have the component do the routing, but I'd like to know if there is a way to do it from my non-react class. Is there maybe a way to pass in the history object and push the new route to it?

Thanks for any help.

EDIT: It's more of a theoretical/methodolgy question but for example:
Manager class:

```<code>class MyManagerClass {
 constructor() {
    this.data = {...some internal data};
}

doSomething(param) {
    if(this.data[param]) {
        this.data[param]();
    } else {
        //here i'd like to change the route in my react app
    }
}
}
</code>```

Component:

```<code>import React, {useContext, useEffect, useRef, useState} from "react";

const MyComponent = props => {
const myManagerClass = new MyManagerClass();

useEffect(() => {
    myManagerClass.doSomething('param');
}, [props.something]);

return (
    <div>Component</div>
)
}
</code>```

答:
There are minimum 2 solutions to this

SOLUTION 1:

You can pass the history object to the action as argument from the component

```<code>class Util {

  static someAction(history) {
      history.push('/someurl');
  }
}
</code>```

and call it like

```<code>const Comp = () => {
   const history = useHistory();
   const someHandler = () => {
       Util.someAction(history);
   }
   ...
}
</code>```

SOLUTION 2:

Use a custom history for Router and then you can import history directly into the class file

history.js

```<code>import {createBrowserHistory}  from 'history';
export const history = createBrowserHistory();
</code>```

use it for Router like

```<code>import { Router } from 'react-router-dom';
import { history } from './path/to/history';
...

return (
  <Router history={history}>{/* Routes here */}</Router>
)
</code>```

and then in your Class file

```<code>import {history} from '/path/to/history';

class Util {

  static someAction() {
      history.push('/someurl');
  }
}
</code>```

Body:
I have a manager class in my app that is just a regular JS class, it's purely logical with no view. I use an instance of it in several of my components. For one of it's actions I'd like it to change the route in my React based app. I know I can return something to each component and then have the component do the routing, but I'd like to know if there is a way to do it from my non-react class. Is there maybe a way to pass in the history object and push the new route to it?

Thanks for any help.

EDIT: It's more of a theoretical/methodolgy question but for example:
Manager class:

class MyManagerClass {
 constructor() {
    this.data = {...some internal data};
}

doSomething(param) {
    if(this.data[param]) {
        this.data[param]();
    } else {
        //here i'd like to change the route in my react app
    }
}
}

Component:

import React, {useContext, useEffect, useRef, useState} from "react";

const MyComponent = props => {
const myManagerClass = new MyManagerClass();

useEffect(() => {
    myManagerClass.doSomething('param');
}, [props.something]);

return (

Component

)
}

Body:
There are minimum 2 solutions to this

SOLUTION 1:

You can pass the history object to the action as argument from the component

class Util {

  static someAction(history) {
      history.push('/someurl');
  }
}

and call it like

const Comp = () => {
   const history = useHistory();
   const someHandler = () => {
       Util.someAction(history);
   }
   ...
}

SOLUTION 2:

Use a custom history for Router and then you can import history directly into the class file

history.js

import {createBrowserHistory}  from 'history';
export const history = createBrowserHistory();

use it for Router like

import { Router } from 'react-router-dom';
import { history } from './path/to/history';
...

return (
  <Router history={history}>{/* Routes here */}</Router>
)

and then in your Class file

import {history} from '/path/to/history';

class Util {

  static someAction() {
      history.push('/someurl');
  }
}


问:
How to setup a custom cron job in opencart?
Can anyone tell me how can I setup a custom cron job in opencart?

I have Url in below format and when I am manually hit this url it works perfectly now I want to make it dynamic on cron schedule basis.

I have setup cron job in https://cron-job.org/en/ using below URL and it works fine but I'm not sure whether it is the right way or not?

```<code>> http://www.yourstore.com/admin/index_for_cron.php?route=module/modulename/function
</code>```

Thanks in advance..!

答:
If you able to setup cron tasks on your web-server, you are always can use curl:

```<code> curl -s "http://www.yourstore.com/admin/index_for_cron.php?route=module/modulename/function" >/dev/null
</code>```

I'm also managed to run my custom modules for OpenCart3 with command like this:

```<code> cd /path/to/your/site && QUERY_STRING="route=module/modulename/function" php -r 'parse_str($_SERVER["QUERY_STRING"],$_GET);include "index.php";'
</code>```

(But in this case you need to consider file permissions and run task under appropriate user.)

Body:
Can anyone tell me how can I setup a custom cron job in opencart?

I have Url in below format and when I am manually hit this url it works perfectly now I want to make it dynamic on cron schedule basis.

I have setup cron job in https://cron-job.org/en/ using below URL and it works fine but I'm not sure whether it is the right way or not?

> http://www.yourstore.com/admin/index_for_cron.php?route=module/modulename/function

Thanks in advance..!

Body:
If you able to setup cron tasks on your web-server, you are always can use curl:

 curl -s "http://www.yourstore.com/admin/index_for_cron.php?route=module/modulename/function" >/dev/null

I'm also managed to run my custom modules for OpenCart3 with command like this:

 cd /path/to/your/site && QUERY_STRING="route=module/modulename/function" php -r 'parse_str($_SERVER["QUERY_STRING"],$_GET);include "index.php";'

(But in this case you need to consider file permissions and run task under appropriate user.)


问:
Edit middle button on bottom tab navigation with React-navigation V5
I'm trying to create a Bottom tab navigation with react-navigation V5, like the image below. The middle one with a bigger image size than the others.

答:
You can get some idea from this. I have done using image. You can do by icon as well if you want.
I have change this on focus you can keep it fix.</p>

```<code><Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'red',
                   // activeBackgroundColor:'#000',
                    //inactiveBackgroundColor:'red',
                    labelStyle: {
                         position: 'absolute',
                         top: constants.vh(35),
                        fontSize:constants.vh(18),
                    }
                }}
            >
                <Tab.Screen name='Home' //bottom tab for Home
                    options={{
                        tabBarIcon: ({ focused }) => {
                            let iconName;
                            iconName = focused ? constants.images.bottomHome : constants.images.bottomHome //for icon or image
                            return (
                                <View>
                                    <Image source={iconName} style={{ width: constants.vw(40), height: constants.vh(25) ,position:'absolute',right:constants.vw(-20),bottom:constants.vh(-5)}} resizeMode="contain" />
                                </View>
                            )
                        }
                    }}
                    component={HomeScreen} />
</Tab.Navigator>
</code>```

Body:
You can get some idea from this. I have done using image. You can do by icon as well if you want.
I have change this on focus you can keep it fix.

<Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'red',
                   // activeBackgroundColor:'#000',
                    //inactiveBackgroundColor:'red',
                    labelStyle: {
                         position: 'absolute',
                         top: constants.vh(35),
                        fontSize:constants.vh(18),
                    }
                }}
            >
                <Tab.Screen name='Home' //bottom tab for Home
                    options={{
                        tabBarIcon: ({ focused }) => {
                            let iconName;
                            iconName = focused ? constants.images.bottomHome : constants.images.bottomHome //for icon or image
                            return (
                                <View>
                                    <Image source={iconName} style={{ width: constants.vw(40), height: constants.vh(25) ,position:'absolute',right:constants.vw(-20),bottom:constants.vh(-5)}} resizeMode="contain" />
                                </View>
                            )
                        }
                    }}
                    component={HomeScreen} />
</Tab.Navigator>


问:
mysql if value = "0" then get other value
I have a table as follows:

```<code>+-----------+------+--------+
| stockcode | year | equity |
+-----------+------+--------+
| AALI      | 2016 |  17347 |
| AALI      | 2017 |  18236 |
| AALI      | 2018 |  18990 |
| AALI      | 2019 |  18521 |
| ABBA      | 2016 |    132 |
| ABBA      | 2017 |    104 |
| ABBA      | 2018 |    203 |
| ABBA      | 2019 |      0 |
| ABDA      | 2016 |   1232 |
| ABDA      | 2017 |   1375 |
| ABDA      | 2018 |   1334 |
| ABDA      | 2019 |   1254 |
+-----------+------+--------+
</code>```

I need a query to get equity values based on the last year.
and if the value of the equity in 2019 = 0, get the value in 2018.

I tried to make it this way but it didn't work(blank page):

```<code>SELECT IF(equity <> '0', equity, SELECT equity FROM table_equity WHERE year='2018' AND stockcode='".$stockcode."') as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"
</code>```

but when I try with code like this it's work:

```<code>SELECT IF(equity <> '0', "active", "nonactive") as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"
</code>```

but of course the results were not what I wanted

So how to?

答:
As you are filtering by stockcode I would sort by year (desc) and then get the first row with non zero equity:

```<code>"SELECT * FROM table_equity
WHERE stockcode='".$stockcode."' AND equity <> 0 AND year < YEAR(CURDATE())
ORDER BY year DESC
LIMIT 1"
</code>```

And you should use prepared statements to prevent from sql injection attacks.

Body:
I have a table as follows:

+-----------+------+--------+
| stockcode | year | equity |
+-----------+------+--------+
| AALI      | 2016 |  17347 |
| AALI      | 2017 |  18236 |
| AALI      | 2018 |  18990 |
| AALI      | 2019 |  18521 |
| ABBA      | 2016 |    132 |
| ABBA      | 2017 |    104 |
| ABBA      | 2018 |    203 |
| ABBA      | 2019 |      0 |
| ABDA      | 2016 |   1232 |
| ABDA      | 2017 |   1375 |
| ABDA      | 2018 |   1334 |
| ABDA      | 2019 |   1254 |
+-----------+------+--------+

I need a query to get equity values based on the last year.
and if the value of the equity in 2019 = 0, get the value in 2018.

I tried to make it this way but it didn't work(blank page):

SELECT IF(equity <> '0', equity, SELECT equity FROM table_equity WHERE year='2018' AND stockcode='".$stockcode."') as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"

but when I try with code like this it's work:

SELECT IF(equity <> '0', "active", "nonactive") as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"

but of course the results were not what I wanted

So how to?

Body:
As you are filtering by stockcode I would sort by year (desc) and then get the first row with non zero equity:

"SELECT * FROM table_equity
WHERE stockcode='".$stockcode."' AND equity <> 0 AND year < YEAR(CURDATE())
ORDER BY year DESC
LIMIT 1"

And you should use prepared statements to prevent from sql injection attacks.


问:
Query json_array in where clauses by key and value
I have a select query witch returns me an array_to_json object. I want to filters the results of select based on specifics keys and values.

Here is my actual query:

```<code>select jsonarray
from (
         SELECT body.id_user,
                array_to_json(array_agg(row_to_json(body))) as jsonarray
         FROM (
                  SELECT  id_user, name, value
                  FROM table_1
                  group by id_user, name, value
              ) body
         group by body.id_user
     ) as test;

</code>```

It returns a lot of rows like this:

```<code>[{"id_user": 1489, "name": "name 1", "value": "value aaaaaa"},  {"id_user": 1489, "name": "name 2", "value": "value babababab"}]

[{ "id_user": 1490, "name": "name 12", "value": "value aaaaaa"  }, { "id_user": 1490, "name": "name 2",  "value": "value babababab" }]

[ { "id_user": 1491, "name": "name 13", "value": "value aaaaaa"  }, { "id_user": 1491,  "name": "name 23",  "value": "value uouououo" }]
</code>```

Well, I want only the rows that have the fields "name": "name 2",  "value": "value babababab" into the json... I've tried

```<code>select jsonarray->'name'
from (
....
     ) as test
where jsonarray->>'name'::text = 'name 2';
</code>```

but it returns nothing. There's another way to query it?

答:
You can check if name 2 is present during the aggregation:

```<code>SELECT jsonb_agg(to_jsonb(body)) as jsonarray
FROM (
  SELECT DISTINCT id_user, name, value
  FROM table_1
) body
group by body.id_user
having bool_or(name = 'name 2') -- those with at least one `name = 'name 2'`
</code>```

Online example

Body:
I have a select query witch returns me an array_to_json object. I want to filters the results of select based on specifics keys and values.

Here is my actual query:

select jsonarray
from (
         SELECT body.id_user,
                array_to_json(array_agg(row_to_json(body))) as jsonarray
         FROM (
                  SELECT  id_user, name, value
                  FROM table_1
                  group by id_user, name, value
              ) body
         group by body.id_user
     ) as test;

It returns a lot of rows like this:

[{"id_user": 1489, "name": "name 1", "value": "value aaaaaa"},  {"id_user": 1489, "name": "name 2", "value": "value babababab"}]

[{ "id_user": 1490, "name": "name 12", "value": "value aaaaaa"  }, { "id_user": 1490, "name": "name 2",  "value": "value babababab" }]

[ { "id_user": 1491, "name": "name 13", "value": "value aaaaaa"  }, { "id_user": 1491,  "name": "name 23",  "value": "value uouououo" }]

Well, I want only the rows that have the fields "name": "name 2",  "value": "value babababab" into the json... I've tried

select jsonarray->'name'
from (
....
     ) as test
where jsonarray->>'name'::text = 'name 2';

but it returns nothing. There's another way to query it?

Body:
You can check if name 2 is present during the aggregation:

SELECT jsonb_agg(to_jsonb(body)) as jsonarray
FROM (
  SELECT DISTINCT id_user, name, value
  FROM table_1
) body
group by body.id_user
having bool_or(name = 'name 2') -- those with at least one `name = 'name 2'`

Online example


问:
A query to summarize data in sub-tree?
My data fits a tree form naturally. Therefore, I have a simple SQL table to store the data: {id, parentid, data1, ..., dataN}

I want to be able to "zoom in" on the data and produce a report which summarizes the data found below the current branch.
That is, when standing in the root, I want to have the totals of all the data. When I have traveled down a certain branch of the tree, I want to only have the summation of the data found only for that node and its child nodes.

How do I write such a query in SQL?

Thanks in advance!

/John

答:
Since sqlite does not support CONNECT BY, you will not be able to perform this calculation in a single query unless you use nested sets or materialized paths for your data.

Alternatively, do it "the hard way" and traverse your tree recursively, one query for each child node starting at the parent-of-interest.

Also see:

Managing Hierarchical Data in MySQL

Recursive Hierarchies: The Relational Taboo!

OwnerDisplayName: John Lane

ContentLicense: CC BY-SA 2.5

Title: A query to summarize data in sub-tree?

OwnerDisplayName: Vlad Romascanu


问:
Maintaining medium-sized to large JS-heavy web apps
What's the best way to deal with lots of JS in a web front end? Google's Closure compiler can compile and minify JS, which is good for production -- but annoying to have to recompile every time I make a change, and annoying to debug.

What's the best way to be able to organise my JS into many files?

答:
In regards to the 'annoying to debug' part of javascript compression, I've got two things happening in my code, only when the project is in debug I'll serve out the non-compressed files, this way I don't have to re-build the javascript compression project after any change to the files. Additionally, if you're using IE (and like it?), IE9 has a 'pretty-print' feature for javascript debugging, which should uncompress (obviously won't fix obfuscation though).

An MSBuild task in visual studio combined with the YUI Compressor for .NET can do javascript/CSS compression and minification for you. I have a 'static' project, where my javascript, CSS, and images sit, so when I modify my javascript/CSS I build this project and it uses YUI compressor to combine and minify my files. This way I can can separate my javascript and css files, but serve them out together without having to use a manual tool to compress them.

In the Project properties, under the Build Events, I put this in the "Post-build event command line":

```<code>/p:SourceLocation="$(ProjectDir)"
$(MSBuildBinPath)\msbuild.exe "$(ProjectDir)MSBuild\MSBuild.xml"
</code>```

A sample MSBuild.xml file: (mine has 3 Compressor Tasks so that I can get specific groups of files)

```<code><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
  <UsingTask
      TaskName="CompressorTask"
      AssemblyFile="Yahoo.Yui.Compressor.dll" />
  <Target Name="MyTaskTarget">
    <ItemGroup>
      <CssFiles Include="$(SourceLocation)..\css\Style.css"/>
      <CssFiles Include="$(SourceLocation)..\css\StylePrint.css" />
      <JavaScriptFiles Include="$(SourceLocation)..\scripts\general\*.js" />
    </ItemGroup>
    <CompressorTask
        CssFiles="@(CssFiles)"
        DeleteCssFiles="false"
        CssOutputFile="$(SourceLocation)..\css\Style.min.css"
        CssCompressionType="YuiStockCompression"
        JavaScriptFiles="@(JavaScriptFiles)"
        ObfuscateJavaScript="True"
        PreserveAllSemicolons="False"
        DisableOptimizations="Nope"
        EncodingType="Default"
        DeleteJavaScriptFiles="false"
        LineBreakPosition="-1"
        JavaScriptOutputFile="$(SourceLocation)..\scripts\general.min.js"
        LoggingType="ALittleBit"
        ThreadCulture="en-us"
        IsEvalIgnored="false"
            />
  </Target>
</Project>
</code>```

Here is another guide to do compression/minification as MSBuild task

Hope that helps

Body:
In regards to the 'annoying to debug' part of javascript compression, I've got two things happening in my code, only when the project is in debug I'll serve out the non-compressed files, this way I don't have to re-build the javascript compression project after any change to the files. Additionally, if you're using IE (and like it?), IE9 has a 'pretty-print' feature for javascript debugging, which should uncompress (obviously won't fix obfuscation though).

An MSBuild task in visual studio combined with the YUI Compressor for .NET can do javascript/CSS compression and minification for you. I have a 'static' project, where my javascript, CSS, and images sit, so when I modify my javascript/CSS I build this project and it uses YUI compressor to combine and minify my files. This way I can can separate my javascript and css files, but serve them out together without having to use a manual tool to compress them.

In the Project properties, under the Build Events, I put this in the "Post-build event command line":

/p:SourceLocation="$(ProjectDir)"
$(MSBuildBinPath)\msbuild.exe "$(ProjectDir)MSBuild\MSBuild.xml"

A sample MSBuild.xml file: (mine has 3 Compressor Tasks so that I can get specific groups of files)

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
  <UsingTask
      TaskName="CompressorTask"
      AssemblyFile="Yahoo.Yui.Compressor.dll" />
  <Target Name="MyTaskTarget">
    <ItemGroup>
      <CssFiles Include="$(SourceLocation)..\css\Style.css"/>
      <CssFiles Include="$(SourceLocation)..\css\StylePrint.css" />
      <JavaScriptFiles Include="$(SourceLocation)..\scripts\general\*.js" />
    </ItemGroup>
    <CompressorTask
        CssFiles="@(CssFiles)"
        DeleteCssFiles="false"
        CssOutputFile="$(SourceLocation)..\css\Style.min.css"
        CssCompressionType="YuiStockCompression"
        JavaScriptFiles="@(JavaScriptFiles)"
        ObfuscateJavaScript="True"
        PreserveAllSemicolons="False"
        DisableOptimizations="Nope"
        EncodingType="Default"
        DeleteJavaScriptFiles="false"
        LineBreakPosition="-1"
        JavaScriptOutputFile="$(SourceLocation)..\scripts\general.min.js"
        LoggingType="ALittleBit"
        ThreadCulture="en-us"
        IsEvalIgnored="false"
            />
  </Target>
</Project>

Here is another guide to do compression/minification as MSBuild task

Hope that helps


问:
When trying to use sshpass command with alias, getting Permission denied response
When I am trying to make a normal sshpass command in my terminal it is working correctly. This is the command I am using:

```<code>sshpass -p 'Rito$pass@20' ssh 'user.name@mysite.com'
</code>```

When I am trying to use the same command by creating an alias, it is responding Permission denied, please try again.

I have created my alias in .profile file. This is how my alias looks:

```<code>alias myalias="sshpass -p 'Rito$pass@20' ssh user.name@mysite.com"
</code>```

Can anyone please explain why I am getting Permission denied error when I am trying to use the alias, and how to resolve it?

=================================================================

Update:

Based on @pynexj comment I ran the command set -x; myalias; set +x and found that the characters post $ are not getting considered in the password. My password was Rito$pass@20 but it was considering only Rito@20, that is all the characters after including the $ is ignored till the @ character.

答:
According to the comment, there's a $ char in the password. So to fix you need to escape the $ char.

For example if the password is pa$$word:

```<code>alias myalias="sshpass -p 'pa\$\$word' ssh user.name@mysite.com"
</code>```

Body:
When I am trying to make a normal sshpass command in my terminal it is working correctly. This is the command I am using:

sshpass -p 'Rito$pass@20' ssh 'user.name@mysite.com'

When I am trying to use the same command by creating an alias, it is responding Permission denied, please try again.

I have created my alias in .profile file. This is how my alias looks:

alias myalias="sshpass -p 'Rito$pass@20' ssh user.name@mysite.com"

Can anyone please explain why I am getting Permission denied error when I am trying to use the alias, and how to resolve it?

=================================================================

Update:

Based on @pynexj comment I ran the command set -x; myalias; set +x and found that the characters post $ are not getting considered in the password. My password was Rito$pass@20 but it was considering only Rito@20, that is all the characters after including the $ is ignored till the @ character.

Body:
According to the comment, there's a $ char in the password. So to fix you need to escape the $ char.

For example if the password is pa$$word:

alias myalias="sshpass -p 'pa\$\$word' ssh user.name@mysite.com"


问:
Segmentation fault with fgets
I am doing a simple program just for opening a file and printing its contents line by line, but I get "Segmentation fault (core dumped)" while compiling with "gcc -o test pruebas.c" (my file is called pruebas.c) and then running the program in the Ubuntu Console from Windows 10, what could be the issue?

This is the code I wrote:

```<code>int main()
{
    char* line = NULL;
    FILE* file = fopen("D:/Documents/Uni/blur.lp", "r");
    while(fgets(line, sizeof(line), file))
    {
        printf("%s", line);
    }
    fclose(file);
    return(0);
</code>```

(the ".lp" extension is the extension of an image format I have to develop for a homework)

答:
Here is a improved version of your program that takes into account above comments.
It's also using preprocessor macros to define line size and file name:</p>

```<code>#include <stdio.h>
#include <stdlib.h>

#define LINE_SIZE 100
#define FILE_NAME "D:/Documents/Uni/blur.lp"

int main(int argc, char **argv)
{

    char line[LINE_SIZE] ;
    FILE *file ;

    file = fopen(FILE_NAME, "r");
    if (file == NULL)
    {
      perror("cannot access " FILE_NAME);
      return 1;
    }

    while(fgets(line, LINE_SIZE, file))
    {
        printf("%s", line);
    }

    fclose(file);
    return(0);

}
</code>```

Title: Segmentation fault with fgets

Body:
I am doing a simple program just for opening a file and printing its contents line by line, but I get "Segmentation fault (core dumped)" while compiling with "gcc -o test pruebas.c" (my file is called pruebas.c) and then running the program in the Ubuntu Console from Windows 10, what could be the issue?

This is the code I wrote:

int main()
{
    char* line = NULL;
    FILE* file = fopen("D:/Documents/Uni/blur.lp", "r");
    while(fgets(line, sizeof(line), file))
    {
        printf("%s", line);
    }
    fclose(file);
    return(0);

(the ".lp" extension is the extension of an image format I have to develop for a homework)

Body:
Here is a improved version of your program that takes into account above comments.
It's also using preprocessor macros to define line size and file name:

#include <stdio.h>
#include <stdlib.h>

#define LINE_SIZE 100
#define FILE_NAME "D:/Documents/Uni/blur.lp"

int main(int argc, char **argv)
{

    char line[LINE_SIZE] ;
    FILE *file ;

    file = fopen(FILE_NAME, "r");
    if (file == NULL)
    {
      perror("cannot access " FILE_NAME);
      return 1;
    }

    while(fgets(line, LINE_SIZE, file))
    {
        printf("%s", line);
    }

    fclose(file);
    return(0);

}


问:
Checkbox update value only works on false to true, not on true to false, React, mongoDB
I use a state as a form to update boolean data in MongoDB.
Only works when the value is updated from false to true, not work from true to false.
Is there somebody who can help me out? Thanks a lot.

Here is my state as a form

```<code>const [user, setUser] = useState({
    name: '',
    email: '',
    password: '',
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false,
  });
</code>```

Here is onChange func

```<code> const onChangeCB = (e) => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };
</code>```

The checkbox

```<code>   <input
        type='checkbox'
        name='cases'
        checked={cases === true}
        onChange={onChangeCB}
      />{' '}
      Case{' '}
      <input
        type='checkbox'
        name='mtrl'
        checked={mtrl === true}
        onChange={onChangeCB}
      />{' '}
      Material{' '}
      <input
        type='checkbox'
        name='cst'
        checked={cst === true}
        onChange={onChangeCB}
      />{' '}
      Cunsumption{' '}
      <input
        type='checkbox'
        name='mp'
        checked={mp === true}
        onChange={onChangeCB}
      />{' '}
      Material Price{' '}
      <input
        type='checkbox'
        name='po'
        checked={po === true}
        onChange={onChangeCB}
      />{' '}
</code>```

答:
You are storing state in object, so in your input, the value of checked should be user.cases (for example)

Working demo

Code snippet

export default function App() {
  const [user, setUser] = useState({
    name: "",
    email: "",
    password: "",
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false
  });
  const onChangeCB = e => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };
  console.log("user", user);
  return (

Hello CodeSandbox

      <input
        type="checkbox"
        name="cases"
        checked={user.cases === true}
        onChange={onChangeCB}
      />{" "}
      Case{" "}
      <input
        type="checkbox"
        name="mtrl"
        checked={user.mtrl === true}
        onChange={onChangeCB}
      />{" "}
      Material{" "}
      <input
        type="checkbox"
        name="cst"
        checked={user.cst === true}
        onChange={onChangeCB}
      />{" "}
      Cunsumption{" "}
      <input
        type="checkbox"
        name="mp"
        checked={user.mp === true}
        onChange={onChangeCB}
      />{" "}
      Material Price{" "}
      <input
        type="checkbox"
        name="po"
        checked={user.po === true}
        onChange={onChangeCB}
      />{" "}

  );
}
```

<p>Note - You can also consider to write the onChange in a simplified way like below:</p>

<pre class="lang-js prettyprint-override"><code>const onChangeCB = (e) => {
  const target = e.target;
  setUser((prev) => ({ ...prev, [target.name]: !prev[target.name] }));
};
</code>```

Body:
I use a state as a form to update boolean data in MongoDB.
Only works when the value is updated from false to true, not work from true to false.
Is there somebody who can help me out? Thanks a lot.

Here is my state as a form

const [user, setUser] = useState({
    name: '',
    email: '',
    password: '',
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false,
  });

Here is onChange func

 const onChangeCB = (e) => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };

The checkbox

   <input
        type='checkbox'
        name='cases'
        checked={cases === true}
        onChange={onChangeCB}
      />{' '}
      Case{' '}
      <input
        type='checkbox'
        name='mtrl'
        checked={mtrl === true}
        onChange={onChangeCB}
      />{' '}
      Material{' '}
      <input
        type='checkbox'
        name='cst'
        checked={cst === true}
        onChange={onChangeCB}
      />{' '}
      Cunsumption{' '}
      <input
        type='checkbox'
        name='mp'
        checked={mp === true}
        onChange={onChangeCB}
      />{' '}
      Material Price{' '}
      <input
        type='checkbox'
        name='po'
        checked={po === true}
        onChange={onChangeCB}
      />{' '}

Body:
You are storing state in object, so in your input, the value of checked should be user.cases (for example)

Working demo

Code snippet

export default function App() {
  const [user, setUser] = useState({
    name: "",
    email: "",
    password: "",
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false
  });
  const onChangeCB = e => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };
  console.log("user", user);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <input
        type="checkbox"
        name="cases"
        checked={user.cases === true}
        onChange={onChangeCB}
      />{" "}
      Case{" "}
      <input
        type="checkbox"
        name="mtrl"
        checked={user.mtrl === true}
        onChange={onChangeCB}
      />{" "}
      Material{" "}
      <input
        type="checkbox"
        name="cst"
        checked={user.cst === true}
        onChange={onChangeCB}
      />{" "}
      Cunsumption{" "}
      <input
        type="checkbox"
        name="mp"
        checked={user.mp === true}
        onChange={onChangeCB}
      />{" "}
      Material Price{" "}
      <input
        type="checkbox"
        name="po"
        checked={user.po === true}
        onChange={onChangeCB}
      />{" "}
    </div>
  );
}

Note - You can also consider to write the onChange in a simplified way like below:

const onChangeCB = (e) => {
  const target = e.target;
  setUser((prev) => ({ ...prev, [target.name]: !prev[target.name] }));
};


问:
Dynamic Endpoint WSO2 API Manager not updating the TO header
Hi I have come across several blogs and forums and I am still unable to achieve the dynamic endpoint url update.My requirement is to update the API endpoint url based on the request parameter value. Hence I am trying to use Dynamic Endpoint feature in WSO2 Api Manager 2.6.0. I have uploaded the in flow sequence with the below code. But I still get the error.

In flow Code:

```<code><sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--dynamicAPI_v1.0" trace ="enable">
   <property name="REST_URL_POSTFIX" scope="axis2" action="remove"/>
   <log level="full">
    <property name="headerTo" value="http://actualurl/tobe/redirected"/>
    <header name="To" expression="get-property('headerTo')"/>
    <property name="ENDPOINT_ADDRESS" value="http://actualurl/tobe/redirected"/>
 </log>
</sequence>
</code>```

Error:

TID: [-1234] [] [2020-06-02 10:37:33,154]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  To:
  /service/1.0/, MessageID:
  urn:uuid:c341daaf-300e-4cdd-b6cd-ba0a7cb4b49d, Direction: request,
  headerTo = http://actualurl/tobe/redirected, ENDPOINT_ADDRESS =
  http://actualurl/tobe/redirected, Envelope:
  {org.apache.synapse.mediators.builtin.LogMediator} TID: [-1234] []
  [2020-06-02 10:37:33,156] ERROR
  {org.apache.axis2.description.ClientUtils} -  The system cannot infer
  the transport information from the /service/1.0/* URL.
  {org.apache.axis2.description.ClientUtils} TID: [-1234] [] [2020-06-02
  10:37:33,156] ERROR {org.apache.synapse.core.axis2.Axis2Sender} -
  Unexpected error during sending message out
  {org.apache.synapse.core.axis2.Axis2Sender}
  org.apache.axis2.AxisFault: The system cannot infer the transport
  information from the /service/1.0/* URL.  at
  org.apache.axis2.description.ClientUtils.inferOutTransport(ClientUtils.java:86)
    at
  org.apache.synapse.core.axis2.DynamicAxisOperation$DynamicOperationClient.executeImpl(DynamicAxisOperation.java:116)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.apache.synapse.core.axis2.Axis2FlexibleMEPClient.send(Axis2FlexibleMEPClient.java:603)
    at
  org.apache.synapse.core.axis2.Axis2Sender.sendOn(Axis2Sender.java:85)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.send(Axis2SynapseEnvironment.java:547)
    at
  org.apache.synapse.endpoints.AbstractEndpoint.send(AbstractEndpoint.java:384)
    at
  org.apache.synapse.endpoints.DefaultEndpoint.send(DefaultEndpoint.java:77)
    at
  org.apache.synapse.endpoints.IndirectEndpoint.send(IndirectEndpoint.java:55)
    at
  org.apache.synapse.mediators.builtin.SendMediator.mediate(SendMediator.java:123)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.filters.FilterMediator.mediate(FilterMediator.java:169)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at org.apache.synapse.rest.Resource.process(Resource.java:351)  at
  org.apache.synapse.rest.API.process(API.java:399)     at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)*

答:
That is because you have done that inside a log mediator. Can you try like below.</p>

```<code><sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--dynamicAPI_v1.0" trace ="enable">
   <property name="REST_URL_POSTFIX" scope="axis2" action="remove"/>
   <property name="headerTo" value="http://actualurl/tobe/redirected"/>
   <header name="To" expression="get-property('headerTo')"/>
   <log level="full">
      <property name="ENDPOINT_ADDRESS" expression="get-property('headerTo')"/>
   </log>
</sequence>
</code>```

Body:
Hi I have come across several blogs and forums and I am still unable to achieve the dynamic endpoint url update.My requirement is to update the API endpoint url based on the request parameter value. Hence I am trying to use Dynamic Endpoint feature in WSO2 Api Manager 2.6.0. I have uploaded the in flow sequence with the below code. But I still get the error.

In flow Code:

<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--dynamicAPI_v1.0" trace ="enable">
   <property name="REST_URL_POSTFIX" scope="axis2" action="remove"/>
   <log level="full">
    <property name="headerTo" value="http://actualurl/tobe/redirected"/>

    <property name="ENDPOINT_ADDRESS" value="http://actualurl/tobe/redirected"/>
 </log>
</sequence>

Error:

TID: [-1234] [] [2020-06-02 10:37:33,154]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  To:
  /service/1.0/, MessageID:
  urn:uuid:c341daaf-300e-4cdd-b6cd-ba0a7cb4b49d, Direction: request,
  headerTo = http://actualurl/tobe/redirected, ENDPOINT_ADDRESS =
  http://actualurl/tobe/redirected, Envelope:
  {org.apache.synapse.mediators.builtin.LogMediator} TID: [-1234] []
  [2020-06-02 10:37:33,156] ERROR
  {org.apache.axis2.description.ClientUtils} -  The system cannot infer
  the transport information from the /service/1.0/* URL.
  {org.apache.axis2.description.ClientUtils} TID: [-1234] [] [2020-06-02
  10:37:33,156] ERROR {org.apache.synapse.core.axis2.Axis2Sender} -
  Unexpected error during sending message out
  {org.apache.synapse.core.axis2.Axis2Sender}
  org.apache.axis2.AxisFault: The system cannot infer the transport
  information from the /service/1.0/* URL.  at
  org.apache.axis2.description.ClientUtils.inferOutTransport(ClientUtils.java:86)
    at
  org.apache.synapse.core.axis2.DynamicAxisOperation$DynamicOperationClient.executeImpl(DynamicAxisOperation.java:116)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.apache.synapse.core.axis2.Axis2FlexibleMEPClient.send(Axis2FlexibleMEPClient.java:603)
    at
  org.apache.synapse.core.axis2.Axis2Sender.sendOn(Axis2Sender.java:85)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.send(Axis2SynapseEnvironment.java:547)
    at
  org.apache.synapse.endpoints.AbstractEndpoint.send(AbstractEndpoint.java:384)
    at
  org.apache.synapse.endpoints.DefaultEndpoint.send(DefaultEndpoint.java:77)
    at
  org.apache.synapse.endpoints.IndirectEndpoint.send(IndirectEndpoint.java:55)
    at
  org.apache.synapse.mediators.builtin.SendMediator.mediate(SendMediator.java:123)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.filters.FilterMediator.mediate(FilterMediator.java:169)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at org.apache.synapse.rest.Resource.process(Resource.java:351)  at
  org.apache.synapse.rest.API.process(API.java:399)     at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)*

Body:
That is because you have done that inside a log mediator. Can you try like below.

<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--dynamicAPI_v1.0" trace ="enable">
   <property name="REST_URL_POSTFIX" scope="axis2" action="remove"/>
   <property name="headerTo" value="http://actualurl/tobe/redirected"/>
   <header name="To" expression="get-property('headerTo')"/>
   <log level="full">
      <property name="ENDPOINT_ADDRESS" expression="get-property('headerTo')"/>
   </log>
</sequence>


问:
Is there a way to have a conditional requirements.txt file for my Python application based on platform?
I have a python application that I wrote to be compatible with both, Linux and Windows platforms. However there is one problem... One of the python packages I need for Windows is not compatible with Linux. Fortunately there is another package that provides the same functionality on Linux. All other dependencies are compatible in both platforms.

I know I could have 2 separate requirement files to address both platform dependencies separately. Something like win_requirements.txt and linux_requirements.txt, however this approach doesn't feel like the best way to do it.

I wonder if there is a way I can have only one requirements.txt file so any user can use pip install -r requirements.txt to install all the dependencies regardless of what platform they are?

Maybe something like??:

```<code>SOAPpy>=0.12.22
pycrypto>=2.6.1
suds>=0.4
Python-ldap>=2.4.19
paramiko>=1.15.2
nose>=1.3.4
selenium>=2.44.0
bottle>=0.12.8
CherryPy>=3.6.0
pika>=0.9.14
if platform.system() == 'Linux':
    wmi-client-wrapper>=0.0.12
else if platform.system() == 'Windows':
    WMI>=1.4.9
</code>```

答:
You can add additional requirements to any package after a semicolon. You may limit any package with multi-condition by and, or. more conditions: https://www.python.org/dev/peps/pep-0508/#environment-markers

examples:

```<code>futures>=3.0.5; python_version < '3.0'
futures>=3.0.5; python_version == '2.6' or python_version=='2.7'
futures>3 ; python_version >= "3.6" and sys_platform == "linux"
futures>3.3 ; python_version >= "3.6" and sys_platform == "darwin"
</code>```

Body:
I have a python application that I wrote to be compatible with both, Linux and Windows platforms. However there is one problem... One of the python packages I need for Windows is not compatible with Linux. Fortunately there is another package that provides the same functionality on Linux. All other dependencies are compatible in both platforms.

I know I could have 2 separate requirement files to address both platform dependencies separately. Something like win_requirements.txt and linux_requirements.txt, however this approach doesn't feel like the best way to do it.

I wonder if there is a way I can have only one requirements.txt file so any user can use pip install -r requirements.txt to install all the dependencies regardless of what platform they are?

Maybe something like??:

SOAPpy>=0.12.22
pycrypto>=2.6.1
suds>=0.4
Python-ldap>=2.4.19
paramiko>=1.15.2
nose>=1.3.4
selenium>=2.44.0
bottle>=0.12.8
CherryPy>=3.6.0
pika>=0.9.14
if platform.system() == 'Linux':
    wmi-client-wrapper>=0.0.12
else if platform.system() == 'Windows':
    WMI>=1.4.9

Body:
You can add additional requirements to any package after a semicolon. You may limit any package with multi-condition by and, or. more conditions: https://www.python.org/dev/peps/pep-0508/#environment-markers

examples:

futures>=3.0.5; python_version < '3.0'
futures>=3.0.5; python_version == '2.6' or python_version=='2.7'
futures>3 ; python_version >= "3.6" and sys_platform == "linux"
futures>3.3 ; python_version >= "3.6" and sys_platform == "darwin"


问:
Arrays.asList(array) in java add unwanted spaces between comma separated string?
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

```<code>String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
</code>```

After converting and removing item it prints

```<code>[467, 470, 464]
</code>```

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

```<code>if (idList.toString().contains(userId)) {
      idList.remove(userId);
}
</code>```

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

```<code>List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);
</code>```

or

```<code>String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);
</code>```

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

答:
This worked, by combining @matt answer's

```<code>List<String> idList = new LinkedList<>();
    idList.add("1");
    idList.add("          2");
    String userId = "2";
    List<String> removeLeadingWhiteSpacesList = new ArrayList<>();
    System.out.println("idList=>"+idList);
    for (String temp : idList) {
        removeLeadingWhiteSpacesList.add(temp.trim());
    }
    if (removeLeadingWhiteSpacesList.contains(userId)) {
        removeLeadingWhiteSpacesList.remove(userId);
        System.out.println("removeLeadingWhiteSpacesList=>"+removeLeadingWhiteSpacesList);
    }
</code>```

It outputs

```<code>idList=>[1,           2]
removeLeadingWhiteSpacesList=>[1]
</code>```

Body:
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));

After converting and removing item it prints

[467, 470, 464]

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

if (idList.toString().contains(userId)) {
      idList.remove(userId);
}

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);

or

String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

Body:
This worked, by combining @matt answer's

List<String> idList = new LinkedList<>();
    idList.add("1");
    idList.add("          2");
    String userId = "2";
    List<String> removeLeadingWhiteSpacesList = new ArrayList<>();
    System.out.println("idList=>"+idList);
    for (String temp : idList) {
        removeLeadingWhiteSpacesList.add(temp.trim());
    }
    if (removeLeadingWhiteSpacesList.contains(userId)) {
        removeLeadingWhiteSpacesList.remove(userId);
        System.out.println("removeLeadingWhiteSpacesList=>"+removeLeadingWhiteSpacesList);
    }

It outputs

idList=>[1,           2]
removeLeadingWhiteSpacesList=>[1]


问:
Matlab substitution within matrices not working as intended
Where does the following matlab code go wrong?

```<code>C=sym('a',[2,1]);
A=sym('aa',2);

A(1,1)=C(1)-10*C(2)*C(2);
A(2,2)=C(2);

subs(A(1,1),C(1),solve(trace(A)==1,C(1)));

disp(A);
</code>```

As I understand it, the diagonal elements of A are set to functions of a1 and a2. Then, in the expression at position A(1,1), substitute for C(1) (which is a1), the solution to trace(A)==1 for the variable C(1). But when you display the matrix A, it seems unchanged.

What is the error? Why is subs not working as intended? The above is the smallest non-working example of large code.

答:
As I understand you try to replace the element at A(1,1) with the result from solving the equation. In this case, you should do something like that:

```<code>C = sym('a',[2,1]);
A = sym('aa',2);
A(1,1) = C(1);
A(2,2) = C(2);
A(1,1) = subs(C(1),solve(trace(A) == 1, C(1)));
disp(A);
</code>```

This will display the following:

```<code>[ 1 - a2, aa1_2]
[  aa2_1,    a2]
</code>```

Body:
Where does the following matlab code go wrong?

C=sym('a',[2,1]);
A=sym('aa',2);

A(1,1)=C(1)-10*C(2)*C(2);
A(2,2)=C(2);

subs(A(1,1),C(1),solve(trace(A)==1,C(1)));

disp(A);

As I understand it, the diagonal elements of A are set to functions of a1 and a2. Then, in the expression at position A(1,1), substitute for C(1) (which is a1), the solution to trace(A)==1 for the variable C(1). But when you display the matrix A, it seems unchanged.

What is the error? Why is subs not working as intended? The above is the smallest non-working example of large code.

Body:
As I understand you try to replace the element at A(1,1) with the result from solving the equation. In this case, you should do something like that:

C = sym('a',[2,1]);
A = sym('aa',2);
A(1,1) = C(1);
A(2,2) = C(2);
A(1,1) = subs(C(1),solve(trace(A) == 1, C(1)));
disp(A);

This will display the following:

[ 1 - a2, aa1_2]
[  aa2_1,    a2]


问:
how Grouping JSON objects in .dmc file?
I have this sample of JSON :

```<code>{
  "sending": {
    "field": [
      {
        "email": "Sample String",
        "id": 1234,
        "name": "Sample String"
      }, {
        "email": "Sample String",
        "id": 1234,
        "name": "Sample String"
      },{
        "email": "Sample String",
        "id": 1111,
        "name": "Sample String"
      }
    ]
  }
}
</code>```

I want to converted JSON to be grouping by id like this:

```<code>{
    "sending": {
        "field": [
            {
                "1234": [
                    {
                        "name": "Sample String",
                        "email": "Sample String"
                    },{
                        "name": "Sample String",
                        "email": "Sample String"
                    }

                ]
            },
            {
                "1111": [
                    {
                        "name": "Sample String",
                        "email": "Sample String"
                    }
                ]
            }
        ]
    }
}
</code>```

I wrote this code in .dmc file but it does not work as I want :

```<code>   map_S_root_S_root = function(){
    var outputroot={};

    var a = 0;
    outputroot =  {};
    outputroot.sending =  {};
    outputroot.sending.field =  [];

    for(i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491 in inputroot.sending.field){
    outputroot.sending.field[a] =  {};
    id = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id;
    outputroot.sending.field[a].id =  [];

    var c =0;
    for(i in outputroot.sending.field[c].id){
    if (inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id === outputroot.sending.field[c].id){
      outputroot.sending.field[c].id[c] += inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
    }
    c++
    }
    outputroot.sending.field[a].id[a] =  {};
    outputroot.sending.field[a].id[a].name = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
    outputroot.sending.field[a].id[a].email = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].email;
        a++;
        }
        return outputroot;

    };
</code>```

I use WSO2 data mapper mediator and write the code in .dmc file (data mapper configuration file ) in integration studio , could anyone help? Thanks

答:
You can reduce it.

var array={ "sending": { "field": [ { "email": "Sample String", "id": 1234, "name": "Sample String" }, { "email": "Sample String", "id": 1234, "name": "Sample String" },{ "email": "Sample String", "id": 1111, "name": "Sample String" } ] }};

array.sending.field = array.sending.field.reduce((acc,{id, ...rest})=>{
   acc[id] =acc[id] || [];
   acc[id].push(rest);
   return acc;
},{});

console.log(array);```

Title: how Grouping JSON objects in .dmc file?

Body:
I have this sample of JSON :

{
  "sending": {
    "field": [
      {
        "email": "Sample String",
        "id": 1234,
        "name": "Sample String"
      }, {
        "email": "Sample String",
        "id": 1234,
        "name": "Sample String"
      },{
        "email": "Sample String",
        "id": 1111,
        "name": "Sample String"
      }
    ]
  }
}

I want to converted JSON to be grouping by id like this:

{
    "sending": {
        "field": [
            {
                "1234": [
                    {
                        "name": "Sample String",
                        "email": "Sample String"
                    },{
                        "name": "Sample String",
                        "email": "Sample String"
                    }

                ]
            },
            {
                "1111": [
                    {
                        "name": "Sample String",
                        "email": "Sample String"
                    }
                ]
            }
        ]
    }
}

I wrote this code in .dmc file but it does not work as I want :

   map_S_root_S_root = function(){
    var outputroot={};

    var a = 0;
    outputroot =  {};
    outputroot.sending =  {};
    outputroot.sending.field =  [];

    for(i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491 in inputroot.sending.field){
    outputroot.sending.field[a] =  {};
    id = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id;
    outputroot.sending.field[a].id =  [];

    var c =0;
    for(i in outputroot.sending.field[c].id){
    if (inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id === outputroot.sending.field[c].id){
      outputroot.sending.field[c].id[c] += inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
    }
    c++
    }
    outputroot.sending.field[a].id[a] =  {};
    outputroot.sending.field[a].id[a].name = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
    outputroot.sending.field[a].id[a].email = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].email;
        a++;
        }
        return outputroot;

    };

I use WSO2 data mapper mediator and write the code in .dmc file (data mapper configuration file ) in integration studio , could anyone help? Thanks


问:
Python how to parse output of Amazon RDS Data Service
I'm struggling to parse output of ExecuteStatement action using Amazon RDS Data service https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_ExecuteStatement.html

Documentation is very poor and I can't find any meaningful examples.

I'm using Aurora MySql DB

Output is returned like this. This example is 2 rows of data returned by SELECT statement, I've replaced actual data with word "data"

```<code> {'ResponseMetadata': {'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'content-type': 'application/json', 'content-length': '809', 'date': 'Tue, 02 Jun 2020 05:39:22 GMT'}, 'RetryAttempts': 0}, 'numberOfRecordsUpdated': 0, 'records': [[{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}], [{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}]]}
</code>```

I need to extract actually only this data fields, so I can use them for INSERT statement in another table.

As per documentation original response is dictionary data type, so I get 3 keys here 'ResponseMetadata', 'numberOfRecordsUpdated' and 'records'.
As per documentation 'records' is Type: Array of arrays of Field objects and here is where I stuck. How I can extract Field objects from array of arrays inside dictionary?

答:
There are many ways, but the most basic nested for-loop in python could suffice:

```<code>data_values = []

for record in result['records']:
    print()
    row_data = []
    for data_dict in record:
        #print(data_dict)
        for data_type, data_value in data_dict.items():
            print(data_type, data_value)
            row_data.append(data_value)

    data_values.append(row_data)

print(data_values)

</code>```

The code can for a good basis for modifications to suit your needs. It produces the following:

```<code>stringValue data
longValue data
stringValue data
stringValue data
stringValue
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data

stringValue data
longValue data
stringValue data
stringValue data
stringValue
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
</code>```

And data_values:

```<code>[['data', 'data', 'data', 'data', '', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data'], ['data', 'data', 'data', 'data', '', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data']]
</code>```

Body:
I'm struggling to parse output of ExecuteStatement action using Amazon RDS Data service https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_ExecuteStatement.html

Documentation is very poor and I can't find any meaningful examples.

I'm using Aurora MySql DB

Output is returned like this. This example is 2 rows of data returned by SELECT statement, I've replaced actual data with word "data"

 {'ResponseMetadata': {'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'content-type': 'application/json', 'content-length': '809', 'date': 'Tue, 02 Jun 2020 05:39:22 GMT'}, 'RetryAttempts': 0}, 'numberOfRecordsUpdated': 0, 'records': [[{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}], [{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}]]}

I need to extract actually only this data fields, so I can use them for INSERT statement in another table.

As per documentation original response is dictionary data type, so I get 3 keys here 'ResponseMetadata', 'numberOfRecordsUpdated' and 'records'.
As per documentation 'records' is Type: Array of arrays of Field objects and here is where I stuck. How I can extract Field objects from array of arrays inside dictionary?

Body:
There are many ways, but the most basic nested for-loop in python could suffice:

data_values = []

for record in result['records']:
    print()
    row_data = []
    for data_dict in record:
        #print(data_dict)
        for data_type, data_value in data_dict.items():
            print(data_type, data_value)
            row_data.append(data_value)

    data_values.append(row_data)

print(data_values)

The code can for a good basis for modifications to suit your needs. It produces the following:

stringValue data
longValue data
stringValue data
stringValue data
stringValue
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data

stringValue data
longValue data
stringValue data
stringValue data
stringValue
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data
stringValue data

And data_values:

[['data', 'data', 'data', 'data', '', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data'], ['data', 'data', 'data', 'data', '', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data']]


答: The best way to change a boolean value is change to the opposite. It´s a toggle function. If you have a boolean state.. you should have a onChange function using ! operator. setState : !state</p>

Title: Checkbox update value only works on false to true, not on true to false, React, mongoDB


问:
iOS13 insertObject:atIndex: object cannot be nil - crash / error
I have an app that worked fine until iOS was upgraded to 13. and it now crashes. The app looks up country codes from an array and then displays the relevent description.

In iOS13 we get an '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil' crash, when we hit that view

The issue appears to relate to be how NSString stringWithFormat:@"%@-%@" extracts the data.

For example I can replace @"%@-%@" with an option like @"da-DK" - and the app performs as expected, pulling up the "Danish (Denmark) " description, and doesn't crash.

The code is below - anyone have an idea what might have changed in iOS13? Thanks.

```<code>+ (NSString *) getTTSDescForDisplay:(NSString *) voiceLanguage {

    NSString *normalizedVoiceLanguage;
    NSArray *array = [voiceLanguage componentsSeparatedByString:@"-"];
    if ([array count] != 2) {
        return nil;
    } else {
        NSString *first = array[0];
        NSString *second = array[1];
        normalizedVoiceLanguage = [NSString stringWithFormat:@"%@-%@",first.lowercaseString,second.uppercaseString];
    }

    NSDictionary *dict = @{
                           @"ar-SA"       :@"Arabic (Saudi Arabia) ",
                           @"cs-CZ"       :@"Czech (Czech Republic) ",
                           @"da-DK"       :@"Danish (Denmark) "
                           };

    NSString *str = [dict objectForKey:normalizedVoiceLanguage];
    return str;
}
</code>```

答:
OK figured it after breakpointing extensively. In the list above I was missing one of the (new? iOS13?) language codes.

I added it...

```<code>@"en-IN"       :@"English (India) ",
</code>```

and this fixed the issue.

Body:
I have an app that worked fine until iOS was upgraded to 13. and it now crashes. The app looks up country codes from an array and then displays the relevent description.

In iOS13 we get an '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil' crash, when we hit that view

The issue appears to relate to be how NSString stringWithFormat:@"%@-%@" extracts the data.

For example I can replace @"%@-%@" with an option like @"da-DK" - and the app performs as expected, pulling up the "Danish (Denmark) " description, and doesn't crash.

The code is below - anyone have an idea what might have changed in iOS13? Thanks.

+ (NSString *) getTTSDescForDisplay:(NSString *) voiceLanguage {

    NSString *normalizedVoiceLanguage;
    NSArray *array = [voiceLanguage componentsSeparatedByString:@"-"];
    if ([array count] != 2) {
        return nil;
    } else {
        NSString *first = array[0];
        NSString *second = array[1];
        normalizedVoiceLanguage = [NSString stringWithFormat:@"%@-%@",first.lowercaseString,second.uppercaseString];
    }

    NSDictionary *dict = @{
                           @"ar-SA"       :@"Arabic (Saudi Arabia) ",
                           @"cs-CZ"       :@"Czech (Czech Republic) ",
                           @"da-DK"       :@"Danish (Denmark) "
                           };

    NSString *str = [dict objectForKey:normalizedVoiceLanguage];
    return str;
}

Body:
OK figured it after breakpointing extensively. In the list above I was missing one of the (new? iOS13?) language codes.

I added it...

@"en-IN"       :@"English (India) ",

and this fixed the issue.


问:
Maven plugins are not downloading or resolving when I create a new project
I am very new to maven was about to start learning spring with maven but when I created my first project with maven in eclipse this error occurred and I think maven plugins are not getting downloaded. I have tried several solutions from stackoverflow but nothing worked.

Console Window is like :-

```<code>[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.097 s
[INFO] Finished at: 2020-06-01T21:17:39-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException
</code>```

Error window is like this:-

Please see this screenshot for exact information of errors.

Screenshot attached

POM.xml file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.anuragr07</groupId>
  <artifactId>springpractice</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>
</code>```

Solutions tried so far:-

Installing maven using help > install a new software option

Tried mvn install using cmd

Tried uncommenting proxy tag in setting.xml file

Tried 'https' instead of 'http' in proxy tag in settings.xml file

Tried reinstalling eclipse

and maybe more..

After mvn package

```<code>E:\Workspace\springpractice>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.anuragr07:springpractice >--------------------
[INFO] Building springpractice 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom

**Downloaded all the plugins**

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.831 s
[INFO] Finished at: 2020-06-01T23:52:35-07:00
[INFO] ------------------------------------------------------------------------

</code>```

I am really frustrated and searching for solutions from past 24 hours. Please help me resolve this.

Thanks!

答:
The given ERORR is the cause of the default goal.

ERROR No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format : or :[:]:.

Resolution:

Specify any goal in your run configuration for maven build like clear, compile, install, package.

    install
...

Could you please refer to the given steps?

Right click on your project.

Click 'Run as' and select 'Maven Build'

Edit Configuration window will open.

write any goal but your problem specific write 'package'
in Goal text box.

Click on 'Run'

Body:
I am very new to maven was about to start learning spring with maven but when I created my first project with maven in eclipse this error occurred and I think maven plugins are not getting downloaded. I have tried several solutions from stackoverflow but nothing worked.

Console Window is like :-

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.097 s
[INFO] Finished at: 2020-06-01T21:17:39-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException

Error window is like this:-

Please see this screenshot for exact information of errors.

Screenshot attached

POM.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.anuragr07</groupId>
  <artifactId>springpractice</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</project>

Solutions tried so far:-

Installing maven using help > install a new software option

Tried mvn install using cmd

Tried uncommenting proxy tag in setting.xml file

Tried 'https' instead of 'http' in proxy tag in settings.xml file

Tried reinstalling eclipse

and maybe more..

After mvn package

E:\Workspace\springpractice>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.anuragr07:springpractice >--------------------
[INFO] Building springpractice 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom

**Downloaded all the plugins**

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.831 s
[INFO] Finished at: 2020-06-01T23:52:35-07:00
[INFO] ------------------------------------------------------------------------

I am really frustrated and searching for solutions from past 24 hours. Please help me resolve this.

Thanks!


问:
go debugger - Command failed: command not available
I'm running the golang debugger dlv and I'm trying to run go code while in the debugger. however, I keep getting an error. how do you run this from within the go debugger?</p>

```<code>if 1 == 1 {
  fmt.Println("hello world")
}
Command failed: command not available
</code>```

答: You can evaluate an expression in Delve now - see https://github.com/go-delve/delve/issues/251.  You can't execute more complex code like a statement.</p>

Body:
I'm running the golang debugger dlv and I'm trying to run go code while in the debugger. however, I keep getting an error. how do you run this from within the go debugger?

if 1 == 1 {
  fmt.Println("hello world")
}
Command failed: command not available


问:
CSS How to print a table with background color (without Print settings changes)
The aim is to print table with colored td-s.
I need a way correct for all types of browsers.

Is there any way?

答: a particularly ugly solution is to place position a .gif (or any form of vector graphic so the size can be changed) image  in the table cell with height and width 100% then a negative z-index property. </p>


问:
How to run files in the working directory through Git Bash and Python
I'm having some issues running Python 3, which I installed with Anaconda, through Git Bash. I'm able to access the interactive environment by entering python but whenever I enter:

```<code>python webscraper.py
</code>```

I get this:

```<code>C:/Users/[My username]/anaconda3/python.exe: can't open file 'webscraper.py': [Errno 2]
No such file or directory
</code>```

The Python file is in the same directory I'm currently working in when I'm getting these errors. The path to my version of Python through Anaconda also looks like it's correct. I was previously able to test scripts in Bash but had to reinstall it to solve some other issue.

答:
First, check if you are using the right python:

```<code>which python # in your git bash session
</code>```

Then test it with the full absolute pathname of the file, as described here:

```<code>python /full/path/to/webscrapper.py
</code>```

Body:
I'm having some issues running Python 3, which I installed with Anaconda, through Git Bash. I'm able to access the interactive environment by entering python but whenever I enter:

python webscraper.py

I get this:

C:/Users/[My username]/anaconda3/python.exe: can't open file 'webscraper.py': [Errno 2]
No such file or directory

The Python file is in the same directory I'm currently working in when I'm getting these errors. The path to my version of Python through Anaconda also looks like it's correct. I was previously able to test scripts in Bash but had to reinstall it to solve some other issue.

Body:
First, check if you are using the right python:

which python # in your git bash session

Then test it with the full absolute pathname of the file, as described here:

python /full/path/to/webscrapper.py


问:
Missing ListView Control in RIDER
I am fairly new to C# and Rider. I was creating a Windows Forms Application in .NET Framework 4.8.

I checked the Designer Toolbox and saw that ListView is not available as one of the options.

Any solution for this or would I have to be forced to move to Visual Studio? (I came from IntelliJ so Rider was more familiar for me)

答:
This is a known issue and is in progress. https://youtrack.jetbrains.com/issue/RIDER-30456/.
So far, you can add required assembly through "Toolbox manager"</p>

Title: Missing ListView Control in RIDER


问:
Migrating Workflow Foundation to Visual Studio 2019
I am in the process of migrating to VS 2019 but have an issue when opening a solution that contains a Workflow Foundation project.

On loading a Visual Studio 2019 the project will not load and just states; "needs migration" next to the project name in Solution Explorer.

I have followed the steps detailed in this article [Here] but to no avail.

答:
I've had the same problem and the solution was to install Office/Sharepoint development workload from the Visual Studio Installer.
If there will be still some issues, you may try to open solution in Visual Studio 2017 (Some parts of Workflow are no longer supported in VS 2019 )  </p>


问:
string.split is not working for some reason
I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.

When I run this code, I get undefined. I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.

Can you please take a look and help figure me out what am I doing wrong?

Here is my code:

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = [names.split(" ")];
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] == "Michael") {
      var Michael = newN[i++];
    }
    return Michael;
  }
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```

答:
return words after Michael

```<code>function getMichaelLastName(inputText) {
  let newArr = []
  var names = inputText;
  var newN = names.split(" ");
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = [...newArr, newN[i + 1]]
    }
  }
  return newArr
}
</code>```

if you want return last name:

```<code>function getMichaelLastName(inputText) {
  let newArr = ''
  var names = inputText;
  var newN = names.split(" ");
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = newN[i + 1]
    }
  }
  return newArr
}
</code>```

Body:
return words after Michael

function getMichaelLastName(inputText) {
  let newArr = []
  var names = inputText;
  var newN = names.split(" ");
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = [...newArr, newN[i + 1]]
    }
  }
  return newArr
}

if you want return last name:

function getMichaelLastName(inputText) {
  let newArr = ''
  var names = inputText;
  var newN = names.split(" ");
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = newN[i + 1]
    }
  }
  return newArr
}


问:
Does implementing the MVP Pattern on webforms app make it easier to transition to MVC?
Since the MVP pattern allows more testability and some reuse in webforms apps, i thought it would be a good first step to moving to MVC for legacy(webforms with code in codebehind, no pattern).  As I refresh myself with MVP internals, it doesn't seem so.  Anyone have experience using this approach. Would it be better to just add MVC to your project and start porting pages/views?

Note: I have webform apps that inject controls dynamically, keepin the amount of pages down to 4 or less (single page webforms app).

答:
It would be better to directly port to MVC, IMHO, for several reasons:

It's going to take a lot of extra time to learn and plan the MVP portion, then migrate to MVC.  If you just directly migrate, there's less learning/planning time involved.

ASP.NET MVC is a specialized framework, and most MVP implementations use web forms - thus it's a port closer to using web forms than views.

We use MVP on a project at work.  To migrate my project it would be easier to do, but I would just rather shoot for the final product rather than use a migration step...  it will be less time overall and a lower cost that way, IMHO.

HTH.


问:
Colored background with png image
I want to create a square white box with png image in it. I want png to follow background while the colour of box doesn't affect it.

Here is the sample of the output that I want:

As for now, the white background color couldn't work after I added background colour on div for image. I want the transparent space of png follow body background color.

jsfiddle

I've attached snippet too. Can someone help me to look into it? Thanks in advance!

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  border: 1px solid black;
  background-color:white;
}

.title {
  margin-top: auto;
  width: auto;
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  animation: gradient 15s ease infinite;
  -webkit-text-fill-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
 <div class="title">
    <img src="https://img.icons8.com/material/24/000000/print--v1.png"/>
  </div>
</div></code>```

答:
Here is the solution:

Step 1: Set position: absolute

Step 2: Set the width of the .title

Step 3: add a transparent color in between other colors in the linear background.

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  background-color:white;
}

.title {
    margin-top: auto;
    position: absolute;
    width: 97vw;
    border: 1px solid black;
    background: linear-gradient(-45deg, #ee7752, #ffffff, #3456ab00, #23a6d5, #23d5ab);
    animation: gradient 15s ease infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
 <div class="title">
    <img src="https://img.icons8.com/material/24/000000/print--v1.png"/>
  </div>
</div></code>```

Title: Colored background with png image

Body:
Here is the solution:

Step 1: Set position: absolute

Step 2: Set the width of the .title

Step 3: add a transparent color in between other colors in the linear background.

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  background-color:white;
}

.title {
    margin-top: auto;
    position: absolute;
    width: 97vw;
    border: 1px solid black;
    background: linear-gradient(-45deg, #ee7752, #ffffff, #3456ab00, #23a6d5, #23d5ab);
    animation: gradient 15s ease infinite;
}

<div class="wrapper">
 <div class="title">
    <img src="https://img.icons8.com/material/24/000000/print--v1.png"/>
  </div>
</div>


问:
Error while counting hashtags using Pyspark
I am working on a twitter dataset. I have the data in JSON format. The structure is:

```<code>root
|-- _id: string (nullable = true)
 |-- created_at: timestamp (nullable = true)
 |-- lang: string (nullable = true)
 |-- place: struct (nullable = true)
 |    |-- bounding_box: struct (nullable = true)
 |    |    |-- coordinates: array (nullable = true)
 |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |    |-- element: double (containsNull = true)
 |    |    |-- type: string (nullable = true)
 |    |-- country_code: string (nullable = true)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- place_type: string (nullable = true)
 |-- retweeted_status: struct (nullable = true)
 |    |-- _id: string (nullable = true)
 |    |-- user: struct (nullable = true)
 |    |    |-- followers_count: long (nullable = true)
 |    |    |-- friends_count: long (nullable = true)
 |    |    |-- id_str: string (nullable = true)
 |    |    |-- lang: string (nullable = true)
 |    |    |-- screen_name: string (nullable = true)
 |    |    |-- statuses_count: long (nullable = true)
 |-- text: string (nullable = true)
 |-- user: struct (nullable = true)
 |    |-- followers_count: long (nullable = true)
 |    |-- friends_count: long (nullable = true)
 |    |-- id_str: string (nullable = true)
 |    |-- lang: string (nullable = true)
 |    |-- screen_name: string (nullable = true)
 |    |-- statuses_count: long (nullable = true)
</code>```

The code I am using for counting hashtag is this:

```<code>non_retweets = tweets.where("retweeted_status IS NULL")
hashtag = non_retweets.select('text').flatMap(lambda x: x.split(" ").filter(lambda x: x.startWith("#"))

hashtag = hashtag.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)

hashtag.collect()
</code>```

The error I am getting is this:

```<code> File "<ipython-input-112-11fd8cbc056d>",line 4
hashtag = hashtag.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)
      ^
SyntaxError: Invalid syntax
</code>```

I am not able to point out what my error is. Please help!

答:
You forgot to add ) after filter. That why it is showing Invalid syntax.

Please check below code.

```<code>hashtag = non_retweets.select('text').flatMap(lambda x: x.split(" ")).filter(lambda x: x.startWith("#"))

</code>```

Body:
I am working on a twitter dataset. I have the data in JSON format. The structure is:

root
|-- _id: string (nullable = true)
 |-- created_at: timestamp (nullable = true)
 |-- lang: string (nullable = true)
 |-- place: struct (nullable = true)
 |    |-- bounding_box: struct (nullable = true)
 |    |    |-- coordinates: array (nullable = true)
 |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |    |-- element: double (containsNull = true)
 |    |    |-- type: string (nullable = true)
 |    |-- country_code: string (nullable = true)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- place_type: string (nullable = true)
 |-- retweeted_status: struct (nullable = true)
 |    |-- _id: string (nullable = true)
 |    |-- user: struct (nullable = true)
 |    |    |-- followers_count: long (nullable = true)
 |    |    |-- friends_count: long (nullable = true)
 |    |    |-- id_str: string (nullable = true)
 |    |    |-- lang: string (nullable = true)
 |    |    |-- screen_name: string (nullable = true)
 |    |    |-- statuses_count: long (nullable = true)
 |-- text: string (nullable = true)
 |-- user: struct (nullable = true)
 |    |-- followers_count: long (nullable = true)
 |    |-- friends_count: long (nullable = true)
 |    |-- id_str: string (nullable = true)
 |    |-- lang: string (nullable = true)
 |    |-- screen_name: string (nullable = true)
 |    |-- statuses_count: long (nullable = true)

The code I am using for counting hashtag is this:

non_retweets = tweets.where("retweeted_status IS NULL")
hashtag = non_retweets.select('text').flatMap(lambda x: x.split(" ").filter(lambda x: x.startWith("#"))

hashtag = hashtag.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)

hashtag.collect()

The error I am getting is this:

 File "<ipython-input-112-11fd8cbc056d>",line 4
hashtag = hashtag.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)
      ^
SyntaxError: Invalid syntax

I am not able to point out what my error is. Please help!

Body:
You forgot to add ) after filter. That why it is showing Invalid syntax.

Please check below code.

hashtag = non_retweets.select('text').flatMap(lambda x: x.split(" ")).filter(lambda x: x.startWith("#"))