问:
How does bidirectional operator work for (g)awk?
I have been looking at the bidirectional operator in awk and been trying to understand it.

https://www.gnu.org/software/gawk/manual/html_node/Two_002dway-I_002fO.html#Two_002dway-I_002fO

So I tried this in .awk file,

```<code>BEGIN {
cmd="tr [a-z] [A-Z]"
print "hi" |& cmd
close(cmd,"to")
cmd |& getline
close(cmd)
}
</code>```

found here, https://books.google.se/books?id=NrZTDwAAQBAJ&pg=PA322&lpg=PA322&dq=bidirectional+pipeline+awk+example&source=bl&ots=awgGmpZBxm&sig=ACfU3U0jxy2GO2qaUb-gCOrP9CmrC3SsYA&hl=sv&sa=X&ved=2ahUKEwijw8i267viAhXq-ioKHRyWDwMQ6AEwC3oECAgQAQ#v=onepage&q=bidirectional%20pipeline%20awk%20example&f=false

This looks quite fine, so I tried to modify it,

```<code>BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
close(cmd,"to")
cmd |& getline
print $0
close(cmd)
}
</code>```

This fails quite good though. I manages to login and get the banner. Then I get the message,

Warning: no access to tty (Bad file descriptor).

Followed by the program terminates. However, the "ls" command is not running. Anyone who know what I have missed?

EDIT

I also tried

```<code>BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
cmd |& getline
print $0
close(cmd)
}
</code>```

without closing the stream in one of the directions. The result is unpredictable. It either hangs or fails the same way. It does at least not work.

Running "ssh server ls /some/file" works fine though, so I suspect it is a awk piping to bash/tcsh issue.

EDIT2

There are a lot of other suggestions here, so I think I need to update my questions. Sometimes it seems as an MVCE may cause more problems that it helps...

Anyway, the idea is to start an ssh session to which I can keep sending new commands until I am done and then the close the ssh session. So the idea was to initiate an ssh shell session and then pipe commands to it and read replies with this operator.

```<code>BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
cmd |& getline
print $0
print "some other command" |& cmd
cmd |& getline
close(cmd)
}
</code>```

Also, there are other options which can be considered, but none which will be easy.

EDIT3

Thinks I will restart this here.

What I want to do is to start an ssh session with the ssh client coming with the standard linux RHEL7 distribution. Then I want to keep the session open while I keep sending commands to it. When I am done I need to terminate the session. From bash it would looks something like this,

```<code>ssh host
command1
command2
exit
</code>```

A requirement is that this is done by pure awk scripting. All other options would just create more problems in the future. Note username being left out. This is currently handled in our environment and doing ssh 10.10.10.10 works perfectly fine.

BR
Patrik

答:
That's not how you execute a remote command with ssh, ssh some_server -t 'command' is.

That's not how you read the output of a co-process with getline, while ( (cmd |& getline line) > 0 ) is.

Try this, no co-process required:

```<code>BEGIN {
    cmd = "ssh some_server \047ls /some/file\047"
    while ( (cmd | getline line) > 0 ) {
        print line
    }
    close(cmd)
}
</code>```

Given that you do want to use co-processes, though, you need the ssh to create some process on your remote machine that subsequent commands can be piped to. Maybe spawn a shell? When I've done in the past hasn't involved awk at all but in shell I used

```<code>coproc ssh_conn { ssh -T ... some_tool_waiting_for_input }
</code>```

to create a remote process and a named pipe to it and afterwards to write to it:

```<code>printf '%s\0' 'command' >&"${ssh_conn[1]}"
</code>```

and to read it's output:

```<code>IFS= read -r -d '' resp <&"${ssh_conn[0]}".
</code>```

So you need to figure out that ssh -T ... some_tool_waiting_for_input as a starting point for doing this from awk (which I think is a bad idea as managing processes is what shells are designed to do, not what awk is designed to do - manipulate text).

In the above case my remote tools read nul-terminated rather than newline-terminated strings so I can send multi-line text to it. Your requirements may be different.

For security my remote command requires the local one to authenticate itself and won't allow connections from anything except my local command, you may want to consider that rather than spawning a remote shell which then anyone can connect to to execute commands on your remote machine.

Btw, try adding -T to your ssh command to get rid of the Warning: no access to tty (Bad file descriptor).

Body:
I have been looking at the bidirectional operator in awk and been trying to understand it.

https://www.gnu.org/software/gawk/manual/html_node/Two_002dway-I_002fO.html#Two_002dway-I_002fO

So I tried this in .awk file,

BEGIN {
cmd="tr [a-z] [A-Z]"
print "hi" |& cmd
close(cmd,"to")
cmd |& getline
close(cmd)
}

found here, https://books.google.se/books?id=NrZTDwAAQBAJ&pg=PA322&lpg=PA322&dq=bidirectional+pipeline+awk+example&source=bl&ots=awgGmpZBxm&sig=ACfU3U0jxy2GO2qaUb-gCOrP9CmrC3SsYA&hl=sv&sa=X&ved=2ahUKEwijw8i267viAhXq-ioKHRyWDwMQ6AEwC3oECAgQAQ#v=onepage&q=bidirectional%20pipeline%20awk%20example&f=false

This looks quite fine, so I tried to modify it,

BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
close(cmd,"to")
cmd |& getline
print $0
close(cmd)
}

This fails quite good though. I manages to login and get the banner. Then I get the message,

Warning: no access to tty (Bad file descriptor).

Followed by the program terminates. However, the "ls" command is not running. Anyone who know what I have missed?

EDIT

I also tried

BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
cmd |& getline
print $0
close(cmd)
}

without closing the stream in one of the directions. The result is unpredictable. It either hangs or fails the same way. It does at least not work.

Running "ssh server ls /some/file" works fine though, so I suspect it is a awk piping to bash/tcsh issue.

EDIT2

There are a lot of other suggestions here, so I think I need to update my questions. Sometimes it seems as an MVCE may cause more problems that it helps...

Anyway, the idea is to start an ssh session to which I can keep sending new commands until I am done and then the close the ssh session. So the idea was to initiate an ssh shell session and then pipe commands to it and read replies with this operator.

BEGIN {
cmd="ssh some_server"
print "ls /some/file" |& cmd
cmd |& getline
print $0
print "some other command" |& cmd
cmd |& getline
close(cmd)
}

Also, there are other options which can be considered, but none which will be easy.

EDIT3

Thinks I will restart this here.

What I want to do is to start an ssh session with the ssh client coming with the standard linux RHEL7 distribution. Then I want to keep the session open while I keep sending commands to it. When I am done I need to terminate the session. From bash it would looks something like this,

ssh host
command1
command2
exit

A requirement is that this is done by pure awk scripting. All other options would just create more problems in the future. Note username being left out. This is currently handled in our environment and doing ssh 10.10.10.10 works perfectly fine.

BR
Patrik

Body:
That's not how you execute a remote command with ssh, ssh some_server -t 'command' is.

That's not how you read the output of a co-process with getline, while ( (cmd |& getline line) > 0 ) is.

Try this, no co-process required:

BEGIN {
    cmd = "ssh some_server \047ls /some/file\047"
    while ( (cmd | getline line) > 0 ) {
        print line
    }
    close(cmd)
}

Given that you do want to use co-processes, though, you need the ssh to create some process on your remote machine that subsequent commands can be piped to. Maybe spawn a shell? When I've done in the past hasn't involved awk at all but in shell I used

coproc ssh_conn { ssh -T ... some_tool_waiting_for_input }

to create a remote process and a named pipe to it and afterwards to write to it:

printf '%s\0' 'command' >&"${ssh_conn[1]}"

and to read it's output:

IFS= read -r -d '' resp <&"${ssh_conn[0]}".

So you need to figure out that ssh -T ... some_tool_waiting_for_input as a starting point for doing this from awk (which I think is a bad idea as managing processes is what shells are designed to do, not what awk is designed to do - manipulate text).

In the above case my remote tools read nul-terminated rather than newline-terminated strings so I can send multi-line text to it. Your requirements may be different.

For security my remote command requires the local one to authenticate itself and won't allow connections from anything except my local command, you may want to consider that rather than spawning a remote shell which then anyone can connect to to execute commands on your remote machine.

Btw, try adding -T to your ssh command to get rid of the Warning: no access to tty (Bad file descriptor).


来源: stackexchange

问:
How to have a calculation over the limits of Int32/64 for the product of an int and a float?
My application has to deal with calculating large numbers. How can I multiply an int and a float and get a product as a BigInteger without overflowing? Specifically, I have to get "BaseCost" x ("multiplier" by the power of "level")

I tested that "new BigInteger(100000000000000000000000)" doesn't work. So I don't think "if(BigInteger > (BigInteger)(Int1 * float1))" will work. It'll probably get overflowed in the "(Int1 * float1)" part.

答:
So this is how I fixed the issue. I used BigDecimal from JcBernack in GitHub and this is the following code.

```<code>private BigInteger Example
{
    get
    {
        return (BigInteger)(new BigDecimal(Int1) * Float2);
    }
}
</code>```

I used a BigDecimal class as I couldn't multiply BigInteger with a float. Also, before using the class I made sure to add a BigInteger caster (from uhDreamer's comment there).

```<code>public static explicit operator BigInteger(BigDecimal value)
{
    BigDecimal floored = value.Floor();
    return floored.Mantissa * BigInteger.Pow(10, floored.Exponent);
}
</code>```

And an Int constructor.

```<code>public BigDecimal(int t)
{
    Exponent = 0;
    Mantissa = t;
    Normalize();
    if(AlwaysTruncate)
    {
        Truncate();
    }
}
</code>```

Now, for developers who just need to multiply integers, they can do this Int1(BigInteger) * Int2.

And, of course, don't forget the System.Numerics namespace.

ContentLicense: CC BY-SA 4.0

Body:
So this is how I fixed the issue. I used BigDecimal from JcBernack in GitHub and this is the following code.

private BigInteger Example
{
    get
    {
        return (BigInteger)(new BigDecimal(Int1) * Float2);
    }
}

I used a BigDecimal class as I couldn't multiply BigInteger with a float. Also, before using the class I made sure to add a BigInteger caster (from uhDreamer's comment there).

public static explicit operator BigInteger(BigDecimal value)
{
    BigDecimal floored = value.Floor();
    return floored.Mantissa * BigInteger.Pow(10, floored.Exponent);
}

And an Int constructor.

public BigDecimal(int t)
{
    Exponent = 0;
    Mantissa = t;
    Normalize();
    if(AlwaysTruncate)
    {
        Truncate();
    }
}

Now, for developers who just need to multiply integers, they can do this Int1(BigInteger) * Int2.

And, of course, don't forget the System.Numerics namespace.


问:
Dynamically generating Ge'ez unicodes

Hi. If you look at the image above, you will see a set of very weird-looking characters displayed along with some Latin characters. The weird ones are Eritrean characters. They are the characters we use in my country. So, to go strait to the point, I am hoping to create even the simplest possible bit of software or maybe even a batch file (if possible) to help me make these characters applicable on the web and make PCs understand and display them when being typed. Just like Arabic, Hindu, Chinese... characters are used. I think, since the question of 'creating a language' is often rare or because I may not know the correct term to use, when I searched the internet to find any tutorial or even a freelancer or anything, all I got was... nothing. So, I am hoping, if anyone can give me a step-by-step guide, or even just a clue about how to create this, would be very helpful.

Thanks.

答: @Samaya, by now you probably got the answer you were looking for. But let me drop what I think. Based on your original question, I think you are trying to develop a small software which can be selected as utility(as a feature) and be used to display  Geez alphabets without the need of installing a separate Geez application. For that, I reckon, the utility application should be developed in a way that it could be selected as a feature (language feature) in an operating system (Like Amharic in windows for instance). However, your subsequent comments seem to focus more on displaying Geez characters on a web. As many have suggested, we already have that functionality. But if you still want to develop an application for it, I would suggest you to have unicode (U1260-በ for instance) array and matching transcription array of your choices from a keyboard ( be - በ   for instance). Your application then would use the array of transcription when keyboard key are entered and match them to the unicode to show the right alphabet in Geez. Not sure if I fully understood what you're looking for but I myself with colleagues did a project that included this type of work for the particular application. By the way, do you have to install Geez software to view Tigrigna/Geez transcript based website? If so, check your version of browser.</p>

ContentLicense: CC BY-SA 3.0

Title: Dynamically generating Ge'ez unicodes


问:
Import hierarchichal JSON file into Pandas dataframe
I have looked for solutions to my problem but couldn't find anything that applies. I'm trying to import a high dimension JSON file into a Pandas dataframe.

The structure is something like:

```<code>{   'manufacturing_plant_events':
        {   'data':
            {   'shiftInformation':
                {   'shift1':
                    { 'color': 'red'
                        , 'amount' : 32
                        , 'order' : None
                    },
                    'shift2':
                    { 'color': 'blue'
                        , 'amount' : 44
                        , 'order' : 1
                    },
                    'shift3':
                    { 'color': 'green'
                        , 'amount' : 98
                        , 'order' : 2
                    }
                }
            ...}
        ...}
    }
</code>```

I have tried numerous solutions including:

json.loads()

pd.DataFrame(json)

json_normalize(json)

pd.read_json(json)

and others, I've tried flattening my array and converting it into a dataframe bu that didn't work either. I'm not sure if this is even possible or if the dataframe supports only a few levels of nested.

The flattening I've tried was to just try and create columns in a dataframe that contain the leaf information. Hence, I'm also fine with a dataframe which has the following column names the full path and the value, the actual value stored in the node.

First row in my dataframe:

```<code>(
manufacturing_plant_events.data.shiftInformation.shift1.color
'red'

manufacturing_plant_events.data.shiftInformation.shift1.amount
32

manufacturing_plant_events.data.shiftInformation.shift1.order
None
)
</code>```

and so on.

Any suggestion on how to solve this is highly appreciated.

答:
I have come up with a dataframe by flattening the dict :

import pandas as pd

def flat_dict(dictionary, prefix):
    if type(dictionary) == dict:
        rows = []

        for key, items in dictionary.items():
            rows += flat_dict(items, prefix + [key])

        return rows

    else:
        return [prefix + [dictionary]]

def dict_to_df(dictionary):
    return pd.DataFrame(flat_dict(dictionary, []))
```

Sure you need to import your json as a dict first thanks to json package.

Body:
I have looked for solutions to my problem but couldn't find anything that applies. I'm trying to import a high dimension JSON file into a Pandas dataframe.

The structure is something like:

{   'manufacturing_plant_events':
        {   'data':
            {   'shiftInformation':
                {   'shift1':
                    { 'color': 'red'
                        , 'amount' : 32
                        , 'order' : None
                    },
                    'shift2':
                    { 'color': 'blue'
                        , 'amount' : 44
                        , 'order' : 1
                    },
                    'shift3':
                    { 'color': 'green'
                        , 'amount' : 98
                        , 'order' : 2
                    }
                }
            ...}
        ...}
    }

I have tried numerous solutions including:

json.loads()

pd.DataFrame(json)

json_normalize(json)

pd.read_json(json)

and others, I've tried flattening my array and converting it into a dataframe bu that didn't work either. I'm not sure if this is even possible or if the dataframe supports only a few levels of nested.

The flattening I've tried was to just try and create columns in a dataframe that contain the leaf information. Hence, I'm also fine with a dataframe which has the following column names the full path and the value, the actual value stored in the node.

First row in my dataframe:

(
manufacturing_plant_events.data.shiftInformation.shift1.color
'red'

manufacturing_plant_events.data.shiftInformation.shift1.amount
32

manufacturing_plant_events.data.shiftInformation.shift1.order
None
)

and so on.

Any suggestion on how to solve this is highly appreciated.

Body:
I have come up with a dataframe by flattening the dict :

import pandas as pd

def flat_dict(dictionary, prefix):
    if type(dictionary) == dict:
        rows = []

        for key, items in dictionary.items():
            rows += flat_dict(items, prefix + [key])

        return rows

    else:
        return [prefix + [dictionary]]

def dict_to_df(dictionary):
    return pd.DataFrame(flat_dict(dictionary, []))

Sure you need to import your json as a dict first thanks to json package.


问:
Copy data from one table to another - Ignore duplicates Postgresql
I am using Postgresql db. I have data in two tables. Table A has 10 records and Table B 5 records.

I would like to copy Table A data to Table B but only copy the new entries (5 records) and ignore the duplicates/already existing data

I would like to copy data from Table A to Table B where Table B will have 10 records (5 old records + 5 new records from Table A)

Can you please help me as to how can this be done?

答:
Assuming id is your primary key, and table structures are identical(both table has common columns as number of columns and data type respectively), use not exists :

```<code>insert into TableB
select *
  from TableA a
 where not exists ( select 0 from TableB b where b.id = a.id )
</code>```

Body:
Assuming id is your primary key, and table structures are identical(both table has common columns as number of columns and data type respectively), use not exists :

insert into TableB
select *
  from TableA a
 where not exists ( select 0 from TableB b where b.id = a.id )


问:
"Getting the top 5 sales by year and display the results by Quarter " using MDX
I'm working with a sales cube.

I want to get the top 5 store by year and display their sales by Quarter later on in my report.

I was able to get the top 5 store but by quarter aswell not only year !

```<code>SELECT NON EMPTY { [Measures].[Revenue] } ON COLUMNS,
NON EMPTY { ([DWH REF DATE].[H_CALENDER].[QUARTER NUM].ALLMEMBERS * TOPCOUNT([DWH REF STORE].[H_STORE].[STORE].ALLMEMBERS , 5  ,  [Measures].[Revenue] )) }
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_VALUE, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( -{ [DWH REF STORE].[H_STORE].[TERRITORY].&[N/A].&[N/A] } ) ON COLUMNS FROM ( SELECT ( { [DWH REF DATE].[H_CALENDER].[YEAR NUM].&[2012] } ) ON COLUMNS FROM [SALES CUBE]))
</code>```

What I want exactly to be able to, is to get the top 5 store by year and after get their sales by quarter of the 5 stores.

答:
Welcome to SO, so lets take a look at an example.
I am trying to get the top 5 subproducts by internet sales from adventureworks cube for 2013

```<code>select
[Measures].[Internet Sales Amount]
on columns,
non empty
topcount
(
[Product].[Subcategory].[Subcategory],
5,
[Measures].[Internet Sales Amount]
)
on rows
from
[Adventure Works]
where [Date].[Calendar].[Calendar Year].&[2013]
</code>```

Result

Now Lets try to divide there sales by quater

```<code>select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Quarter of Year].[Calendar Quarter of Year]
on rows
from
(select  topcount([Product].[Subcategory].[Subcategory],5,[Measures].[Internet Sales Amount]) on 0 from [Adventure Works] )
where [Date].[Calendar].[Calendar Year].&[2013]
</code>```

Result

Edit: based on comment

```<code>select
[Measures].[Internet Sales Amount]
on columns,
non empty
(
topcount
(
[Product].[Subcategory].[Subcategory],
5,
[Measures].[Internet Sales Amount]
),[Date].[Calendar Quarter of Year].[Calendar Quarter of Year])
on rows
from
[Adventure Works]
where [Date].[Calendar].[Calendar Year].&[2013]
</code>```

Result

Body:
I'm working with a sales cube.

I want to get the top 5 store by year and display their sales by Quarter later on in my report.

I was able to get the top 5 store but by quarter aswell not only year !

SELECT NON EMPTY { [Measures].[Revenue] } ON COLUMNS,
NON EMPTY { ([DWH REF DATE].[H_CALENDER].[QUARTER NUM].ALLMEMBERS * TOPCOUNT([DWH REF STORE].[H_STORE].[STORE].ALLMEMBERS , 5  ,  [Measures].[Revenue] )) }
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_VALUE, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( -{ [DWH REF STORE].[H_STORE].[TERRITORY].&[N/A].&[N/A] } ) ON COLUMNS FROM ( SELECT ( { [DWH REF DATE].[H_CALENDER].[YEAR NUM].&[2012] } ) ON COLUMNS FROM [SALES CUBE]))

What I want exactly to be able to, is to get the top 5 store by year and after get their sales by quarter of the 5 stores.

Body:
Welcome to SO, so lets take a look at an example.
I am trying to get the top 5 subproducts by internet sales from adventureworks cube for 2013

select
[Measures].[Internet Sales Amount]
on columns,
non empty
topcount
(
[Product].[Subcategory].[Subcategory],
5,
[Measures].[Internet Sales Amount]
)
on rows
from
[Adventure Works]
where [Date].[Calendar].[Calendar Year].&[2013]

Result

Now Lets try to divide there sales by quater

select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Quarter of Year].[Calendar Quarter of Year]
on rows
from
(select  topcount([Product].[Subcategory].[Subcategory],5,[Measures].[Internet Sales Amount]) on 0 from [Adventure Works] )
where [Date].[Calendar].[Calendar Year].&[2013]

Result

Edit: based on comment

select
[Measures].[Internet Sales Amount]
on columns,
non empty
(
topcount
(
[Product].[Subcategory].[Subcategory],
5,
[Measures].[Internet Sales Amount]
),[Date].[Calendar Quarter of Year].[Calendar Quarter of Year])
on rows
from
[Adventure Works]
where [Date].[Calendar].[Calendar Year].&[2013]

Result


问:
should I open/close different Postgres connections in one node endpoint? making this work with OOP
I'm setting up the ability for my node server to load up the proper information from my DB (postgres) to render a certain client View. I'm currently refactoring my server code to follow an Object Oriented Approach with class constructors.

I currently have it so that Readers are a class of functions that are responsible for, well, running read queries on my database. I have inherited classes like MainViewReader and MatchViewReader, and they all inherit from a "Reader" class which instantiates a connection with postgres using the pg-promise library.

The issue with this is that I can't use two view readers or they will be opening up duplicate connections, therefore I am finding myself writing redundant code. So I believe I have two design choices, and I was wondering what was more efficient:

Instead of setting the pattern to be by servlet view, instead set
the pattern to be by the table read using that class, ie
NewsTableReader" MatchTableReader. Pro's of this is that none of
the code is redundant and can be used in different servlets, Con's
is that I would have to end the connection to postgres on every
instance of the Reader class before instantiating a new one as such:

const NewsTableReader = NewsTableReader()
await NewsTableReader.close()

const MatchTableReader = MatchTableReader()
await MatchTableReader.close()

```

<ol start="2">
<li>Just having view readers. Pro's is that this is only one persisting
connection, cons is that there is lots of redundant code if i'm
loading data from the same tables in different views, example:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>const MatchViewReader = MatchViewReader()
await MatchViewReader.load_news()
await MatchViewReader.load_matches()

</code>```

Which approach is going to affect my performance negatively the most?

答:
You've correctly ascertained that you should not create multiple connection pools with the same connection options 1. But this doesn't have to influence the structure of your code.

You could create a global pool, and pass that to your Reader constructors, as a kind of Dependency injection:

class Reader {
  constructor(db) {
    this._db = db
  }
}

class NewsTableReader extends Reader {}
class MatchTableReader extends Reader {}

const pgp = require('pg-promise')(/* library options */)
const db = (/* connection options */)

const newsTableReader = new NewsTableReader(db)
const matchTableReader = new MatchTableReader(db)

await newsTableReader.load()
await matchTableReader.load()
// await Promise.all([newsTableReader.load(), matchTableReader.load()])
```

<p>An other way to go is to use the same classes with the <code>extend</code> event of the <code>pg-promise</code> library:</p>

<pre class="lang-js prettyprint-override"><code>const pgp = require('pg-promise')({
  extend(obj, dc) {
    obj.newsTableReader = new NewsTableReader(obj);
    obj.matchTableReader = new MatchTableReader(obj);
  }
})

const db = (/* connection options */)

await db.newsTableReader.load()

await db.tx(async t => {
    const news = await t.newsTableReader.load();
    const match = await t.matchTableReader.load();
    return {news, match};
});
</code>```

The upside of the extend event is, that you can use all of the functionality (eg. transactions and tasks) provided by the pg-promise library across different models. The thing to keep in mind is, that it creates new objects on every db.task(), db.tx() and db.connect() call.

Body:
I'm setting up the ability for my node server to load up the proper information from my DB (postgres) to render a certain client View. I'm currently refactoring my server code to follow an Object Oriented Approach with class constructors.

I currently have it so that Readers are a class of functions that are responsible for, well, running read queries on my database. I have inherited classes like MainViewReader and MatchViewReader, and they all inherit from a "Reader" class which instantiates a connection with postgres using the pg-promise library.

The issue with this is that I can't use two view readers or they will be opening up duplicate connections, therefore I am finding myself writing redundant code. So I believe I have two design choices, and I was wondering what was more efficient:

Instead of setting the pattern to be by servlet view, instead set
the pattern to be by the table read using that class, ie
NewsTableReader" MatchTableReader. Pro's of this is that none of
the code is redundant and can be used in different servlets, Con's
is that I would have to end the connection to postgres on every
instance of the Reader class before instantiating a new one as such:

const NewsTableReader = NewsTableReader()
await NewsTableReader.close()

const MatchTableReader = MatchTableReader()
await MatchTableReader.close()

Just having view readers. Pro's is that this is only one persisting
connection, cons is that there is lots of redundant code if i'm
loading data from the same tables in different views, example:

const MatchViewReader = MatchViewReader()
await MatchViewReader.load_news()
await MatchViewReader.load_matches()

Which approach is going to affect my performance negatively the most?

Body:
You've correctly ascertained that you should not create multiple connection pools with the same connection options 1. But this doesn't have to influence the structure of your code.

You could create a global pool, and pass that to your Reader constructors, as a kind of Dependency injection:

class Reader {
  constructor(db) {
    this._db = db
  }
}

class NewsTableReader extends Reader {}
class MatchTableReader extends Reader {}

const pgp = require('pg-promise')(/* library options */)
const db = (/* connection options */)

const newsTableReader = new NewsTableReader(db)
const matchTableReader = new MatchTableReader(db)

await newsTableReader.load()
await matchTableReader.load()
// await Promise.all([newsTableReader.load(), matchTableReader.load()])

An other way to go is to use the same classes with the extend event of the pg-promise library:

const pgp = require('pg-promise')({
  extend(obj, dc) {
    obj.newsTableReader = new NewsTableReader(obj);
    obj.matchTableReader = new MatchTableReader(obj);
  }
})

const db = (/* connection options */)

await db.newsTableReader.load()

await db.tx(async t => {
    const news = await t.newsTableReader.load();
    const match = await t.matchTableReader.load();
    return {news, match};
});

The upside of the extend event is, that you can use all of the functionality (eg. transactions and tasks) provided by the pg-promise library across different models. The thing to keep in mind is, that it creates new objects on every db.task(), db.tx() and db.connect() call.


问:
How to permanently redirect `http://` and `www.` URLs to `https://`?
I have a Google App Engine project. On this project I have setup a custom domain and an SSL certificate. Therefore, I can use https://www.mysite.xxx, http://www.mysite.xxx and just the naked domain mysite.xxx.

Is it possible to permanently redirect the last two to always use the secure https:// domain using the developers console or do I just have to redirect in the code?

答: In case your domain is purchased or transferred to Google Domain then you could do it in G-Suite under the Synthetic records section:


问:
QueryableStore accessible from different application id
I have an application which consumes as stream all user activities and I want to count for example how many times he saw the home page and so on and so forth. I materialized count into a persistent key-value store. I want to have access from a different application to this key-value store and get data from this store because I want to share these statistics via rest endpoint. Is it possible?</p>

答:
I want to have access from a different application to this key-value store and get data from this store because I want to share these statistics via rest endpoint. Is it possible?

Yes, this is possible. The feature is called interactive queries in Kafka Streams. There is also a demo application called Kafka Music that you can use as a starting point.

Your first application uses Kafka Streams to compute the state continuously, and it also needs to provide sth like a REST/Thrift/... API that your second application can query. Your second application can be anything: it can be a Python app, a JavaScript app, even a command line tool like curl -- it doesn't have to be another Kafka Streams application.

You must manually implement the "API" of your first application with whatever REST tooling etc. you prefer using, just like for any other Java application that needs to implement a REST API. Kafka Streams provides, via the aforementioned interactive queries functionality, all the necessary methods to tap into and expose the data in your Kafka Streams state stores through the DIY API of yours. (Kafka Streams intentionally does not provide "a REST API" or "a gRPC API" etc. itself because needs across developers are often very different.)


问:
Nock not intercepting http requests
I am currently using node-fetch and nock for an express server that sits on top of an angular project.

I have the following middleware that is making a call to an api:

```<code>export const middleware = async(response: any) => {
    try {
        const result = await fetch(url).then(res => res.json())
        return response.status(200).json(result);
    } catch(err) {
        logger.error({eventId: 'get-content', err});
        return response.status(500)
    }
}
</code>```

and my test is as follows:

```<code>describe('API service', () => {
    let response, scope;
    beforeEach(() => {
        response = {
            status(s) { this.statusCode = s; return this; },
            json(result) { this.res = result; return this; },
        };
    })

    afterEach(() => {
        nock.restore();
    })

    it('should return a 200 response from successful call api', (done) => {
        scope = nock(url)
            .get(/.*/)
            .reply(200, {data: 'content'})

        middleware(response).then(data => {
            expect(response.status).toEqual(200);
            expect(response.data).toEqual('content');
            scope.isDone();
            done();
        })
    })
})
</code>```

However, nock is not mocking the data response from the middleware function. Instead, I'd have to use scope to access its parameters.

The middleware function acts as if nock never mocked its response. Why is this occurring? Am I missing a configuration?

I am serving my tests using karma runner.

答:
Nock works by overriding Node's http.request function. Also, it overrides http.ClientRequest too to cover for modules that use it directly.

https://github.com/nock/nock#how-does-it-work

Unfortunately it appears fetch does not make use of the http.request or http.ClientRequest meaning the requests are never intercepted by nock.

A better approach may be to mock fetch with a library such as fetch-mock.

Title: Nock not intercepting http requests

Body:
I am currently using node-fetch and nock for an express server that sits on top of an angular project.

I have the following middleware that is making a call to an api:

export const middleware = async(response: any) => {
    try {
        const result = await fetch(url).then(res => res.json())
        return response.status(200).json(result);
    } catch(err) {
        logger.error({eventId: 'get-content', err});
        return response.status(500)
    }
}

and my test is as follows:

describe('API service', () => {
    let response, scope;
    beforeEach(() => {
        response = {
            status(s) { this.statusCode = s; return this; },
            json(result) { this.res = result; return this; },
        };
    })

    afterEach(() => {
        nock.restore();
    })

    it('should return a 200 response from successful call api', (done) => {
        scope = nock(url)
            .get(/.*/)
            .reply(200, {data: 'content'})

        middleware(response).then(data => {
            expect(response.status).toEqual(200);
            expect(response.data).toEqual('content');
            scope.isDone();
            done();
        })
    })
})

However, nock is not mocking the data response from the middleware function. Instead, I'd have to use scope to access its parameters.

The middleware function acts as if nock never mocked its response. Why is this occurring? Am I missing a configuration?

I am serving my tests using karma runner.


问:
How to profile a rails controller that returns a json response with rack-mini-profiler?
I am using rack-mini-profiler in my rails 3.2 project.

In gemfile:

```<code>gem 'rack-mini-profiler'
</code>```

Everything works great. But my application is mostly a set of json endpoints. So while it is very useful to be to able to inspect the performance of html pages, I would like to also be able to see the performance of controllers that return json.

Example of my controller:

```<code>class UsersController < BaseController
  def json_method
    # you don't see the mini profiler ui for this controller
    render json: { users: [:foo, :bar]}
  end
end
</code>```

If I go to localhost:3000/users/json_method, I see my json response but not the profiler ui.

答:
Note that in a new Rails API project initialized using rails new api_name --api, the ApplicationController inherits from ActionController::API, instead of ActionAcontroller::Base. In this case, mini-profiler might not load when your HTML page is shown.

I had to change the base class to ActionController::Base to make it work. If in your app you see no requests to load resources from mini-profiler on your HTML page, you may want to try this change. Took me a long while to figure out.

Also note that you do need to have at least the  tag in your template to be rendered, otherwise the mini-profiler divs will not be properly injected.

Body:
I am using rack-mini-profiler in my rails 3.2 project.

In gemfile:

gem 'rack-mini-profiler'

Everything works great. But my application is mostly a set of json endpoints. So while it is very useful to be to able to inspect the performance of html pages, I would like to also be able to see the performance of controllers that return json.

Example of my controller:

class UsersController < BaseController
  def json_method
    # you don't see the mini profiler ui for this controller
    render json: { users: [:foo, :bar]}
  end
end

If I go to localhost:3000/users/json_method, I see my json response but not the profiler ui.

Body:
Note that in a new Rails API project initialized using rails new api_name --api, the ApplicationController inherits from ActionController::API, instead of ActionAcontroller::Base. In this case, mini-profiler might not load when your HTML page is shown.

I had to change the base class to ActionController::Base to make it work. If in your app you see no requests to load resources from mini-profiler on your HTML page, you may want to try this change. Took me a long while to figure out.

Also note that you do need to have at least the <body> tag in your template to be rendered, otherwise the mini-profiler divs will not be properly injected.


问:
Build Failed Could not find method signingConfigs()
I follow in official website : https://facebook.github.io/react-native/docs/signed-apk-android.html

it said line: 128 error
which is
signingConfigs signingConfigs.release

in android/app/build.gradle

```<code> signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfigs signingConfigs.release
        }
    }
</code>```

in android/.gradle/gradle.properties

```<code>MYAPP_RELEASE_STORE_FILE=ezam.keystore
MYAPP_RELEASE_KEY_ALIAS=ezam
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****
</code>```

答:
In my case, I have to do

```<code>buildTypes{
    release{
        signingConfig signingConfigs.release
    }
}
</code>```

instead of

```<code>buildTypes{
    release{
        signingConfig release
    }
}
</code>```

Body:
I follow in official website : https://facebook.github.io/react-native/docs/signed-apk-android.html

it said line: 128 error
which is
signingConfigs signingConfigs.release

in android/app/build.gradle

 signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfigs signingConfigs.release
        }
    }

in android/.gradle/gradle.properties

MYAPP_RELEASE_STORE_FILE=ezam.keystore
MYAPP_RELEASE_KEY_ALIAS=ezam
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****

Body:
In my case, I have to do

buildTypes{
    release{
        signingConfig signingConfigs.release
    }
}

instead of

buildTypes{
    release{
        signingConfig release
    }
}


问:
NativeScript getJSON malformed response
Trying to get data from OMDb API, in Postman the result returns fine, while the getJSON function returns the data unstructured

I have already tried using a typed interface

```<code>export interface ApiResponse {
    Search: Movies[];
    totalResults: string;
    Response: string;
}

export interface Movies {
    title: string;
    year: number;
    poster: string;
    imdbId: string;
    type: string;
}
</code>```

This is the getJSON code

return getJSON<any>(
            this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
        ).then(r => {
            console.log(r);
        });
```

<p>which returns then json malformed </p>

```LOG from device : {
LOG from device : "imdbID": "tt1201607",
LOG from device : "Type": "movie",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
LOG from device : },
LOG from device : {
LOG from device : "Year": "2011",
LOG from device : "Search": [
LOG from device : "Title": "Harry Potter and the Deathly Hallows: Part 2",
LOG from device : {
LOG from device : "Title": "Harry Potter and the Sorcerer's Stone",
LOG from device : "Year": "2001",
LOG from device : "imdbID": "tt0241527",
LOG from device : "Type": "movie",
LOG from device : },
LOG from device : {
LOG from device : "Title": "Harry Potter and the Chamber of Secrets",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
```

<p>Expecting a return like this from Postman: </p>

```{
    "Search": [
        {
            "Title": "Harry Potter and the Deathly Hallows: Part 2",
            "Year": "2011",
            "imdbID": "tt1201607",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
        },
        {
            "Title": "Harry Potter and the Sorcerer's Stone",
            "Year": "2001",
            "imdbID": "tt0241527",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
        },
        {
            "Title": "Harry Potter and the Chamber of Secrets",
            "Year": "2002",
            "imdbID": "tt0295297",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BMTcxODgwMDkxNV5BMl5BanBnXkFtZTYwMDk2MDg3._V1_SX300.jpg"
        }
    ],
    "totalResults": "80",
    "Response": "True"
}
```

答:
Before the console log, use another then(I am pretty sure you should do it with a promise) and resolve the returned result as follows or reject in case of error. You can also add a console log in the catch block, to see the body of the error:

```<code>return new Promise((resolve, reject) => {
   fetch(
            this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
        )
        .then(res => res.json())
        .then(r => {
            console.log(r);
            resolve(r)
        })
        .catch(err => reject(err))
})
</code>```

The fetch method already returns a Promise, so you do not have to return a new Promise you can just concatenate .then() after the fetch. In my view it is fancier to use resolve and reject.
This should fix the problem.
Also see the docs for fetch in Native Script here: Fetch

Title: NativeScript getJSON malformed response

Body:
Trying to get data from OMDb API, in Postman the result returns fine, while the getJSON function returns the data unstructured

I have already tried using a typed interface

export interface ApiResponse {
    Search: Movies[];
    totalResults: string;
    Response: string;
}

export interface Movies {
    title: string;
    year: number;
    poster: string;
    imdbId: string;
    type: string;
}

This is the getJSON code

return getJSON<any>(
            this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
        ).then(r => {
            console.log(r);
        });

which returns then json malformed

LOG from device : {
LOG from device : "imdbID": "tt1201607",
LOG from device : "Type": "movie",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
LOG from device : },
LOG from device : {
LOG from device : "Year": "2011",
LOG from device : "Search": [
LOG from device : "Title": "Harry Potter and the Deathly Hallows: Part 2",
LOG from device : {
LOG from device : "Title": "Harry Potter and the Sorcerer's Stone",
LOG from device : "Year": "2001",
LOG from device : "imdbID": "tt0241527",
LOG from device : "Type": "movie",
LOG from device : },
LOG from device : {
LOG from device : "Title": "Harry Potter and the Chamber of Secrets",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"

Expecting a return like this from Postman:

{
    "Search": [
        {
            "Title": "Harry Potter and the Deathly Hallows: Part 2",
            "Year": "2011",
            "imdbID": "tt1201607",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
        },
        {
            "Title": "Harry Potter and the Sorcerer's Stone",
            "Year": "2001",
            "imdbID": "tt0241527",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
        },
        {
            "Title": "Harry Potter and the Chamber of Secrets",
            "Year": "2002",
            "imdbID": "tt0295297",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BMTcxODgwMDkxNV5BMl5BanBnXkFtZTYwMDk2MDg3._V1_SX300.jpg"
        }
    ],
    "totalResults": "80",
    "Response": "True"
}

Body:
Before the console log, use another then(I am pretty sure you should do it with a promise) and resolve the returned result as follows or reject in case of error. You can also add a console log in the catch block, to see the body of the error:

return new Promise((resolve, reject) => {
   fetch(
            this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
        )
        .then(res => res.json())
        .then(r => {
            console.log(r);
            resolve(r)
        })
        .catch(err => reject(err))
})

The fetch method already returns a Promise, so you do not have to return a new Promise you can just concatenate .then() after the fetch. In my view it is fancier to use resolve and reject.
This should fix the problem.
Also see the docs for fetch in Native Script here: Fetch


问:
I was trying to complete a palindrome-check but reverse variable is not having the expected value
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

```<code>number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")
</code>```

答:
This is another way to check in python if a number is palindrome</p>

```<code>number = input("Type the number:")
temp = str(number)
reverse = temp[::-1]

if reverse == temp :
    print("this is a palindrome number")
else:
    print("this is not a palindrome number")
</code>```

Body:
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")

Body:
This is another way to check in python if a number is palindrome

number = input("Type the number:")
temp = str(number)
reverse = temp[::-1]

if reverse == temp :
    print("this is a palindrome number")
else:
    print("this is not a palindrome number")


问:
I am not able to create msi setup using installshield for self hosted console application
I have created self-hosted WCF service using Console application. I have created msi using Installshield but when I am installing setup it will stuck and after some time failed to setup.

I have added log in code and found that on the line of hosting WCF service it was going to stuck and throw an error.

Any Idea how can I resolve this issue?

答:
Service Install: Can you install and run it manually? You must install with admin rights, if you specify a user account to run the service it must have the "log on as a service" privilege (check by running secpol.msc or see here), the file you install must actually be a proper service - obviously - I sometimes mix up my test executables with the service binary. Ever forget? Happens to me :-).

Logging: Get yourself a proper log file first of all:

```<code>msiexec.exe /i "Setup.msi" /L*V "C:\Setup.log"
</code>```

Or in silent mode:

```<code>msiexec.exe /i "Setup.msi" /QN /L*V "C:\Setup.log"
</code>```

Some more information on Logging:

Installsite.org on logging

Event logging, etc...

Interpreting MSI log files, etc...

Credentials: Just adding that there are several built-in accounts you can use to run the service:

The difference between the 'Local System' account and the 'Network Service' account?

And there is the new concept of "managed service accounts". Step-by-Step.

And finally "group managed service account".

Body:
Service Install: Can you install and run it manually? You must install with admin rights, if you specify a user account to run the service it must have the "log on as a service" privilege (check by running secpol.msc or see here), the file you install must actually be a proper service - obviously - I sometimes mix up my test executables with the service binary. Ever forget? Happens to me :-).

Logging: Get yourself a proper log file first of all:

msiexec.exe /i "Setup.msi" /L*V "C:\Setup.log"

Or in silent mode:

msiexec.exe /i "Setup.msi" /QN /L*V "C:\Setup.log"

Some more information on Logging:

Installsite.org on logging

Event logging, etc...

Interpreting MSI log files, etc...

Credentials: Just adding that there are several built-in accounts you can use to run the service:

The difference between the 'Local System' account and the 'Network Service' account?

And there is the new concept of "managed service accounts". Step-by-Step.

And finally "group managed service account".


问:
Disable ContextMenu in ReactJS
first post here so hopefully I can ask this question the most helpful manner possible. I'm pretty new to coding and in trying to push myself decided to attempt to recreate Minesweeper using React and not using any tutorial. I've gotten a lot of the functionality but am really stuck on this part. I am using the event listener 'onContextMenu' to register a right click to "flag" a mine in the program. But I can't figure the right way to isolate it or maybe it's a syntax issue preventing the menu from popping up at the same time. In JS it seems really simple of just returning false on the event listener, but I can't figure it out in React.

I'm currently using 'onContextMenu' to handle my right click and calling a function that handles the flag assignment with that event listener. Can I also within a function disable the contextMenu from showing?

Thank you for any help you can offer!

The div being rendered looks like this right now:

```<code><div
   contextMenu="none"
   className="square"
   onContextMenu={() => this.props.rightClick(props.arrayVal)}
   onClick={() => {this.props.playerTurn(this.props.index)}}
   style={{color:COLORS[this.props.arrayVal], backgroundImage:this.backgroundChooser(this.props.arrayVal)}}
    >
       {this.squareContent(this.props.arrayVal)}
</div>
</code>```

The function being called looks like this:

```<code>rightClick = (id) => {
    let { board, gameWon, minesLeft } = this.state
    let mineCount = minesLeft
    let move = board
    if (gameWon === false) {
        if (board[id] === -1) {
            move[id] = 9
            mineCount -= 1
        } else if (board[id] === 9) {
            move[id] = "?"
            mineCount += 1
        } else if (board[id] === "?") {
            move[id] = -1
        }
        this.setState({
            board: move,
            minesLeft: mineCount
        })
    }
}
</code>```

I was able to waste another long bit of time and get a senior dev friend to look at this for me. Here was the solution. Hope it helps someone else :-)! See comment below:

答:
I know its an old one but heres my solution for this:
first, select the element you want to disable the contextMenu for (in this occasion its a div element) and just add this event to the element:

 e.preventDefault()}... />

ReactDOM.render(
 e.preventDefault()}>right click me
, root)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

right clicking the div above won't trigger the context menu

Title: Disable ContextMenu in ReactJS

Body:
first post here so hopefully I can ask this question the most helpful manner possible. I'm pretty new to coding and in trying to push myself decided to attempt to recreate Minesweeper using React and not using any tutorial. I've gotten a lot of the functionality but am really stuck on this part. I am using the event listener 'onContextMenu' to register a right click to "flag" a mine in the program. But I can't figure the right way to isolate it or maybe it's a syntax issue preventing the menu from popping up at the same time. In JS it seems really simple of just returning false on the event listener, but I can't figure it out in React.

I'm currently using 'onContextMenu' to handle my right click and calling a function that handles the flag assignment with that event listener. Can I also within a function disable the contextMenu from showing?

Thank you for any help you can offer!

The div being rendered looks like this right now:

 this.props.rightClick(props.arrayVal)}
   onClick={() => {this.props.playerTurn(this.props.index)}}
   style={{color:COLORS[this.props.arrayVal], backgroundImage:this.backgroundChooser(this.props.arrayVal)}}
    >
       {this.squareContent(this.props.arrayVal)}

The function being called looks like this:

rightClick = (id) => {
    let { board, gameWon, minesLeft } = this.state
    let mineCount = minesLeft
    let move = board
    if (gameWon === false) {
        if (board[id] === -1) {
            move[id] = 9
            mineCount -= 1
        } else if (board[id] === 9) {
            move[id] = "?"
            mineCount += 1
        } else if (board[id] === "?") {
            move[id] = -1
        }
        this.setState({
            board: move,
            minesLeft: mineCount
        })
    }
}

I was able to waste another long bit of time and get a senior dev friend to look at this for me. Here was the solution. Hope it helps someone else :-)! See comment below:

Body:
I know its an old one but heres my solution for this:
first, select the element you want to disable the contextMenu for (in this occasion its a div element) and just add this event to the element:

<div onContextMenu={(e)=> e.preventDefault()}... />

ReactDOM.render(<div onContextMenu={(e)=> e.preventDefault()}>right click me</div>, root)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

right clicking the div above won't trigger the context menu


问:
Trying to use InheritedWidget but Getting Null

I’m invoking the of function of the InheritedWidget, but my function is returning null when, as you can see above, I have my widget at the top of the tree. The call is coming from a page that was pushed onto the Navigator stack, which is not this page. Anyone know why? My InheritedWidget code is below.

```<code>class LiveKHProvider extends InheritedWidget {
  final LiveKHBloc liveKHBloc = LiveKHBloc();

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => oldWidget != this;

  static LiveKHBloc of(BuildContext context) {
    var inheritFromWidgetOfExactType =
        context.inheritFromWidgetOfExactType(LiveKHProvider); // to clearly see what’s returning null.
        //This is where it returns null,
        //so the below line is executed on a null object.
    return (inheritFromWidgetOfExactType as LiveKHProvider).liveKHBloc;
  }

  LiveKHProvider({Key key, Widget child}) : super(key: key, child: child);
}
</code>```

答:
InheritedWidget, in my testing atleast, can be inherited even if it's a parent of the MaterialApp/WidgetsApp/CupertinoApp or route.

For anyone else having this problem, a more likely explaination is that you've imported the InheritedWidget with different casing. i.e. Where you generate it, you may have imported it as import 'MyInheritedWidget.dart', while where you are trying to retrieve it, you have it imported as import 'myinheritedwidget.dart' .

This wont cause an error in either file (in windows atleast), but it will not be matched and return null.

Body:
I’m invoking the of function of the InheritedWidget, but my function is returning null when, as you can see above, I have my widget at the top of the tree. The call is coming from a page that was pushed onto the Navigator stack, which is not this page. Anyone know why? My InheritedWidget code is below.

class LiveKHProvider extends InheritedWidget {
  final LiveKHBloc liveKHBloc = LiveKHBloc();

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => oldWidget != this;

  static LiveKHBloc of(BuildContext context) {
    var inheritFromWidgetOfExactType =
        context.inheritFromWidgetOfExactType(LiveKHProvider); // to clearly see what’s returning null.
        //This is where it returns null,
        //so the below line is executed on a null object.
    return (inheritFromWidgetOfExactType as LiveKHProvider).liveKHBloc;
  }

  LiveKHProvider({Key key, Widget child}) : super(key: key, child: child);
}


问:
auto return type of a function which can return an object of sibling
I have  two classes which are inheriting from class Base

struct Base
{
   virtual ~Base() = default;
};

class Derived_1:public Base
{
  public:
     void getSomeFunc();
};

class Derived_2:public Base
{
  public:
     void getSomeFunc();
};
```

<p>Now what I want to write a function which takes base class pointer object and after dynamic casting finding the appropriate child and returns it so that we can call right version of <code>getSomeFunc()</code></p>

<p>I tried to write </p>

```auto getChild(Base* ptr)
{
  Derived_1 * p = dynamic_cast<Derived_1*>(ptr)
  if(p)
  {
    return p;
  }
  else
  {
      Derived_2 * q = dynamic_cast<Derived_2*>(ptr)
      if(q)
      {
        return q;
      }
     else
     {
        // some handling to avoid bugs!!
     }
  }
```

But It does not get compiled. Any way to serve my requirement.

Edit 1 ----------------------------------

Error  from compiler is - incorrect deduction of 'auto'.
Compile is gcc

答:
This is almost certainly not what you want to do. Instead,  use a virtual method:

```<code>class Base {
public:
    virtual void getSomeFunc() = 0;
    // ... etc etc ...
};
</code>```

then, you could write:

```<code>Base* ptr = get_a_base_instance_ptr_from_somewhere();
ptr->getSomeFunc();
</code>```

In your code, you were trying to have auto have either the type of p or the type of q. But auto only has a single type. And a type which can accept both a pointer to Derived_1 and a pointer to Derived_2 is... yes, you guessed it: Base*.

edit: If you are unable to change the Base, Derived_1 and Derived_2 class, you could consider using std::variant<Derived_1*, Derived_2*>, and using visitation to call the appropriate method for each of these types. If you haven't used variants before, see the CPP-reference page on std::variant.  For information on how to write a visitor for use with a variant, see this SO question:

How does std::visit work with std::variant?

Body:
I have  two classes which are inheriting from class Base

struct Base
{
   virtual ~Base() = default;
};

class Derived_1:public Base
{
  public:
     void getSomeFunc();
};

class Derived_2:public Base
{
  public:
     void getSomeFunc();
};

Now what I want to write a function which takes base class pointer object and after dynamic casting finding the appropriate child and returns it so that we can call right version of getSomeFunc()

I tried to write

auto getChild(Base* ptr)
{
  Derived_1 * p = dynamic_cast<Derived_1*>(ptr)
  if(p)
  {
    return p;
  }
  else
  {
      Derived_2 * q = dynamic_cast<Derived_2*>(ptr)
      if(q)
      {
        return q;
      }
     else
     {
        // some handling to avoid bugs!!
     }
  }

But It does not get compiled. Any way to serve my requirement.

Edit 1 ----------------------------------

Error  from compiler is - incorrect deduction of 'auto'.
Compile is gcc

Body:
This is almost certainly not what you want to do. Instead,  use a virtual method:

class Base {
public:
    virtual void getSomeFunc() = 0;
    // ... etc etc ...
};

then, you could write:

Base* ptr = get_a_base_instance_ptr_from_somewhere();
ptr->getSomeFunc();

In your code, you were trying to have auto have either the type of p or the type of q. But auto only has a single type. And a type which can accept both a pointer to Derived_1 and a pointer to Derived_2 is... yes, you guessed it: Base*.

edit: If you are unable to change the Base, Derived_1 and Derived_2 class, you could consider using std::variant<Derived_1*, Derived_2*>, and using visitation to call the appropriate method for each of these types. If you haven't used variants before, see the CPP-reference page on std::variant.  For information on how to write a visitor for use with a variant, see this SO question:

How does std::visit work with std::variant?


问:
How do i get the HTML from a MockMVC?
In spring, I have found my MockMVC for a given url:

```<code>MvcResult result = this.mockMvc.perform( get(urlToFetch).sessionAttrs(sessionAttr))
            .andExpect(status().isOk())
            .andReturn();
</code>```

Great. Now I want to see what the html that this would return is. How do I do that? I want a string representation of it (ie String theHtml = ...) so I can parse it and check it in my test.

答:
You can simply use

String responseString = result.getResponse().getContentAsString();

Title: How do i get the HTML from a MockMVC?

Body:
In spring, I have found my MockMVC for a given url:

MvcResult result = this.mockMvc.perform( get(urlToFetch).sessionAttrs(sessionAttr))
            .andExpect(status().isOk())
            .andReturn();

Great. Now I want to see what the html that this would return is. How do I do that? I want a string representation of it (ie String theHtml = ...) so I can parse it and check it in my test.


问:
How a corrupted double linked list error is detected in malloc?
I don't understand a condition for gettint the error - corrupted double-linked list (not small) -

There is a point in the program where it crashes due to corrupted double-linked list (not small).

At this moment, I don't want to know why it crashed, but I want to know how this conditions work

```<code>if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) || __builtin_expect(P->bk_nextsize->fd_nextsize != P, 0))
     malloc_printerr (check_action,"corrupted double-linked list (not small)", P, AV);
</code>```

Here we can see that the error double-linked list is observed when the P->fd_nextsize->bk_nextsize != P is not accomplished or P->bk_nextsize->fd_nextsize is not accomplished.

But my main problem is that I can't explain how this part of code -  P->fd_nextsize->bk_nextsize - expects to be P. I am expecting that P->fd_nextsize->bk_nextsize is P->bk_nextsize.

Maybe I am confused with the structure of the double linked list in the bins.

At this moment, I understand the double linked list as this:

```<code>+------------------->+----------------+ <---------+
|                    |  fd_nextsize   |           |
|                    |                |           |
|                    |                |           |
|                    +----------------+           |
|                    |                |           |
|                    |fd_nextsize     |           |
|                    |                |           |
|                    +----------------+           |
|                    |                |           |
|                    +bk_nextisize    |--------------------+
|                    |                |           |        |
|                    +----------------+           |        |
|                                                 |        |
|                                                 |        |
|                                                 |        |
|                                                 |        |
|                     +---------------+           |        |
|                     |  P            |           |        |
|                     |               |           |        |
|                     +---------------+           |        |
|                     |               |           |        |
|                     |fd_nextsize    +-----------+        |
|                     |               |                    |
|                     +---------------+                    |
|                     |               |                    |
|         +-----------+bk_nextsize    |                    |
|         |           |               |                    |
|         |           +---------------+                    |
|         |                                                |
|         |                                                |
|         |                                                |
|         +----------->+----------------+<-----------------+
|                      | bk_nextisize   |
|                      |                |
|                      |                |
|                      +----------------+
|                      |                |
+----------------------+ fd_nextsize    |
                       |                |
                       +----------------+
                       |bk_nextsize     |
                       |                |
                       +----------------+

</code>```

So, if I am incorrect about my understanding of the double linked lists in the bins (Important information, according to the code and also due to the fact that we are using fd_nextsize and bk_nextsize this chunk is not in the smallbin) please correct me. Since at this moment, this condition does not make any sense to me.

Body:
I don't understand a condition for gettint the error - corrupted double-linked list (not small) -

There is a point in the program where it crashes due to corrupted double-linked list (not small).

At this moment, I don't want to know why it crashed, but I want to know how this conditions work

if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) || __builtin_expect(P->bk_nextsize->fd_nextsize != P, 0))
     malloc_printerr (check_action,"corrupted double-linked list (not small)", P, AV);

Here we can see that the error double-linked list is observed when the P->fd_nextsize->bk_nextsize != P is not accomplished or P->bk_nextsize->fd_nextsize is not accomplished.

But my main problem is that I can't explain how this part of code -  P->fd_nextsize->bk_nextsize - expects to be P. I am expecting that P->fd_nextsize->bk_nextsize is P->bk_nextsize.

Maybe I am confused with the structure of the double linked list in the bins.

At this moment, I understand the double linked list as this:

+------------------->+----------------+ <---------+
|                    |  fd_nextsize   |           |
|                    |                |           |
|                    |                |           |
|                    +----------------+           |
|                    |                |           |
|                    |fd_nextsize     |           |
|                    |                |           |
|                    +----------------+           |
|                    |                |           |
|                    +bk_nextisize    |--------------------+
|                    |                |           |        |
|                    +----------------+           |        |
|                                                 |        |
|                                                 |        |
|                                                 |        |
|                                                 |        |
|                     +---------------+           |        |
|                     |  P            |           |        |
|                     |               |           |        |
|                     +---------------+           |        |
|                     |               |           |        |
|                     |fd_nextsize    +-----------+        |
|                     |               |                    |
|                     +---------------+                    |
|                     |               |                    |
|         +-----------+bk_nextsize    |                    |
|         |           |               |                    |
|         |           +---------------+                    |
|         |                                                |
|         |                                                |
|         |                                                |
|         +----------->+----------------+<-----------------+
|                      | bk_nextisize   |
|                      |                |
|                      |                |
|                      +----------------+
|                      |                |
+----------------------+ fd_nextsize    |
                       |                |
                       +----------------+
                       |bk_nextsize     |
                       |                |
                       +----------------+

So, if I am incorrect about my understanding of the double linked lists in the bins (Important information, according to the code and also due to the fact that we are using fd_nextsize and bk_nextsize this chunk is not in the smallbin) please correct me. Since at this moment, this condition does not make any sense to me.

Body:
Example of  corrupted double list with correct diagram.

gef> x/200x victim
0x2c76330:      0x00000000      0x00000000      0x000004d1      0x00000000
0x2c76340:      0x140e8fb8      0x00007f12      0x140e8fb8      0x00007f12
0x2c76350:      0x02c15e48      0x00000000      0x02c76330      0x00000000
0x2c76360:      0x00000318      0x00000000      0x00000000      0x00000000

Here

0x02c15e48    >>> fd_nextsize
0x02c76330    >>> bk_nextsize

gef> x/100x 0x02c15e48
0x2c15e48:      0x02c76348      0x00000000      0x00000000      0x00000000
0x2c15e58:      0x00000019      0x00000000      0x09080003      0x0071db5c
0x2c15e68:      0xc0b51d4f      0x00000001      0x000000fa      0x00000000
0x2c15e78:      0x00000003      0x00007706      0x00007706      0x586a0001

0xc0b51d4f >>> victim->fd_nextisize->fd_nextsize
0x000000fa >>> vicitim->fd_nextsize->bk_nextsize  >>>>>>>>>>>>>>>>>>>>>>>>>>>>> This is not valid.

gef> x/100x 0x02c76330
0x2c76330:      0x00000000      0x00000000      0x000004d1      0x00000000
0x2c76340:      0x140e8fb8      0x00007f12      0x140e8fb8      0x00007f12
0x2c76350:      0x02c15e48      0x00000000      0x02c76330      0x00000000
0x2c76360:      0x00000318      0x00000000      0x00000000      0x00000000

0x02c15e48 >>> victim->bk_nextsize->fd_nextsize
0x02c76330 >>> victim->bk_nextsize->bk_nextsize >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> This condition is valid.

   Double Linked Lists in GLIBC

             +----------------------+<------------------+
             |      ChunkA          |                   |
             +-----------------------+                  |
             |fd_nextsize           |                   |
             +----------------------+                   |
             |                      |                   |
         +---+bk_nextsize           |                   |
         |   +----------------------+                   |
         |                                              |
         |  +------------------------+<---------+       |
         |  |    ChunkB              |          |       |
         |  +------------------------+          |       |
         |  |fd_nextsize             |          |       |
         |  |                        |          |       |
         |  +------------------------+          |       |
+-----------+bk_nextsize             |          |       |
|        |  +------------------------+          |       |
|        |                                      |       |
|        +->+------------------------+<-----------------------------+
|           |      ChunkC            |          |       |           |
|           +------------------------+          |       |           |
|           |fd_nextsize             +------------------+           |
|           |                        |          |                   |
|           +------------------------+          |                   |
|    +------+bk_nextsize             |          |                   |
|    |      +------------------------+          |                   |
|    |                                          |                   |
+---------->+------------------------+          |                   |
     |      |        ChunkD          |          |                   |
     |      +------------------------+          |                   |
     |      |fd_nextsize             +----------+                   |
     |      +------------------------+                              |
     |      |                        |                              |
     |      |bk_nextsize             |                              |
     |      +------------------------+                              |
     |                                                              |
     +----> +------------------------+                              |
            |       ChunkE           |                              |
            +------------------------+                              |
            |fd_nextsize             +------------------------------+
            |                        |
            +------------------------+
            |bk_nextsize             |
            +------------------------+


问:
Using charAt with number in Javascript
I want to set some index to my statement and check it's found or not i found this method charAt but it's work just with strings so how to handle these with numbers

```<code>if (mobileNumber) {
        let j = mobileNumber.charAt(2);
        let w = mobileNumber.charAt(0);
        alert("@", w, j)
        if (j === 9) { //Not work quz it's a number
          alert("FoundJ", j)
          return;
        } else if (w === 6) { //Not work quz it's a number
          alert("FoundW", w)
          return
        } else{
           alert("sorry, App does not work in your city right now")
           return
          }
</code>```

Update

now I handle the index but I have some issue with them here is my Statements
if I write the number and it contains 9 || 6 in the (2)index I see the alert when calling the function I don't know why?

```<code> let j = mobileNumber.toString().charAt(2);
      if (mobileNumber.length <= 0) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, write your Mobile Number"
          })
        );
        return;
      } else if (mobileNumber.length < 10) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid:
              "• Your Mobile Number must be exactly 10 characters!"
          })
        );
        return;
      } else if (regNumber.test(mobileNumber) === false) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, Your mobile must be a number"
          })
        );
        return;
      }
      else if (j != 9 || j != 6) { // i think the issue with **OR**
        alert("sorry not work in your city yet!")
        return;
      }
 else {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: ""
          })
        );
      }
</code>```

答:
Just convert them to strings before:

```<code>if (mobileNumber) {
   let j = mobileNumber.toString().charAt(2);
   let w = mobileNumber.toString().charAt(0);
}
</code>```

And if you need them as numbers, just parse them back:

```<code>let jNumber = parseInt(j, 10);
</code>```

Title: Using charAt with number in Javascript

Body:
I want to set some index to my statement and check it's found or not i found this method charAt but it's work just with strings so how to handle these with numbers

if (mobileNumber) {
        let j = mobileNumber.charAt(2);
        let w = mobileNumber.charAt(0);
        alert("@", w, j)
        if (j === 9) { //Not work quz it's a number
          alert("FoundJ", j)
          return;
        } else if (w === 6) { //Not work quz it's a number
          alert("FoundW", w)
          return
        } else{
           alert("sorry, App does not work in your city right now")
           return
          }

Update

now I handle the index but I have some issue with them here is my Statements
if I write the number and it contains 9 || 6 in the (2)index I see the alert when calling the function I don't know why?

 let j = mobileNumber.toString().charAt(2);
      if (mobileNumber.length <= 0) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, write your Mobile Number"
          })
        );
        return;
      } else if (mobileNumber.length < 10) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid:
              "• Your Mobile Number must be exactly 10 characters!"
          })
        );
        return;
      } else if (regNumber.test(mobileNumber) === false) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, Your mobile must be a number"
          })
        );
        return;
      }
      else if (j != 9 || j != 6) { // i think the issue with **OR**
        alert("sorry not work in your city yet!")
        return;
      }
 else {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: ""
          })
        );
      }

Body:
Just convert them to strings before:

if (mobileNumber) {
   let j = mobileNumber.toString().charAt(2);
   let w = mobileNumber.toString().charAt(0);
}

And if you need them as numbers, just parse them back:

let jNumber = parseInt(j, 10);


问:
Create one object instance per class in hierarchy
I was asked this question in an interview.

There are 3 classes A, B extends A & C extends B. We have to design these classes conforming to these constraints

Client can instantiate only one instance of A, one instance of B & one instance of C using their default constructor with new keyword.

Trying to create another instance of any of these class will result in an exception.

The designer of the class have to enforce the above 2 rules, so that client will experience the above rules implicitly (i.e. it should not be the responsibility of client to conform to above rules).

I suggested an approach using an static Map<Class, Object>. So for e.g. when somebody called new B() it would check if map.contains(B.class). If yes then throw exception & if not then save instance in map & let the object be created.

But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.

How would I solve this problem?

答:
But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.

Simply by putting that map, and the code around it into some distinct Utility class. So that each and of your classes could do something like:

```<code>public WhateverClassConstructor() {
  synchroized(someLock) {
     SingeltonChecker.ensureUnique(this);
</code>```

with

```<code> public static void ensureUnique(Object objectToAdd) {
   Class<?> classToAdd = o.getClass();
   ...
</code>```

And given the fact that C extends B extends A, you probably only need that call in the constructor of class A. On the other hand, imagine that your first call to new C() causes an exception with the C-constructor, but a second call would not. Sure, that is a problem in itself, but still, the question remains: how do you ensure an object was fully and correctly initialized before adding it to such a map?!

Thus: there is a ton of things to consider when writing such utility code. Thus my answer would focus on the impractically, almost stupid-ness of the given design point, and suggest to throw it away and go for other solutions, for example something as simple as:

```<code>public enum SingletonObjectHolder {
  private final Object hold;
  A_INSTANCE(new A()), B_INSTANCE(new B())...

  public Object getSingleton() { return hold; }
  private SingletonObjectHolder(Object o) { hold = o };
</code>```

Don't waste too much time trying to give people a technical answer, when the real point is to not shoot yourself into the foot. And make no mistake: getting that map-based "singleton" approach to work robust and correct, for all kinds of contexts, consider that really hard.

In other words: if I would ask you this question in an interview, I would want to hear an answer that challenges that horrible design point. Sure, spent 10% of your time outlining a solution for the given scenario. But spend 90% of the time explaining why it is so bad, and why other solutions would be much better.

Body:
But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.

Simply by putting that map, and the code around it into some distinct Utility class. So that each and of your classes could do something like:

public WhateverClassConstructor() {
  synchroized(someLock) {
     SingeltonChecker.ensureUnique(this);

with

 public static void ensureUnique(Object objectToAdd) {
   Class<?> classToAdd = o.getClass();
   ...

And given the fact that C extends B extends A, you probably only need that call in the constructor of class A. On the other hand, imagine that your first call to new C() causes an exception with the C-constructor, but a second call would not. Sure, that is a problem in itself, but still, the question remains: how do you ensure an object was fully and correctly initialized before adding it to such a map?!

Thus: there is a ton of things to consider when writing such utility code. Thus my answer would focus on the impractically, almost stupid-ness of the given design point, and suggest to throw it away and go for other solutions, for example something as simple as:

public enum SingletonObjectHolder {
  private final Object hold;
  A_INSTANCE(new A()), B_INSTANCE(new B())...

  public Object getSingleton() { return hold; }
  private SingletonObjectHolder(Object o) { hold = o };

Don't waste too much time trying to give people a technical answer, when the real point is to not shoot yourself into the foot. And make no mistake: getting that map-based "singleton" approach to work robust and correct, for all kinds of contexts, consider that really hard.

In other words: if I would ask you this question in an interview, I would want to hear an answer that challenges that horrible design point. Sure, spent 10% of your time outlining a solution for the given scenario. But spend 90% of the time explaining why it is so bad, and why other solutions would be much better.


问:
How can I return a struct if a condition is true and an int if the condition is false
First a simple example:

```<code>typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}
</code>```

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

答:
There's no way to have a variable return type from a function in C.

One option is to modify the struct to include an int which indicates if the struct is valid or not.

```<code>typedef struct
{
    int valid;
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
} Order;

Order algorithm(int a, int b)
{
    Order ord;
    ord.valid = -1;     //  assume an error has occurred
    if(a != b)
    {
        ord.valid = 0;
        // populate other members of ord
    }
    return ord;
}
</code>```

This requires the caller to check, for example;

```<code> Order result = algorithm(i, j);
 if (result.valid == 0)
 {
      // use members of result
 }
 else
    complain_bitterly();
</code>```

Another is to add a third (pointer) argument to the function

```<code> Order algorithm(int a, int b, int *valid)
 {
      Order ord;
      *valid = -1;
      if (a != b)
      {
          // populate members of ord
          *valid = 0;
      }
      return ord;
  }

  void caller()
  {
      int valid;
      Order result = algorithm(i,j, &valid);
      if (valid == 0)
      {
          // use members of result
      }
  }
</code>```

Body:
First a simple example:

typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

Body:
There's no way to have a variable return type from a function in C.

One option is to modify the struct to include an int which indicates if the struct is valid or not.

typedef struct
{
    int valid;
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
} Order;

Order algorithm(int a, int b)
{
    Order ord;
    ord.valid = -1;     //  assume an error has occurred
    if(a != b)
    {
        ord.valid = 0;
        // populate other members of ord
    }
    return ord;
}

This requires the caller to check, for example;

 Order result = algorithm(i, j);
 if (result.valid == 0)
 {
      // use members of result
 }
 else
    complain_bitterly();

Another is to add a third (pointer) argument to the function

 Order algorithm(int a, int b, int *valid)
 {
      Order ord;
      *valid = -1;
      if (a != b)
      {
          // populate members of ord
          *valid = 0;
      }
      return ord;
  }

  void caller()
  {
      int valid;
      Order result = algorithm(i,j, &valid);
      if (valid == 0)
      {
          // use members of result
      }
  }


答:
First convert number to string using toString(), then use charAt(index)

var mobileNumber = 98812345;
console.log(mobileNumber.toString().charAt(1));```

Title: Using charAt with number in Javascript


问:
Replace javascript array with item inside of object
I want to show some data depending on which month it is. I have an array from 0 to 11. I'm confused on how to do this because there are multiple arrays inside of the object and it's scaring me lol

```<code>[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
];
</code>```

I have a variable that I can reference like this: getMonth(new Date(this.props.startDate))

0

Can I do something like this?

forEach(data[x].rain[getMonth(new Date(this.props.startDate))])

I'd like to replace the existing rain array with the data of the corresponding month. So for example if it was January (0) I'd like data[1].rain = 22.4091

expected output if (getMonth = 0):

```<code>[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: 22.4091
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: 22.4091
    ],
  },
];
</code>```

Body:
I want to show some data depending on which month it is. I have an array from 0 to 11. I'm confused on how to do this because there are multiple arrays inside of the object and it's scaring me lol

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
];

I have a variable that I can reference like this: getMonth(new Date(this.props.startDate))

0

Can I do something like this?

forEach(data[x].rain[getMonth(new Date(this.props.startDate))])

I'd like to replace the existing rain array with the data of the corresponding month. So for example if it was January (0) I'd like data[1].rain = 22.4091

expected output if (getMonth = 0):

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: 22.4091
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: 22.4091
    ],
  },
];

Body:
You can use map(). Return an object from map() with all properties same as previous but change rain to the the first element of it.

 let arr = [ { l: false, u: 'AU', n: 'Adelaide', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, { l: false, u: 'AU', n: 'A Different Place', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, ];

const res = arr.map(x => ({...x,rain:x.rain[0]}))
console.log(res)


问:
"SQL Server Compact 2008" including spatial support
I've read somewhere that there will be a "SQL Server Compact 2008" including spatial support but now that I search for it, I can't find it anywhere. For example, there's nothing on https://connect.microsoft.com/SQLServer/content/content.aspx?ContentID=5470 regarding the compact version.

Does anyone know what the scoop is?

I have a situation here, i have created WPF application with SQL Compact edition database , now i want to store some spatial data in it. I am using google maps and want to use the geography data type which is not supported in CE. Now, what should be the best approach i should follow, should i use the express edition but then how will i encrypt the data in db / make it safe?

答: On this page here, you can read all about the new release of SQL Server Compact Edition v4.0 - however, I don't see any mention of the SQL Server 2008 spatial datatypes being supported.</p>


问:
How to retrieve all data from three tables according to groupby of second table's field value using Laravel eloquent query?
I have three models with some methods like

1.Employee Model

class Employee extends Model
{
    protected $fillable = [
       'employee_no','card_no','inactivedate', 'activedate', 'status',
     ];

    public function office(){
        return $this->hasOne(EmployeeOffice::class);
    }

    public function section(){
        return $this->belongsTo('App\Hrm\Section');
    }

}

```

<p>2.EmployeeOffice Model</p>

<pre class="lang-php prettyprint-override"><code>class EmployeeOffice extends Model
{
  $fillable = ['employee_id','section_id','line_id','join_date','gross','confirm_date'];

public function employee(){
    return $this->belongsTo(Employee::class);
 }

public function section(){
   return $this->belongsTo('App\Hrm\Section');
}

}

</code>```

3.Section model....

```<code>class Section extends Model
{
    protected $fillable = ['name','description','status'];

  //
}

</code>```

i need all inactive employee information according to the employee inactive date(from employee model) as well as their all office information from EmployeeOffice model and must be groupBy according to section_id which is (section_id as foreign key) available in EmployeeOffice model.

For that i have to go with some condition like  ..

 Employee::where('inactivedate','like','%'.$date.'%');
*And need all data from office and employee table
*need section name and grouped by as section name from section model

***please suggest me how can i solve this problem ***
```

答:
Try this:

```<code>$data = Section::with(
    array(
        'employeeOffice' => function(
            $query->with(
                'employees' => function(
                    $query->where('employees.inactivatedate', 'like', '%'.$date.'%'
                    )
            )
        )
    )
)
->get();
</code>```

This should give you an array to every section_id. In this array are the employeeOffices (1:n-Relationship). The second query with with will fetch for each employeeOffice the employee who sits in it.

But if you defined the relationships right, this should do the trick to:

```<code>Section::with('EmployeeOffice.Employee')->get();
</code>```

Nested Eager Loading

Body:
I have three models with some methods like

1.Employee Model

class Employee extends Model
{
    protected $fillable = [
       'employee_no','card_no','inactivedate', 'activedate', 'status',
     ];

    public function office(){
        return $this->hasOne(EmployeeOffice::class);
    }

    public function section(){
        return $this->belongsTo('App\Hrm\Section');
    }

}

2.EmployeeOffice Model

class EmployeeOffice extends Model
{
  $fillable = ['employee_id','section_id','line_id','join_date','gross','confirm_date'];

public function employee(){
    return $this->belongsTo(Employee::class);
 }

public function section(){
   return $this->belongsTo('App\Hrm\Section');
}

}

3.Section model....

class Section extends Model
{
    protected $fillable = ['name','description','status'];

  //
}

i need all inactive employee information according to the employee inactive date(from employee model) as well as their all office information from EmployeeOffice model and must be groupBy according to section_id which is (section_id as foreign key) available in EmployeeOffice model.

For that i have to go with some condition like  ..

 Employee::where('inactivedate','like','%'.$date.'%');
*And need all data from office and employee table
*need section name and grouped by as section name from section model

***please suggest me how can i solve this problem ***

Body:
Try this:

$data = Section::with(
    array(
        'employeeOffice' => function(
            $query->with(
                'employees' => function(
                    $query->where('employees.inactivatedate', 'like', '%'.$date.'%'
                    )
            )
        )
    )
)
->get();

This should give you an array to every section_id. In this array are the employeeOffices (1:n-Relationship). The second query with with will fetch for each employeeOffice the employee who sits in it.

But if you defined the relationships right, this should do the trick to:

Section::with('EmployeeOffice.Employee')->get();

Nested Eager Loading


问:
How to make Vue auto-instantiate components on init?
I'm new to Vue, I'm doing some tests.

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <select v-for="select in selects">
        <option>test</option>
      </select>
    </div>
  `,
  props:['selects']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[{name:'select-1'},{name:'select-2'}]
  }
  ,mounted: function(){
  }
  ,created: function(){
  }
  ,methods: {

  }
});
</code>```

...And later in html:

```<code><area-selectors-box></area-selectors-box>
</code>```

But it will only output

, not the selects.

Why? What am I doing wrong?

答:
Thank to @Daniel Danaee, I found out I missed a step. On my html I had to reference the binded property like this:</p>

```<code><area-selectors-box v-bind:selects="selects"></area-selectors-box>
</code>```

Body:
I'm new to Vue, I'm doing some tests.

Vue.component('area-selectors-box', {
  template: `

      <select v-for="select in selects">
        <option>test</option>
      </select>

  `,
  props:['selects']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[{name:'select-1'},{name:'select-2'}]
  }
  ,mounted: function(){
  }
  ,created: function(){
  }
  ,methods: {

  }
});

...And later in html:

<area-selectors-box></area-selectors-box>

But it will only output

, not the selects.

Why? What am I doing wrong?

Body:
Thank to @Daniel Danaee, I found out I missed a step. On my html I had to reference the binded property like this:

<area-selectors-box v-bind:selects="selects"></area-selectors-box>