问:
App Store upload is really slow and hogging my internet connection
In the past 6 months every time I upload a new version/build to the Apple App Store through Xcode / Application Loader, it takes between 20-40 minutes for even the smallest app. The uploader is always stuck at the beginning and when if finishes after a huge amount of time, the progress bar just jumps to the end.

Also, and the most annoying, it totally hogs my internet connection (and anyone who is connected to the network aside from me). It’s not usable at all.. it’s really frustrating to upload a build to the App Store for so much time while it totally kills my internet connection -> it happens on any internet connection I try to upload from: Home, office, friends houses, public networks at the mall / restaurants.

When I upload APKs to the Google Play Store, everything works crazy fast (5-10min tops!) and my internet connection is working fine while doing it.

I also tried opening a bug report ticket to Apple, but because it’s Apple, they didn’t even take the time to answer it for almost a month now.

Does this happen to anyone here? Is there a way around it?

Thank you very much :)

答:
I have the same problem. fastlane deliver worked for me. Still very slow, but at least it works and does not hog internet.
Here the docs


来源: stackexchange

问:
How to run sql scripts from a pl sql procedure
I have a procedure like :

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;
</code>```

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;
</code>```

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?

答:
You could write a Java Stored Procedure to open the file and return its contents as a String and then call Execute Immediate on the String.

Be VERY CAREFUL doing this though as any malicious sql in those files can do pretty much whatever it wants.

ContentLicense: CC BY-SA 2.5

Body:
I have a procedure like :

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?


问:
How can I serve files under node_modules with GitHub Pages?
github pages won't serve my node_modules files (gives 404's), despite the special attention i've provided to it

github project https://github.com/open-history/sandbox

hosted on github pages https://open-history.github.io/sandbox/

(notice the 404's)

i've tracked the node_modules files i want into the repository

i've added the empty .nojekyll file (the previously established solution)

i must be missing something, since so many other users seem to be doing the same thing, most of which report success after adding .nojekyll

答:
Just sit back, and have a rum

it turns out, github pages just employs some serverside caching, and it can take hours to begin serving up new files

all i needed to do, was wait it out

interestingly, the node_module files were available via a curl request for awhile before my web browsers could finally see the fruits of my labor — see relevant comments in this github issue https://github.com/isaacs/github/issues/844

ContentLicense: CC BY-SA 3.0


问:
Install.aspx file issue while upgrading Evoq Content
Currently my application is running on Evoq Content 7.3 and I was trying to upgrade it to Evoq Basic 8.5. I have copied the upgraded file into my application directory And now when I try to access the http://MYWEBSITE/install/install.aspx?mode=upgrade , It is giving error "resource can not found Requested URL: /install/install.aspx.

Please advise.

答:
This looks like some files were removed from the install directory, probably as part of a security precaution.  I'm not sure why they were not added back with the upgrade package.

You might be able to fix this by copying the install directory from an appropriate install package.  Just the install directory.

As always, make a copy of your database and complete file directory first, just in the event that what you do fails.


问:
How to handle requests in ReactJs?
I explain my question using the following image.

 1. First user login to my app which hosted on server [3], via cloud[1].
    In the meantime, the user authenticates using Identity Provider[1].
    And Identity Provider sends JWT to Cloud Server[1].

Then Cloud Sercer[1] send the request to my Application Server[1]
along with that JWT as request header and Application Server[3] then serve index page
back to the user.

Now my problem is I need to get that JWT within my ReactJs application in order to get user details within that JWT. Since React is client-side framework I unable to handle requests with React.

So my problem is how can I get this JWT from ReactJs side?

答:
Yes, ReactJS it self cannot handle this because it's frontend.

You need to have a separate backend for your application (i.e BFF - backend for frontend). You can use a nodejs server to wrap your frontend and have a middleware to capture the JWT request and extract user details. Then at the time of serving to react frontend from the nodejs server, you can bind the information to it.

When binding I would prefer binding data to a javascript variable or function.

in your react index page you can have a global function.

```<code><body>
  <script type="application/javascript">
    function getUserDetails(){
      return JSON.parse("!!!!USER_DATA!!!!");
    }
  </script>
  <div id="app"></div>
</body>
</code>```

and you can replace '!!!!USER_DATA!!!!' part with a valid json with user details when rendering the react page from BFF. like this,

```<code>let userDetailJsonString = JSON.stringify(dataFromJWT);
res.send(renderingIndexPage.replace(/\!\!\!\!USER_DATA\!\!\!\!/g, userDetailJsonString.replace(/"/g, "\\\"")));
</code>```

You can do this in different ways, You may try a  different way.

Title: How to handle requests in ReactJs?

Body:
Yes, ReactJS it self cannot handle this because it's frontend.

You need to have a separate backend for your application (i.e BFF - backend for frontend). You can use a nodejs server to wrap your frontend and have a middleware to capture the JWT request and extract user details. Then at the time of serving to react frontend from the nodejs server, you can bind the information to it.

When binding I would prefer binding data to a javascript variable or function.

in your react index page you can have a global function.

<body>
  <script type="application/javascript">
    function getUserDetails(){
      return JSON.parse("!!!!USER_DATA!!!!");
    }
  </script>
  <div id="app"></div>
</body>

and you can replace '!!!!USER_DATA!!!!' part with a valid json with user details when rendering the react page from BFF. like this,

let userDetailJsonString = JSON.stringify(dataFromJWT);
res.send(renderingIndexPage.replace(/\!\!\!\!USER_DATA\!\!\!\!/g, userDetailJsonString.replace(/"/g, "\\\"")));

You can do this in different ways, You may try a  different way.


问:
how to choose LSTM 2-d input shape?
I am trying to feed 1-D signal(1,2000) which has 22 features(22,2000) into LSTM.

(1-D signal is taken by 10 seconds with 200 hz sampling rate)

And I have 808 batches. (808, 22, 2000)

I saw that the LSTM receives 3D tensor shape of (batch_size, timestep, input_dim).

So is it right that my input shape as?

: (batch_size = 808, timestep = 2000, input_dim = 3)

here is my sample of code.

# data shape check
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
(727, 22, 2000)
(81, 22, 2000)
(727, 2)
(81, 2)

# Model Config
inputshape = (808,2000,2)  # 22 chanel, 2000 samples
lstm_1_cell_num = 20
lstm_2_cell_num = 20
inputdrop_ratio = 0.2
celldrop_ratio = 0.2

# define model
model = Sequential()
model.add(LSTM(lstm_1_cell_num, input_shape=inputshape, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(20))
model.add(LSTM(lstm_2_cell_num, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(2, activation='sigmoid'))
print(model.summary())
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
```

答:
First input shape must be (22,2000) and batch size should be given in the fit function. So try this</p>

```<code>inputshape = (22,2000)

model.fit(X_train, y_train,
          batch_size=808,
          epochs=epochs,
          validation_data=(X_test,y_test),
          shuffle=True)
</code>```

Title: how to choose LSTM 2-d input shape?

Body:
First input shape must be (22,2000) and batch size should be given in the fit function. So try this

inputshape = (22,2000)

model.fit(X_train, y_train,
          batch_size=808,
          epochs=epochs,
          validation_data=(X_test,y_test),
          shuffle=True)


答:
What you do in the loop is equivalent to the following q code:

```<code>q)`:alpha set enlist`a`b!1 2
q)`:alpha upsert`a`b!1 2
q)show get`:alpha
a b
---
1 2
1 2
</code>```

There is nothing surprising here.  The set command saves a 1-row table (recall that in q a table is a list of dictionaries) in the file alpha, then the upsert command appends a row which is the same as the one saved and finally get reads the resulting 2-row table back.

What you probably want is to initialize the table outside of the loop, run a series of upserts in the loop and show the result after the loop.

Note that you can initialize the table like this:

```<code>>>> q.set(':alpha', q('!', ["Name","Bid","Ask","Time"], ()).flip)
k('`:alpha')
>>> q.get(':alpha').show()
Name Bid Ask Time
-----------------
</code>```

Finally, if your goal is to save the feed, it is rarely a good idea to write each message to the disk as soon as it arrives.  Most feed handlers collect a day worth of market data in memory and save it in HDB at the end of the day.

ContentLicense: CC BY-SA 4.0

Title: PyQ - q.upsert and q.set append to splayed kdb database

Body:
When I run the following code in pyq...

from bittrex.bittrex import Bittrex, API_V2_0
import time, json
from pyq import q, K

get_bittrex = Bittrex(None, None)
starttime = time.time()

market_result = get_bittrex.get_market_summaries()['result']

while True:
    for res in market_result:
        market_name = res['MarketName']
        ask = str(res['Ask'])
        bid = str(res['Bid'])
        last = str(res['Last'])
        timeStamp = str(res['TimeStamp'])
        if market_name in ['USDT-BTC', 'USDT-ETH', 'USDT-LTC']:
            mkt = {"Name": market_name,"Bid": bid,"Ask": ask,"Time":timeStamp}
            q.set(':alpha', [mkt])
            q.upsert(':alpha', mkt)
            q.get(':alpha').show()

    time.sleep(10.0)

it returns every 10 seconds to the console...

Name     Bid            Ask            Time
--------------------------------------------------------------
USDT-BTC 15475.00000001 15530.99999999 2017-12-09T02:46:52.547
USDT-BTC 15475.00000001 15530.99999999 2017-12-09T02:46:52.547
Name     Bid          Ask      Time
------------------------------------------------------
USDT-ETH 454.00000001 454.9999 2017-12-09T02:46:52.017
USDT-ETH 454.00000001 454.9999 2017-12-09T02:46:52.017
Name     Bid          Ask          Time
----------------------------------------------------------
USDT-LTC 133.76999998 133.98999999 2017-12-09T02:46:49.703
USDT-LTC 133.76999998 133.98999999 2017-12-09T02:46:49.703
Name     Bid            Ask            Time
--------------------------------------------------------------
USDT-BTC 15475.00000001 15530.99999999 2017-12-09T02:46:52.547
USDT-BTC 15475.00000001 15530.99999999 2017-12-09T02:46:52.547
Name     Bid          Ask      Time
------------------------------------------------------
USDT-ETH 454.00000001 454.9999 2017-12-09T02:46:52.017
USDT-ETH 454.00000001 454.9999 2017-12-09T02:46:52.017
Name     Bid          Ask          Time
----------------------------------------------------------
USDT-LTC 133.76999998 133.98999999 2017-12-09T02:46:49.703
USDT-LTC 133.76999998 133.98999999 2017-12-09T02:46:49.703

Why does it print each line 2x? Also, how can I modify this so each market_name is added to the same table, i.e., it's currently printing each market_name to it's own table instead of appending to the existing table.

Ideal output would like like the following...

Name     Bid            Ask            Time
--------------------------------------------------------------
USDT-BTC 15475.00000001 15530.99999999 2017-12-09T02:46:52.547
USDT-ETH 454.00000001 454.9999 2017-12-09T02:46:52.017
USDT-LTC 133.76999998 133.98999999 2017-12-09T02:46:49.703

Body:
What you do in the loop is equivalent to the following q code:

q)`:alpha set enlist`a`b!1 2
q)`:alpha upsert`a`b!1 2
q)show get`:alpha
a b
---
1 2
1 2

There is nothing surprising here.  The set command saves a 1-row table (recall that in q a table is a list of dictionaries) in the file alpha, then the upsert command appends a row which is the same as the one saved and finally get reads the resulting 2-row table back.

What you probably want is to initialize the table outside of the loop, run a series of upserts in the loop and show the result after the loop.

Note that you can initialize the table like this:

>>> q.set(':alpha', q('!', ["Name","Bid","Ask","Time"], ()).flip)
k('`:alpha')
>>> q.get(':alpha').show()
Name Bid Ask Time
-----------------

Finally, if your goal is to save the feed, it is rarely a good idea to write each message to the disk as soon as it arrives.  Most feed handlers collect a day worth of market data in memory and save it in HDB at the end of the day.


问:
Show data from database in ajax
I want to show data from database into ajax.

function Data_Table() {
  $.ajax( {
    url: "<?php echo site_url('admin-spot/company/FieldTable')?>", type: "GET", dataType: "JSON", success: function(data) {
      $('#map').dataSrc(data.map);
    }
  }
  );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="map" src="" frameborder="0" style="width: 100%; height: 300px;" allowfullscreen></iframe></code>```

答:
As far as i understand from your hard to judge description and the comments section, you are trying to set the src attribute of the iframe
 with the googlemap link in the ajax success function and the src is coming from server-side, if this is it you have to use .prop to assign the src  which should be a URL

change your function to the following

```<code> function Data_Table() {

        $.ajax({
            url: "<?php echo site_url('admin-spot/company/FieldTable')?>",
            type: "GET",
            dataType: "JSON",
            success: function (data) {

                $('#map').prop('src',
                    data.map
                );
            }
        });
    }
</code>```

Title: Show data from database in ajax

Body:
As far as i understand from your hard to judge description and the comments section, you are trying to set the src attribute of the iframe
 with the googlemap link in the ajax success function and the src is coming from server-side, if this is it you have to use .prop to assign the src  which should be a URL

change your function to the following

 function Data_Table() {

        $.ajax({
            url: "<?php echo site_url('admin-spot/company/FieldTable')?>",
            type: "GET",
            dataType: "JSON",
            success: function (data) {

                $('#map').prop('src',
                    data.map
                );
            }
        });
    }


问:
Changing constraints constants
I have a function that anchors the views to other views easily without having to write a lot of code. The function is called like this:

```<code>    view.anchor(top: NSLayoutYAxisAnchor?,
    left: NSLayoutXAxisAnchor?,
    bottom: NSLayoutYAxisAnchor?,
    right: NSLayoutXAxisAnchor?,
    topConstant:CGFloat?,
    leftConstant: CGFloat?,
    bottomConstant: CGFloat?,
    rightConstant: CGFloat?,
    widthConstant: CGFloat?,
    heightConstant: CGFloat?)
</code>```

Basically I just put in anchors for other views, add constants if needed and adjust width and height. All parameters are optional

This works great and it saves lots of space and code, however at the moment I want to change the heightConstant in one of my views and the only way that I have seen people changing constraints is by creating a variable for each constraint like this:

```<code>var heightConstraint = view.heightAnchor.constraint(equalTo: 20, multiplier: 1)
</code>```

and then change it later on by accessing the variable.

Is there any other way of updating constraints other than this way or do I have to get rid of my function and start using variables

答:
I'd recommend that you start using variables to save the constraints.

You could go digging around in the constraints variable on your view, find the right constraint there, and then update it, but that is imo messy code.

Title: Changing constraints constants

Body:
I have a function that anchors the views to other views easily without having to write a lot of code. The function is called like this:

    view.anchor(top: NSLayoutYAxisAnchor?,
    left: NSLayoutXAxisAnchor?,
    bottom: NSLayoutYAxisAnchor?,
    right: NSLayoutXAxisAnchor?,
    topConstant:CGFloat?,
    leftConstant: CGFloat?,
    bottomConstant: CGFloat?,
    rightConstant: CGFloat?,
    widthConstant: CGFloat?,
    heightConstant: CGFloat?)

Basically I just put in anchors for other views, add constants if needed and adjust width and height. All parameters are optional

This works great and it saves lots of space and code, however at the moment I want to change the heightConstant in one of my views and the only way that I have seen people changing constraints is by creating a variable for each constraint like this:

var heightConstraint = view.heightAnchor.constraint(equalTo: 20, multiplier: 1)

and then change it later on by accessing the variable.

Is there any other way of updating constraints other than this way or do I have to get rid of my function and start using variables


问:
Entityframework 6.2.0 IQueryable.Count VS IQueryable.ToList().Count
This is a very weird problem
In short

```<code>var q = (some query).Count();
</code>```

Gives my a number and

```<code>var q = (some query).ToList().Count();
</code>```

Gives me entirely different number...

with mentioning that (some query) has two includes (joins)

is there a sane explanation for that???

EDIT: here is my query

```<code>var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).Count();
</code>```

this gives me a wrong number

and this:

```<code>var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).ToList().Count();
</code>```

Gives me accurate number..

EDIT 2
Wher I wrote my query as linq query it worked perfectly...

```<code>var q1 = (from d in db.membership_renewals where d.isDeleted == false join m in db.members on d.mr_memberId equals m.m_id join s in db.sports on d.mr_sportId equals s.s_id select d.mr_id).Count();
</code>```

I think the problem that entity framework doesn't execute the joins in the original query but forced to execute them in (ToList())...

答:
My guess is IQueryable gives a smaller number cause not all the objects are loaded, kind of like a stream in Java, but IQueryable.toList().count() forces the Iqueryable to load all the data and it is traversed by the list constructor and stored in the list so IQueryable.toList().Count() is the accurate answer. This is based on 5 minutes of search on MSDN.

The idea is the underlying datastore of the IQueryable is a database iterator so it executes differently every time because it executes the query again on the database, so if you call it twice against the same table, and the data has changed you get different results. This is called delayed execution. But when you say IQueryable.ToList() you force the iterator to do the whole iteration once and dump the results in a list which is constant

Body:
This is a very weird problem
In short

var q = (some query).Count();

Gives my a number and

var q = (some query).ToList().Count();

Gives me entirely different number...

with mentioning that (some query) has two includes (joins)

is there a sane explanation for that???

EDIT: here is my query

var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).Count();

this gives me a wrong number

and this:

var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).ToList().Count();

Gives me accurate number..

EDIT 2
Wher I wrote my query as linq query it worked perfectly...

var q1 = (from d in db.membership_renewals where d.isDeleted == false join m in db.members on d.mr_memberId equals m.m_id join s in db.sports on d.mr_sportId equals s.s_id select d.mr_id).Count();

I think the problem that entity framework doesn't execute the joins in the original query but forced to execute them in (ToList())...


问:
Is std::ifstream significantly slower than FILE?
I've been informed that my library is slower than it should be, on the order of 30+ times too slow parsing a particular file (text file, size 326 kb). The user suggested that it may be that I'm using std::ifstream (presumably instead of FILE).

I'd rather not blindly rewrite, so I thought I'd check here first, since my guess would be the bottleneck is elsewhere. I'm reading character by character, so the only functions I'm using are get(), peek(), and tellg()/seekg().

Update:

I profiled, and got confusing output - gprof didn't appear to think that it took so long. I rewrote the program to read the entire file into a buffer first, and it sped up by about 100x. I think the problem may have been the tellg()/seekg() that took a long time, but gprof may have been unable to see that for some reason. In any case, ifstream does not appear to buffer the entire file, even for this size.

答:
I don't think that'd make a difference. Especially if you're reading char by char, the overhead of I/O is likely to completely dominate anything else.
Why do you read single bytes at a time? You know how extremely inefficient it is?

On a 326kb file, the fastest solution will most likely be to just read it into memory at once.

The difference between std::ifstream and the C equivalents, is basically a virtual function call or two. It may make a difference if executed a few tens of million times per second, otherwise, not reall. file I/O is generally so slow that the API used to access it doesn't really matter. What matters far more is the read/write pattern. Lots of seeks are bad, sequential reads/writes good.

OwnerDisplayName: Jesse Beder

LastEditorDisplayName: Jesse Beder

OwnerDisplayName: jalf


问:
high order component throws an invalid react element error (reactjs)
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

```<code>const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};
</code>```

And then I'm using this HOC as an alias of <Route /> component like this:

```<code><BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

EDIT:

But this approach works fine:

```<code>const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

答: I’m not very familiar with the syntax you wrote. But spotted one thing. Your parameter is component but inside you are using Component which in this context is undefined</p>

Body:
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};

And then I'm using this HOC as an alias of <Route /> component like this:

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>

EDIT:

But this approach works fine:

const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>


问:
.net core 2 entity framework migrations not working
I'm having a problem with adding a database migration in .net core 2.0.
I'm getting the following error:

```<code>An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:83:19)
    at __webpack_require__ (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:20:30)
    at createWebpackDevServer (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:62:26)
    at C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:114:19
    at IncomingMessage.<anonymous> (C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:133:38)
    at emitNone (events.js:86:13)
Current directory is: D:\Projects\Jeroen Fiers\Projecten\Fiers\bin\MCD\Debug\netcoreapp2.0
)
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
</code>```

My Program.cs is adjusted to the following:

```<code>public class Program{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
</code>```

The strange part is that the migrations have worked before (one time).

答:
for Example if you have 2 project in your solution as : UiProject & DataProject

first set your ui project as startup. then in powershell goto the your DataAccess project then:

```<code>1: dotnet ef migrations add firstMigrate --startup-project ./UiProject
2: dotnet ef database update --startup-project ./UiProject
</code>```

Body:
I'm having a problem with adding a database migration in .net core 2.0.
I'm getting the following error:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:83:19)
    at __webpack_require__ (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:20:30)
    at createWebpackDevServer (C:\Users\Dries\AppData\Local\Temp\quzf2u2y.rt0:62:26)
    at C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:114:19
    at IncomingMessage.<anonymous> (C:\Users\Dries\AppData\Local\Temp\00o3h05d.izo:133:38)
    at emitNone (events.js:86:13)
Current directory is: D:\Projects\Jeroen Fiers\Projecten\Fiers\bin\MCD\Debug\netcoreapp2.0
)
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

My Program.cs is adjusted to the following:

public class Program{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

The strange part is that the migrations have worked before (one time).

Body:
for Example if you have 2 project in your solution as : UiProject & DataProject

first set your ui project as startup. then in powershell goto the your DataAccess project then:

1: dotnet ef migrations add firstMigrate --startup-project ./UiProject
2: dotnet ef database update --startup-project ./UiProject


问:
strang "reduce" behavior in python2.7
I am writing a program to merge list of dictionary:

```<code>li = [{u'1234': [[1512734546591, 1512734552591]]}, {}, {}, {}]

reduce(lambda a, b: a.items() + b.items(), [l for l in li])
</code>```

then it shows error

AttributeError: 'list' object has no attribute 'items'

why ?

答:
Think about the result of a.items() + b.items() for the first iteration. What is the type of the result? The result is passed into the lambda as a on the next iteration.

It's a list. On the next iteration, a will be a list (the result of the previous a.items() + b.items()) and b will be a dict. At this point, a.items() is attempting to access the items attribute of a list, of which there is none.

Title: strang "reduce" behavior in python2.7

Body:
I am writing a program to merge list of dictionary:

li = [{u'1234': [[1512734546591, 1512734552591]]}, {}, {}, {}]

reduce(lambda a, b: a.items() + b.items(), [l for l in li])

then it shows error

AttributeError: 'list' object has no attribute 'items'

why ?


答:
It should be  :

```<code>const AuthRoute = (Component ) => { // <-- Component which refers to PrivateComponent
  class AuthComponent extends React.Component {  // <-- React.Component
     ....
</code>```

and Not :

```<code>const AuthRoute = ({ component: Component }) => {

    class AuthComponent extends Component {
      ...
</code>```

Also check out my other answer to have elegant HOC .

Title: high order component throws an invalid react element error (reactjs)

Body:
It should be  :

const AuthRoute = (Component ) => { // <-- Component which refers to PrivateComponent
  class AuthComponent extends React.Component {  // <-- React.Component
     ....

and Not :

const AuthRoute = ({ component: Component }) => {

    class AuthComponent extends Component {
      ...

Also check out my other answer to have elegant HOC .


问:
What is the difference of the anonymous internal class directly call the external class instance method in the OpenJDK and Oracle?
Today, I reviewed same Android code, and found a strange phenomenon.

It is the anonymous internal class directly called the external class instance method.

In my mind, directly calling a method is equivalent to adding this directly before the method, and this is an instance of an inner class.

According to this logic, an instance of an external class is invoked directly in the anonymous inner class, that will caused the compile ERROR.

But actually compile this application, and no problem. And the running log is normal.

Therefore, writing a simple Demo to verify the previous concept is wrong. code show as below:

```<code>public class InnerClass {
    public static void main(String[] args) {
        new InnerClass().process();
    }

    public void process() {
        new Thread() {
            @Override
            public void run() {
                System.out.println(toString("test"));
            }
        }.start();
    }

    public String toString(String string) {
        return string;
    }
}
</code>```

In the Oracle:

In the OpenJDK:

So, What is the difference of the anonymous internal class directly call the external class instance method in the OpenJDK and Oracle?

Where can I find documentation to see these differences?

I worked hard, but did not get a clear answer.

Thanks.

P.S.

In According to my point of view

```<code>public class InnerClass {
    public static void main(String[] args) {
        new InnerClass().process();
    }

    public void process() {
        new Thread() {
            @Override
            public void run() {
                // In According to my point of view
                // toString("test")
                // <==>
                // this.toString("test")
                // and `this` is the instance of Thread
                // what's the error of my view?
                System.out.println(toString("test"));
            }
        }.start();
    }

    public String toString(String string) {
        return string;
    }
}
</code>```

答:
The problem is that

```<code>        public void run() {
            System.out.println(toString("test"));
        }
</code>```

is calling toString on the anonymous Thread subclass, and that is Thread::toString().  There is no Thread::toString(String), and the toString(String) method from the enclosing scope is not considered.

The JLS states that it will only check an enclosing / outer class for a method if there is no method with the required name in the inner class.  See JLS 15.12.1:

If the form is MethodName, that is, just an Identifier, then:

If the Identifier appears in the scope of a visible method declaration
  with that name (§6.3, §6.4.1), then:

If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or
  interface to search is T.

This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking
  for methods in an enclosing class and its superclass hierarchy. See
  §6.5.7.1 for an example.

As to why OpenJDK Java 7 accepts your test class .... if that is actually true, I'd call that a compiler bug.  But it would be a general Java 7 bug not an OpenJDK specific one.  The javac codebases are (AFAIK) identical for Oracle and OpenJDK releases of the same version.

Interestingly, I have a copy of Oracle Java 6, and javac from that version also calls this a compilation error as well.

```<code>$ /usr/java/jdk1.6.0_45/bin/javac InnerClass.java
InnerClass.java:10: cannot find symbol
symbol: method toString(java.lang.String)
                System.out.println(toString("test"));
                                   ^
1 error
</code>```

So ... maybe ... you should rerun your OpenJDK Java 7 test, and make sure you are compiling the same source code!

Body:
Today, I reviewed same Android code, and found a strange phenomenon.

It is the anonymous internal class directly called the external class instance method.

In my mind, directly calling a method is equivalent to adding this directly before the method, and this is an instance of an inner class.

According to this logic, an instance of an external class is invoked directly in the anonymous inner class, that will caused the compile ERROR.

But actually compile this application, and no problem. And the running log is normal.

Therefore, writing a simple Demo to verify the previous concept is wrong. code show as below:

public class InnerClass {
    public static void main(String[] args) {
        new InnerClass().process();
    }

    public void process() {
        new Thread() {
            @Override
            public void run() {
                System.out.println(toString("test"));
            }
        }.start();
    }

    public String toString(String string) {
        return string;
    }
}

In the Oracle:

In the OpenJDK:

So, What is the difference of the anonymous internal class directly call the external class instance method in the OpenJDK and Oracle?

Where can I find documentation to see these differences?

I worked hard, but did not get a clear answer.

Thanks.

P.S.

In According to my point of view

public class InnerClass {
    public static void main(String[] args) {
        new InnerClass().process();
    }

    public void process() {
        new Thread() {
            @Override
            public void run() {
                // In According to my point of view
                // toString("test")
                // <==>
                // this.toString("test")
                // and `this` is the instance of Thread
                // what's the error of my view?
                System.out.println(toString("test"));
            }
        }.start();
    }

    public String toString(String string) {
        return string;
    }
}

Body:
The problem is that

        public void run() {
            System.out.println(toString("test"));
        }

is calling toString on the anonymous Thread subclass, and that is Thread::toString().  There is no Thread::toString(String), and the toString(String) method from the enclosing scope is not considered.

The JLS states that it will only check an enclosing / outer class for a method if there is no method with the required name in the inner class.  See JLS 15.12.1:

If the form is MethodName, that is, just an Identifier, then:

If the Identifier appears in the scope of a visible method declaration
  with that name (§6.3, §6.4.1), then:

If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or
  interface to search is T.

This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking
  for methods in an enclosing class and its superclass hierarchy. See
  §6.5.7.1 for an example.

As to why OpenJDK Java 7 accepts your test class .... if that is actually true, I'd call that a compiler bug.  But it would be a general Java 7 bug not an OpenJDK specific one.  The javac codebases are (AFAIK) identical for Oracle and OpenJDK releases of the same version.

Interestingly, I have a copy of Oracle Java 6, and javac from that version also calls this a compilation error as well.

$ /usr/java/jdk1.6.0_45/bin/javac InnerClass.java
InnerClass.java:10: cannot find symbol
symbol: method toString(java.lang.String)
                System.out.println(toString("test"));
                                   ^
1 error

So ... maybe ... you should rerun your OpenJDK Java 7 test, and make sure you are compiling the same source code!


问:
ORA-02253: constraint specification not allowed here - foreign key
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

```<code>CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);
</code>```

答:
Try This:</p>

```<code>CREATE TABLE CLIENTE(
   RUT              VARCHAR2(10)  NOT NULL,
   NOMBRE           VARCHAR2(20)  NOT NULL,
   APELLIDOP        VARCHAR2(30)  NOT NULL,
   APELLIDOM        VARCHAR2(30)  NOT NULL,
   DIRECCION        VARCHAR2(100) NOT NULL,
   TELEFONO         NUMBER(8)     NOT NULL,
   EMAIL            VARCHAR2(255) NOT NULL,
   FECHA_NACIMIENTO DATE          NOT NULL,
   SEXO             CHAR(1)       NOT NULL,
   COD_CIUDAD       NUMBER(3)
);

ALTER TABLE CLIENTE
  ADD CONSTRAINT CLIENTE_PK PRIMARY KEY (RUT)
  USING INDEX;

ALTER TABLE CLIENTE
  ADD CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
  REFERENCES [FOREIGN KEY TABLE NAME] ([PRIMARY KEY COLUMN OF FOREIGN KEY TABLE]);
</code>```

Body:
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);

Body:
Try This:

CREATE TABLE CLIENTE(
   RUT              VARCHAR2(10)  NOT NULL,
   NOMBRE           VARCHAR2(20)  NOT NULL,
   APELLIDOP        VARCHAR2(30)  NOT NULL,
   APELLIDOM        VARCHAR2(30)  NOT NULL,
   DIRECCION        VARCHAR2(100) NOT NULL,
   TELEFONO         NUMBER(8)     NOT NULL,
   EMAIL            VARCHAR2(255) NOT NULL,
   FECHA_NACIMIENTO DATE          NOT NULL,
   SEXO             CHAR(1)       NOT NULL,
   COD_CIUDAD       NUMBER(3)
);

ALTER TABLE CLIENTE
  ADD CONSTRAINT CLIENTE_PK PRIMARY KEY (RUT)
  USING INDEX;

ALTER TABLE CLIENTE
  ADD CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
  REFERENCES [FOREIGN KEY TABLE NAME] ([PRIMARY KEY COLUMN OF FOREIGN KEY TABLE]);


问:
Replacing missing value with mean of 2 nearest rows in R
I have a datatable with missing value, and I want to replace it with the average of 2 nearest row.

```<code>library(data.table)
A <- data.table(id = c(1:10),
                Value = c(1:3,NA,5:10))

> A
    id Value
 1:  1     1
 2:  2     2
 3:  3     3
 4:  4    NA
 5:  5     5
 6:  6     6
 7:  7     7
 8:  8     8
 9:  9     9
10: 10    10
</code>```

For example, I want the NA to be replaced by the mean of row3 and row5, which is 4.

答:
na.approx in the zoo package does that.  If there can be leading or trailing NA values and you want to:

extend the nearest non-NA values add the rule = 2 argument to na.approx or

leave those as NA add the na.rm = FALSE argument to na.approx.

See ?na.approx for further arguments.  Other possibilities from the same package include na.spline (fill in with cubic spline fit), na.aggregate (mean of all non-NA values), na.locf (last value carried forward) and na.StructTS (seasonal Kalman filter).

```<code>library(zoo)

A[, list(Value = na.approx(Value))]
</code>```

giving:

```<code>    Value
 1:     1
 2:     2
 3:     3
 4:     4
 5:     5
 6:     6
 7:     7
 8:     8
 9:     9
10:    10
</code>```

Body:
I have a datatable with missing value, and I want to replace it with the average of 2 nearest row.

library(data.table)
A <- data.table(id = c(1:10),
                Value = c(1:3,NA,5:10))

> A
    id Value
 1:  1     1
 2:  2     2
 3:  3     3
 4:  4    NA
 5:  5     5
 6:  6     6
 7:  7     7
 8:  8     8
 9:  9     9
10: 10    10

For example, I want the NA to be replaced by the mean of row3 and row5, which is 4.

Body:
na.approx in the zoo package does that.  If there can be leading or trailing NA values and you want to:

extend the nearest non-NA values add the rule = 2 argument to na.approx or

leave those as NA add the na.rm = FALSE argument to na.approx.

See ?na.approx for further arguments.  Other possibilities from the same package include na.spline (fill in with cubic spline fit), na.aggregate (mean of all non-NA values), na.locf (last value carried forward) and na.StructTS (seasonal Kalman filter).

library(zoo)

A[, list(Value = na.approx(Value))]

giving:

    Value
 1:     1
 2:     2
 3:     3
 4:     4
 5:     5
 6:     6
 7:     7
 8:     8
 9:     9
10:    10


问:
How would I fix this multi-table query to select only the rows that are needed?
I'm trying to make a query that selects all messages from a specific user and all of that user's friends. This query almost works, but the first part causes issues because it ends up selecting all rows from 'friends.' I'm thinking I need to use some sort of JOIN for this to work as needed, but I don't have enough experience with JOINS to make this work after experimenting for over an hour now.</p>

```<code>SELECT a.*
  FROM messages a, friends b
 WHERE a.username = '$user' OR b.username = '$user' && b.friend = a.username
 ORDER BY a.id DESC
 LIMIT 5
</code>```

答:
```<code>SELECT a.*
  FROM messages a
 WHERE a.username = '$user'
    OR a.username in (SELECT b.friend FROM friends b WHERE b.username = '$user')
 ORDER BY a.id DESC
 LIMIT 5
</code>```

Body:
I'm trying to make a query that selects all messages from a specific user and all of that user's friends. This query almost works, but the first part causes issues because it ends up selecting all rows from 'friends.' I'm thinking I need to use some sort of JOIN for this to work as needed, but I don't have enough experience with JOINS to make this work after experimenting for over an hour now.

SELECT a.*
  FROM messages a, friends b
 WHERE a.username = '$user' OR b.username = '$user' && b.friend = a.username
 ORDER BY a.id DESC
 LIMIT 5


问:
SourceTree - rebase - Errors During Merge
I'm trying to do something simple like editing the commit message for a previous commit.

Checking git status I have:

```<code>nothing to commit, working directory clean
</code>```

I then click on the commit and do SourceTree > Repository > Interactive Rebase...

but get this dialog box, and a completely blank/empty description area:

Note: I read somewhere that this might be due to FileMerge creating a .orig backup file. However, looking through FileMerge preferences I don't see anything about backup files

答:
Push a remote version of the branch you want to rebase

SourceTree is attempting to present you the local commits that have been made on top of the remote branch.

If the remote branch does not exist, SourceTree doesn't know which commit to use as the "parent" of the rebase.

When you get this extremely unhelpful blank error, the issue is that your current branch does not have a remote. Or perhaps that your local branch is up to date with the remote, and you thus have no commits to rebase.

Push a remote version of your branch at the commit you want to use as the parent of the rebase.

Body:
I'm trying to do something simple like editing the commit message for a previous commit.

Checking git status I have:

nothing to commit, working directory clean

I then click on the commit and do SourceTree > Repository > Interactive Rebase...

but get this dialog box, and a completely blank/empty description area:

Note: I read somewhere that this might be due to FileMerge creating a .orig backup file. However, looking through FileMerge preferences I don't see anything about backup files


问:
In retrieving JSON data, whats the point of having a completion block return Void?
So we have this function that retrieves JSON data and presents it in its completion block, what I'm trying to understand is why use the signature: ((Data) -> Void) instead of just (Data), is the void really necessary? Here is the function:

```<code> typealias JSONData = ((Data) -> Void)

  func getJSONData(type: String, urlExtension: String, completion: @escaping JSONData) {

    let request = URLRequest(url: URL(string:"\(baseURL)\(type)/\(urlExtension)?api_key=\(apiKey)&region=US&append_to_response=videos,images,releases")! )

    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in

      if error == nil {
        if let httpResponse = response as? HTTPURLResponse {
          switch (httpResponse.statusCode) {
          case 200:
            if let data = data {
              completion(data)
            }
          default:
            print(httpResponse.statusCode)
          }
        }
      } else {

        DispatchQueue.main.async {

          if let error = error {
            print("Error: \(error.localizedDescription)") }
          return
        }
      }
    })
    dataTask.resume()
  }
</code>```

答:
Swift syntax dictates that you must declare closures with a return type after the ->.

You have two options:

typealias JSONData = (Data) -> Void

typealias JSONData = (Data) -> ()

I see Apple using #1 most frequently.

Body:
So we have this function that retrieves JSON data and presents it in its completion block, what I'm trying to understand is why use the signature: ((Data) -> Void) instead of just (Data), is the void really necessary? Here is the function:

 typealias JSONData = ((Data) -> Void)

  func getJSONData(type: String, urlExtension: String, completion: @escaping JSONData) {

    let request = URLRequest(url: URL(string:"\(baseURL)\(type)/\(urlExtension)?api_key=\(apiKey)&region=US&append_to_response=videos,images,releases")! )

    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in

      if error == nil {
        if let httpResponse = response as? HTTPURLResponse {
          switch (httpResponse.statusCode) {
          case 200:
            if let data = data {
              completion(data)
            }
          default:
            print(httpResponse.statusCode)
          }
        }
      } else {

        DispatchQueue.main.async {

          if let error = error {
            print("Error: \(error.localizedDescription)") }
          return
        }
      }
    })
    dataTask.resume()
  }


问:
Android Device Monitor not opening
I am unable to run Android Monitor. I am using Android Studio.  Not Eclipse.

When I attempt to open it in the terminal using  sudo ./monitor, I see the following warning, then it shows

WARNING: An illegal reflective access operation has occurred WARNING:
  Illegal reflective access by
  org.eclipse.osgi.internal.baseadaptor.BaseStorage
  (file:/Users/kidus11/Library/Android/sdk/tools/lib/monitor-x86_64/plugins/org.eclipse.osgi_3.8.2.v20130124-134944.jar)
  to method java.net.URLClassLoader.addURL(java.net.URL) WARNING: Please
  consider reporting this to the maintainers of
  org.eclipse.osgi.internal.baseadaptor.BaseStorage WARNING: Use
  --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be
  denied in a future release

I have Java version 9, as well has Javac 9

I have installed the latest version of JDK or JRE

Here is the tag I see every time I try to open Android Device Monitor

!ENTRY org.eclipse.osgi 4 0 2017-10-04 20:18:12.531 !MESSAGE
  Application error !STACK 1 java.lang.IllegalStateException: Unable to
  acquire application service. Ensure that the org.eclipse.core.runtime
  bundle is resolved and started (see config.ini).  at
  org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:74)
    at
  org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at
  org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at
  java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method)   at
  java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)   at
  org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)  at
  org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)     at
  org.eclipse.equinox.launcher.Main.run(Main.java:1438)

Any help would be greatly appreciated!

答:
Newest Android Studio Bundle comes with its own JRE (under <ANDROID_STUDIO>/jre and this is the recommended JRE to work with (look at File / Project Structure / SDK Location).

Likewise, a simple option is to create a symbolic link under the monitor tools to keep JRE in line with Android Studio even getting an update.

For MAC or Linux:

```<code>#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86_64/jre
</code>```

32 bits:

```<code>#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86/jre
</code>```

Then the ddms monitor works for both ways:  from Studio IDE (Tools / Android / ADM) or command line  (<SDK>tools/./monitor)

Title: Android Device Monitor not opening

Body:
Newest Android Studio Bundle comes with its own JRE (under <ANDROID_STUDIO>/jre and this is the recommended JRE to work with (look at File / Project Structure / SDK Location).

Likewise, a simple option is to create a symbolic link under the monitor tools to keep JRE in line with Android Studio even getting an update.

For MAC or Linux:

#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86_64/jre

32 bits:

#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86/jre

Then the ddms monitor works for both ways:  from Studio IDE (Tools / Android / ADM) or command line  (<SDK>tools/./monitor)


问:
How to run Apple Accelerate fft algorithms with data length, which is not power of 2?
I want to port an algorithm from Android to iOS written in C. For Android I use fftw3 library. And it is able to run the algorithm on input data with any size. For example the size I see in debug is 14996. And It's pretty efficient. And when I read the docs from here: https://developer.apple.com/documentation/accelerate/1449739-vdsp_dft_zrop_createsetup?language=objc I see that there are some spesific requirements for input length. Are there any way to avoid this or to modify the input data to meet the requirements?</p>

答:
Sorry, no, the Accelerate DFT routines only support the documented sizes. Only powers of two multiplied by 1, 3, 5, or 15 are supported.

(These include sizes that have been useful previously. It is possible to support other sizes in the future if we get sufficient requests for them, but 14996 seems unusual. Usually numbers with only small prime factors are preferred, but 14996 has a factor of 151. What makes it a size that is interesting to take a DFT for?)

As for modifying your input data, some applications will pad their data with zeroes to make it a supported length. But then adjustments may need to be made, depending on the application.

You can, of course, also use FFTW on iOS.


问:
Does MongoDB supports TLS1.2 version or above?
This is regarding security part of MongoDB.

I saw the documentation of MongoDB and found that it supports TLS 1.0 & 1.1.

May I know does MongoDB supports TLS 1.2 version or above?

答:
Yes, it does, for a while now. It's mentioned here in a MongoDB blog post on May 21, 2014:

In order to protect the network traffic, SSL/TLS should be enabled
  between clients and the server and in between servers. MongoDB
  supports TLS 1.0, 1.1 and 1.2, all SSL versions are disabled. Enabling
  TLS is well described in the security documentation.

See Source on GitHub.


问:
How do I use reduce() to mimic the capabilities of forEach()?
I'm trying to accomplish a task with reduce() that I know how to do with forEach().  Unfortunately I'm not sure how to structure the syntax and I can't find a good example.

Example 1) In this code I use forEach() to insert the word species into the first index of each array.

"use strict";

var creatureArray;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureArray.forEach(function(value, index, array) {
  array[index].unshift('species');
});

console.log(creatureArray);```
</div>
</div>
</p>

<p><strong>Example 2)</strong> In this code I try to accomplish something similar using <code>.reduce()</code>.  However I know that I'm missing a piece of syntax. I can't figure out how to apply the updated array to the accumulator which is then returned as an object.  Thanks so much for any help!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function(accumulator, currentValue, index, array) {
  array[index].unshift('species');
  //what goes here?
  return accumulator;
}, {});

console.log(creatureObject);</code>```

答:
map is more apropriate in this case:

var creatureArray = [ ['zombie'  , 30, 1, 'bite' , 0,  5],
                      ['skeleton', 10, 2, 'sword', 1, 10],
                      ['orc'     , 15, 4, 'club' , 1,  7] ]

var creatureObject = creatureArray.map(currentValue => ['species', ...currentValue] )

console.log( JSON.stringify( creatureObject ).replace(/],/g, '],\n ') )```

Body:
I'm trying to accomplish a task with reduce() that I know how to do with forEach().  Unfortunately I'm not sure how to structure the syntax and I can't find a good example.

Example 1) In this code I use forEach() to insert the word species into the first index of each array.

"use strict";

var creatureArray;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureArray.forEach(function(value, index, array) {
  array[index].unshift('species');
});

console.log(creatureArray);

Example 2) In this code I try to accomplish something similar using .reduce().  However I know that I'm missing a piece of syntax. I can't figure out how to apply the updated array to the accumulator which is then returned as an object.  Thanks so much for any help!

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function(accumulator, currentValue, index, array) {
  array[index].unshift('species');
  //what goes here?
  return accumulator;
}, {});

console.log(creatureObject);


问:
read in .txt file than split it into 3 columns
(Edited)Pretty new at this R stuff but I find it very interesting. Trying to follow  this tutorial. OK so what I am trying to do is some text manipulation like strip white space, convert case, filter stop words but first I want to read it into a dataframe that contains 3 columns.
I am trying to read in the data in this zip file=

http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/smsspamcollection.zip

which is a .txt file of ham and spam messages. I want to split it up into three columns "ID", "Text" , "Class" . "ID" being the unique identifier of the String, "Text" is the actual message, and "Class" is the "ham" or "spam" classifiers of the messages.

What I have so far is ...

```<code>dat = readLines("SMSSpamCollection.txt")
dat = as.data.frame(do.call(rbind, strsplit(dat, split="\t")),
                                                 stringsAsFactors=FALSE)
names(dat) = c("ID", "Class" , "Text")
</code>```

This does read it into the dataframe but it does not recognise the index as the "ID" column ,Any help?

答: This file does not contain identifiers. It has only two variables, 'Class' and 'Text'. The names would be 'Class' and 'Text'.</p>

Body:
(Edited)Pretty new at this R stuff but I find it very interesting. Trying to follow  this tutorial. OK so what I am trying to do is some text manipulation like strip white space, convert case, filter stop words but first I want to read it into a dataframe that contains 3 columns.
I am trying to read in the data in this zip file=

http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/smsspamcollection.zip

which is a .txt file of ham and spam messages. I want to split it up into three columns "ID", "Text" , "Class" . "ID" being the unique identifier of the String, "Text" is the actual message, and "Class" is the "ham" or "spam" classifiers of the messages.

What I have so far is ...

dat = readLines("SMSSpamCollection.txt")
dat = as.data.frame(do.call(rbind, strsplit(dat, split="\t")),
                                                 stringsAsFactors=FALSE)
names(dat) = c("ID", "Class" , "Text")

This does read it into the dataframe but it does not recognise the index as the "ID" column ,Any help?


问:
python-valve rcon minecraft 'ConnectionRefusedError: [Errno 111] Connection refused'
I am trying to connect to RCON on a minecraft server hosted on my own network using python-valve. My code is as follows(Keep in mind it is only accessible on my network, hence my connection to localhost):

```<code>import valve.rcon
def rconsendCMD():
    address = ("127.0.0.1", 25575)
    valve.rcon.execute(address,"jeff","time set night")
</code>```

That code, according to the documentation, should work fine yet it returns:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "bot.py", line 90, in on_message
    rconsendCMD()
  File "bot.py", line 43, in rconsendCMD
    valve.rcon.execute(address,"jeff","time set night")
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 630, in execute
    with RCON(address, password) as rcon:
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 325, in __enter__
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 464, in wrapper
    return function(instance, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 464, in wrapper
    return function(instance, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 483, in connect
    self._socket.connect(self._address)
ConnectionRefusedError: [Errno 111] Connection refused
</code>```

The documentation for 'valve.rcon.execute()' can be found here

答: I found out the problem. I am hosting the server on a seperate machine from what I'm executing the python code on. I tried to send it to connect to localhost rather than my private address within my network. Answer found here</p>

Body:
I am trying to connect to RCON on a minecraft server hosted on my own network using python-valve. My code is as follows(Keep in mind it is only accessible on my network, hence my connection to localhost):

import valve.rcon
def rconsendCMD():
    address = ("127.0.0.1", 25575)
    valve.rcon.execute(address,"jeff","time set night")

That code, according to the documentation, should work fine yet it returns:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "bot.py", line 90, in on_message
    rconsendCMD()
  File "bot.py", line 43, in rconsendCMD
    valve.rcon.execute(address,"jeff","time set night")
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 630, in execute
    with RCON(address, password) as rcon:
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 325, in __enter__
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 464, in wrapper
    return function(instance, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 464, in wrapper
    return function(instance, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/valve/rcon.py", line 483, in connect
    self._socket.connect(self._address)
ConnectionRefusedError: [Errno 111] Connection refused

The documentation for 'valve.rcon.execute()' can be found here


问:
I got this error: Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'
I got this code:

```<code>double[][] ou = new double[h][w];

for(i=0;i<h;i++)
   for(int j=0;j<w;j++)
      ou[i][j] = sortie[z++];

return ou;
</code>```

And I get this 2 errors:

```<code>Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'
</code>```

referred to "return ou"

```<code>Error 2: Invalid rank specifier: expected ',' or ']'
</code>```

referred to "double[][] ou = new double[h][w];"

EDIT:
I try to convert a code from Java to C# and that is were I have                  "double[][] ou = new double[h][w];"

答:
What you want to create is a multidimentional array but are creating a Jagged array which is an Array of Array. Look at this SO question for differences.

Multidimentional Arrays and Jagged Array

So in first line itself you cant create an array with new double[h][w] which is not allowed

you need to creae the array like this

```<code>double[,] array = new double [h,w];
</code>```

and access elements like this

```<code>array[i,j] = somevalue;
</code>```

Body:
I got this code:

double[][] ou = new double[h][w];

for(i=0;i<h;i++)
   for(int j=0;j<w;j++)
      ou[i][j] = sortie[z++];

return ou;

And I get this 2 errors:

Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'

referred to "return ou"

Error 2: Invalid rank specifier: expected ',' or ']'

referred to "double[][] ou = new double[h][w];"

EDIT:
I try to convert a code from Java to C# and that is were I have                  "double[][] ou = new double[h][w];"

Body:
What you want to create is a multidimentional array but are creating a Jagged array which is an Array of Array. Look at this SO question for differences.

Multidimentional Arrays and Jagged Array

So in first line itself you cant create an array with new double[h][w] which is not allowed

you need to creae the array like this

double[,] array = new double [h,w];

and access elements like this

array[i,j] = somevalue;


问:
RNFetchBlob blob not being removed after close()
I am uploading an image from the local (ios) filesystem to Firebase using RNFetchBlob

Although my image is being deleted, my blob is remaining in the filesystem after closing it.
I tried unlinking the blob but it still remains

```<code>function createBlob(uri, mediaType) {
  const Blob = RNFetchBlob.polyfill.Blob;
  const typePrefix = isImage(mediaType) ? 'image' : 'video';
  window.Blob = Blob;
  window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;

  return new Promise((resolve, reject) => {
    const uid = guid();
    const mediaRef = firebase.storage().ref('users').child(`${uid}.${mediaType}`);
    let uploadBlob = null;

    Blob.build(uri, { type: `${typePrefix}/${mediaType}` })
    .then((blob) => {
      uploadBlob = blob;
      return mediaRef.put(blob, { type: `${typePrefix}/${mediaType}` });
    })
    .then((response) => {
      uploadBlob.close();

      resolve(response);
    })
    .catch(error => {
      reject(error);
    });
  });
}
</code>```

This is how it looks in my simulator folder after closing the blob

After the createBlob I am deleting the file from local storage using RNFetchBlob.fs.unlink(path)

答:
I don't think you're close() is working because the uploadBlob variable was created in the previous closure, but not passed on to the next .then block. I'm thinking this might work...

```<code>Blob.build(uri, { type: `${typePrefix}/${mediaType}` })
.then((blob) => {
  uploadBlob = blob;
  return ({
     response: mediaRef.put(blob, { type: `${typePrefix}/${mediaType}` }),
     blob: uploadBlob
})
.then(({response, blob}) => {
  blob.close();

  resolve(response);
})
</code>```

Body:
I am uploading an image from the local (ios) filesystem to Firebase using RNFetchBlob

Although my image is being deleted, my blob is remaining in the filesystem after closing it.
I tried unlinking the blob but it still remains

function createBlob(uri, mediaType) {
  const Blob = RNFetchBlob.polyfill.Blob;
  const typePrefix = isImage(mediaType) ? 'image' : 'video';
  window.Blob = Blob;
  window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;

  return new Promise((resolve, reject) => {
    const uid = guid();
    const mediaRef = firebase.storage().ref('users').child(`${uid}.${mediaType}`);
    let uploadBlob = null;

    Blob.build(uri, { type: `${typePrefix}/${mediaType}` })
    .then((blob) => {
      uploadBlob = blob;
      return mediaRef.put(blob, { type: `${typePrefix}/${mediaType}` });
    })
    .then((response) => {
      uploadBlob.close();

      resolve(response);
    })
    .catch(error => {
      reject(error);
    });
  });
}

This is how it looks in my simulator folder after closing the blob

After the createBlob I am deleting the file from local storage using RNFetchBlob.fs.unlink(path)

Body:
I don't think you're close() is working because the uploadBlob variable was created in the previous closure, but not passed on to the next .then block. I'm thinking this might work...

Blob.build(uri, { type: `${typePrefix}/${mediaType}` })
.then((blob) => {
  uploadBlob = blob;
  return ({
     response: mediaRef.put(blob, { type: `${typePrefix}/${mediaType}` }),
     blob: uploadBlob
})
.then(({response, blob}) => {
  blob.close();

  resolve(response);
})


问:
Can't get sound file to play in iOS
```<code>@IBAction func cowButton(_ sender: UIButton) {
    let soundFileSeleced : String = soundArray[0]
    print(soundFileSeleced)
    playSound()
}
func playSound() {
    let soundURL = Bundle.main.url(forResource: "cowSound", withExtension: ".wav")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    }
    catch {
        print(error)
    }
    audioPlayer.play()
}
</code>```

I can't get my sound to play. What's wrong with my code? I get the message:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

答:
Check your syntax on the let soundURL line. Pretty sure withExtension shouldn't have the . in it.

Try this?

let soundURL = Bundle.main.url(forResource: "cowSound", withExtension: "wav")

Title: Can't get sound file to play in iOS

Body:
@IBAction func cowButton(_ sender: UIButton) {
    let soundFileSeleced : String = soundArray[0]
    print(soundFileSeleced)
    playSound()
}
func playSound() {
    let soundURL = Bundle.main.url(forResource: "cowSound", withExtension: ".wav")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    }
    catch {
        print(error)
    }
    audioPlayer.play()
}

I can't get my sound to play. What's wrong with my code? I get the message:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"


问:
Is there a way to maintain a db relationship (pk/fk) in the following scenario
My current db design is in the screenshot. It seems flawed because there is no enforced relationship (pk/fk) between the t_criteria_director and the t_criteria_a b c d e f... tables.  Is there a better way to design this one to many scenario to keep referential integrity?

答:
Your design doesn't "seem" anything because we can't read your mind. You have given some aspects of a design but not the business "scenario" it represents/implements/describes or how it does so.

SQL NULL, UNIQUE, PKs & FKs are kinds of constraints. A constraint is a limitation on what database values can appear. An SQL FK says subrow values for a column list in a table must appear elsewhere for a column list whose columns form a SQL UNIQUE NOT NULL column set (which PK is a case of) in their table. If your design is subject to a constraint and it isn't implied by other enforced constraints, enforce it. Otherwise don't. Preferably declaratively. Most SQL DBMSs only let you declare a few kinds of cheap-to-enforce constraints. Others must be enforced via triggers.

The constraints are a consequence of the criteria for rows going into vs staying out of tables in a given situation (the table predicates, "what the tables mean") and what situations can & can't arise according to your business rules. We don't know what those are unless you tell us. We can hope to guess using your table & column names, any other info you give & common sense.

You have to tell us either the constraints or the predicates & what situations can/can't arise.

Here your tables are using a straightforward table plus some EAV design to record the data of some straightforward table not explicitly in your design. As always you could avoid EAV by just using DDL to keep the straightforward table's schema & constraints up to date, but instead you have chosen a static schema that requires more complex schema, queries & constraints. The straightforward expression of the EAV constraints is typically that the straightforward table they represent has certain constraints plus that the t_criteria_x are views of it and/or that it is a view of them. But typically the only SQL declarations available just let you express fragments of that.

I guess that what you intend here includes that for each t_criteria_x table its PK value must appear in t_criteria_director with a table_name value 't_criteria_x'. Another way to put this is that if you added to t_criteria_x a table_name column with value 't_criteria_x' then the result must have (id, table_name) subrows appear as t_criteria_director (criteria_id, table_name) subrows. If also t_criteria_director (criteria_id, table_name) subrows are SQL UNIQUE NOT NULL then we have that that augmented t_criteria_x has a composite SQL FK (id, table_name) referencing t_criteria_director (criteria_id, table_name). You can express this declaratively by actually augmenting t_criteria_x by such a (possibly computed/generated/calculated) columns. But you probably also have other constraints, like there aren't any (constraint_id, table_name) pairs in t_criteria_director that aren't referenced by some augmented t_constraint_x.

Calling the column table_name shows an implementation-oriented bias from the EAV because that column is a type/variant discriminator/tag in the ER sense that the types of entities represented by the ids in the t_criteria_x tables are "subtypes" of the type of entity represented by t_criteria_director. (This is also a concept/technique from 3GL record data structures used for dynamically simulating typing.) After all the table_name column value doesn't have to be a table name, it just has to be some value that identifies the entity subtype, and such entities don't have to only participate in one table's relationship/association. (Research SQL/database/ER subtyping/polymorphism/inheritance and the design anti-pattern two/many/multiple FKs [sic] to two/many/multiple tables.)

You have to determine what the table predicates are and what their constraints consequently are. Preferably via determining what the straightforward table they collectively represent is & what its predicate is and what the database constraints are using it. Then you must decide whether per cost/benefit you are going to modify your design to make constraints declarative and/or you are or are not going to enforce constraints via triggers.


问:
Why is `stack build` altering my .cabal file?
I am attempting to build a project which uses Euterpea.

Running stack build I get the following error, suggesting that I need to add Euterpea to the build-depends section of my .cabal file.

```<code>$ sb
composition-0.1.0.0: build (lib + exe)
Preprocessing library composition-0.1.0.0...
[2 of 2] Compiling Lib              ( src/Lib.hs, .stack-work/dist/x86_64-linux-nix/Cabal-1.24.2.0/build/Lib.o )

/home/matthew/backup/composition/composition/src/Lib.hs:5:1: error:
    Failed to load interface for ‘Euterpea’
    It is a member of the hidden package ‘Euterpea-2.0.4’.
    Perhaps you need to add ‘Euterpea’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package composition-0.1.0.0 using:
      /home/matthew/.stack/setup-exe-cache/x86_64-linux-nix/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-nix/Cabal-1.24.2.0 build lib:composition exe:composition-exe --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
</code>```

I add Euterpea there, and the library section of my .cabal file then is the following.

```<code>library
  hs-source-dirs:
      src
  build-depends:   base >= 4.7 && < 5
                 , Euterpea
  exposed-modules:
      Lib
  other-modules:
      Paths_composition
  default-language: Haskell2010
</code>```

However, when I then run stack build again, it gives the same error -- and changes my .cabal file back to what it was originally, with the library section then looking like

```<code>library
  hs-source-dirs:
      src
  build-depends:
      base >= 4.7 && < 5
  exposed-modules:
      Lib
  other-modules:
      Paths_composition
  default-language: Haskell2010
</code>```

Why is stack build altering my cabal file? I have never seen that occurring before.

Side note:
Not sure if it is related, but the .cabal file's format appears to be different than it normally does. Here as with previous projects I auto-initialized by running stack new <project-name>. I don't know what I might have done different from previous projects to cause this unexpected behavior of stack build.

答:
Make sure package.yaml exists in the root of your project directory.

package.yaml is a new file format to improve the syntax of cabal, converted by hpack.

Stack supports hpack as strongly as the stack build command automatically converts package.yaml into a cabal file with hpack command.

So, delete package.yaml or edit package.yaml to add Euterpea package.
Editing it would not be so difficult as its format is YAML.

Body:
I am attempting to build a project which uses Euterpea.

Running stack build I get the following error, suggesting that I need to add Euterpea to the build-depends section of my .cabal file.

$ sb
composition-0.1.0.0: build (lib + exe)
Preprocessing library composition-0.1.0.0...
[2 of 2] Compiling Lib              ( src/Lib.hs, .stack-work/dist/x86_64-linux-nix/Cabal-1.24.2.0/build/Lib.o )

/home/matthew/backup/composition/composition/src/Lib.hs:5:1: error:
    Failed to load interface for ‘Euterpea’
    It is a member of the hidden package ‘Euterpea-2.0.4’.
    Perhaps you need to add ‘Euterpea’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package composition-0.1.0.0 using:
      /home/matthew/.stack/setup-exe-cache/x86_64-linux-nix/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-nix/Cabal-1.24.2.0 build lib:composition exe:composition-exe --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1

I add Euterpea there, and the library section of my .cabal file then is the following.

library
  hs-source-dirs:
      src
  build-depends:   base >= 4.7 && < 5
                 , Euterpea
  exposed-modules:
      Lib
  other-modules:
      Paths_composition
  default-language: Haskell2010

However, when I then run stack build again, it gives the same error -- and changes my .cabal file back to what it was originally, with the library section then looking like

library
  hs-source-dirs:
      src
  build-depends:
      base >= 4.7 && < 5
  exposed-modules:
      Lib
  other-modules:
      Paths_composition
  default-language: Haskell2010

Why is stack build altering my cabal file? I have never seen that occurring before.

Side note:
Not sure if it is related, but the .cabal file's format appears to be different than it normally does. Here as with previous projects I auto-initialized by running stack new <project-name>. I don't know what I might have done different from previous projects to cause this unexpected behavior of stack build.


问:
How to define boost::any operator ==
I want to define operator == for boost::any in my project. Since the arguments belong to the boost namespace, this is where argument-dependent lookup will search for it. So, the signature is:

```<code>namespace boost
{
    bool operator == (const boost::any &, const boost::any &);
}
</code>```

However, this generates ambiguous overload errors whenever I include a boost library that compares enums for equality, such as thread/locks.hpp — the compiler sees no reason to prefer converting the enums to int and using the built-in comparison instead of converting them to boost::any and using mine.

I can hack around this by also including any such libraries in the same file as my comparator and defining custom operators for comparing boost's enums. But there got to be a better way, right?

答:
```<code>namespace boost {
  template<class T,
    typename std::enable_if<std::is_same<T, any>{}, bool>::type =true
  >
  bool operator == (const T& lhs, const T& rhs){
    return any_equal(lhs, rhs);
  }
}
</code>```

Title: How to define boost::any operator ==

Body:
I want to define operator == for boost::any in my project. Since the arguments belong to the boost namespace, this is where argument-dependent lookup will search for it. So, the signature is:

namespace boost
{
    bool operator == (const boost::any &, const boost::any &);
}

However, this generates ambiguous overload errors whenever I include a boost library that compares enums for equality, such as thread/locks.hpp — the compiler sees no reason to prefer converting the enums to int and using the built-in comparison instead of converting them to boost::any and using mine.

I can hack around this by also including any such libraries in the same file as my comparator and defining custom operators for comparing boost's enums. But there got to be a better way, right?


问:
JavaScript make a class's method static and available to its instances
How can you make a class's method static (available on the class itself) and accessible from its instances in JavaScript?

```<code>class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class
</code>```

答:
You can use the static keyword to do so.

```<code>class A {
    constructor(){}
    static method(){}
}

const x = new A();
</code>```

EDIT:

```<code>x.constructor.method(); // this is possible
A.method();
</code>```

In Javascript, static methods are bound to class and not instances, so they can only be called by atleast using the constructor. A.prototype handles instance methods whereas the function A handles it's attributes.

Body:
How can you make a class's method static (available on the class itself) and accessible from its instances in JavaScript?

class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class

Body:
You can use the static keyword to do so.

class A {
    constructor(){}
    static method(){}
}

const x = new A();

EDIT:

x.constructor.method(); // this is possible
A.method();

In Javascript, static methods are bound to class and not instances, so they can only be called by atleast using the constructor. A.prototype handles instance methods whereas the function A handles it's attributes.


问:
What is the rationale for limitations on pointer arithmetic or comparison?
In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

What are the reasons of such limitations?

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

答:
Since the C standard intends to cover the majority of processor architectures, it should also cover this one:
Imagine an architecture (I know one, but wouldn't name it) where pointers are not just plain numbers, but are like structures or "descriptors". Such a structure contains information about the object it points into (its virtual address and size) and the offset within it. Adding or subtracting a pointer produces a new structure with only the offset field adjusted; producing a structure with the offset greater than the size of the object is hardware prohibited. There are other restrictions (such as how the initial descriptor is produced or what are the other ways to modify it), but they are not relevant to the topic.</p>


问:
Can you write a concept for ContiguousIterator?
I know there is concept for ContiguousIterator in words specification sense, but I wonder if it can be written using C++20/C++17 Concepts TS syntax.

My problem with this is that unlike RandomAccessIterator ContiguousIterator  requires not just some operations like it+123 to work, but depends on runtime result of that operation.

答: No you cannot, not without a traits class or other helper, where types opt-in to being contiguous.</p>


问:
JSON NO_REFERENCES
I have just started using JSON...
I am using it in my project (Spring).
I am making JSON string using XStream...
I found in tutorial of XStream that using JSON, we have to set it's mode to NO_REFERENCES.
I tried out searching it's reason on various sites, but I didn't find it anywhere...
I tried removing it from my code...
But that also did not had any effect on my output...
So, tell me why we have to set it's mode to NO_REFERENCES?</p>

答: Because, as the tutorial says, JSON has no mechanism for handling references; duplicates must be explicitly written out. If both foo and bar point to baz, then baz will get written twice; once under foo and once under bar.

Title: JSON NO_REFERENCES


问:
Ajax/PHP long-polling results in 503 error
I'm playing around with AJAX long-polling and trying to read/update a simple counter (number) value in an MySQL cell by clicking on a button.

The PHP creates an infinite while loop and is checking if the value in the according cell has been modified (MySQL "current_timestamp", UNIX). If it has and the current_timestamp value is bigger then the timestamp the AJAX call was made, it's breaking the loop and sending the updated value and the updated current_timestamp to the client. The AJAX processes the data.

The Problem: It works but after a while I get a 503 error. I guess it's obviously the while loop or other open connections through multiple windows in other browsers (for testing).

PHP-File text.php:

```<code>// Connect to database
$con = mysql_connect('XX', 'XX', 'XX');

if (!$con)
{
    die('Error' . mysql_error());
}

mysql_select_db('X', $con);

// Get data
$query = mysqli_query("SELECT counter_value, last_modified FROM content WHERE X = 'X' ORDER BY X DESC");

// Start infinite loop
set_time_limit(0);

while (true)
{

    // The timestamp of the last ajax call = the last modified timestamp
    $last_ajax_call = $_GET['timestamp'];

    clearstatcache();

    // Get the value of the counter and the last modified timestamp
    while($row = mysql_fetch_array($query))
    {
        $counter_value = $row['counter_value'];
        $last_modified= strtotime($row['last_modified']);
    }

    // If the time of the last modified timestamp is bigger/later than the last ajax call
    if ($last_modified > $last_ajax_call)
    {

        $result = array(
            'counter_value' => $counter_value,
            'timestamp' => $last_modified
        );
        $json = json_encode($result);
        echo $json;

        break;

    // If not, try again in 3 seconds
    } else
    {
        sleep(3);
        continue;
    }
}

// Close database
mysql_close($con);
</code>```

AJAX Part in js-File:

```<code>function getContent()
{
// get timestamp of last modified stored in attribute. The initial/first timestamp attribute is set beforehand.
var timestamp = $('#timestamp').attr('data-timestamp');

    $.ajax(
    {
        type: 'GET',
        url: 'test.php',
        async: true,
        cache: false,
        data: {timestamp:timestamp},
        success: function(data){
            var obj = jQuery.parseJSON(data);
            $("#counter").text(obj.counter_value);
            $("#timestamp").attr("data-timestamp", obj.timestamp);

            getContent();
        }
   }
   );
}

getContent();
</code>```

So the result is a 503 error which goes away after ca. 10 Minutes and it's working again.

(Any typos/formatting might be the result of cleaning up the code.)
I just started learning PHP and JS, so there might be a few newbie mistakes or weird lines in there, please be nice. Any advice on optimising the code is very appreciated!

答:
It dies because PHP doesn't work the way you think it does.

You have intentionally put an infinite loop into your php in the assumption it will make your code keep looping around and rechecking the next GET request on each loop.

The reality is that the code is executed once for each request, and until execution of the code completes the server doesn't respond.

AJAX long polling requires no special handling in php, it's just an AJAX request in a loop. You might want to include a slight delay in your AJAX code otherwise your server will be hammered with requests.

To be honest this isn't what long polling is for, the idea of it is to update pages without any user interaction to display unread message notifications etc.

If you want to monitor user events like button clicks then bind your AJAX function to the clicking of the button.

Body:
I'm playing around with AJAX long-polling and trying to read/update a simple counter (number) value in an MySQL cell by clicking on a button.

The PHP creates an infinite while loop and is checking if the value in the according cell has been modified (MySQL "current_timestamp", UNIX). If it has and the current_timestamp value is bigger then the timestamp the AJAX call was made, it's breaking the loop and sending the updated value and the updated current_timestamp to the client. The AJAX processes the data.

The Problem: It works but after a while I get a 503 error. I guess it's obviously the while loop or other open connections through multiple windows in other browsers (for testing).

PHP-File text.php:

// Connect to database
$con = mysql_connect('XX', 'XX', 'XX');

if (!$con)
{
    die('Error' . mysql_error());
}

mysql_select_db('X', $con);

// Get data
$query = mysqli_query("SELECT counter_value, last_modified FROM content WHERE X = 'X' ORDER BY X DESC");

// Start infinite loop
set_time_limit(0);

while (true)
{

    // The timestamp of the last ajax call = the last modified timestamp
    $last_ajax_call = $_GET['timestamp'];

    clearstatcache();

    // Get the value of the counter and the last modified timestamp
    while($row = mysql_fetch_array($query))
    {
        $counter_value = $row['counter_value'];
        $last_modified= strtotime($row['last_modified']);
    }

    // If the time of the last modified timestamp is bigger/later than the last ajax call
    if ($last_modified > $last_ajax_call)
    {

        $result = array(
            'counter_value' => $counter_value,
            'timestamp' => $last_modified
        );
        $json = json_encode($result);
        echo $json;

        break;

    // If not, try again in 3 seconds
    } else
    {
        sleep(3);
        continue;
    }
}

// Close database
mysql_close($con);

AJAX Part in js-File:

function getContent()
{
// get timestamp of last modified stored in attribute. The initial/first timestamp attribute is set beforehand.
var timestamp = $('#timestamp').attr('data-timestamp');

    $.ajax(
    {
        type: 'GET',
        url: 'test.php',
        async: true,
        cache: false,
        data: {timestamp:timestamp},
        success: function(data){
            var obj = jQuery.parseJSON(data);
            $("#counter").text(obj.counter_value);
            $("#timestamp").attr("data-timestamp", obj.timestamp);

            getContent();
        }
   }
   );
}

getContent();

So the result is a 503 error which goes away after ca. 10 Minutes and it's working again.

(Any typos/formatting might be the result of cleaning up the code.)
I just started learning PHP and JS, so there might be a few newbie mistakes or weird lines in there, please be nice. Any advice on optimising the code is very appreciated!


问:
How to set a cell unconnectable dynamically？
I create cells with some ports:

How can I set the input-port unconnectable when the income-edges are more than the input-ports?

How to disable a cell connect with the cell of given type?

I find a class mxMultiplicity, it seems to be helpful, but I don't know how to use it.

The XML expression of the graph is like this. There are two kinds of cells, they have user object Table and Operation as value.

<mxGraphModel>
  <root>
    <mxCell id="0"/>
    <mxCell id="1" parent="0"/>
    <mxCell id="2" style="table" vertex="1" parent="1">

        <Array as="data">
          <add value="1"/>
          <add value="2"/>
          <add value="3"/>
        </Array>

      <mxGeometry x="90" y="50" width="50" height="50" as="geometry"/>
      <Array as="ports">
        <Object type="out" x="0.5" y="0.5" perimeter="1"/>
      </Array>
    </mxCell>
    <mxCell id="3" vertex="1" parent="1">
      <Operation name="add" portNumber="2" code="a + b" as="value"/>
      <mxGeometry x="150" y="180" width="90" height="50" as="geometry"/>
      <Array as="ports">
        <Object type="in" x="0.3" y="0" perimetry="1" as="add-in0"/>
        <Object type="in" x="0.6" y="0" perimetry="1" as="add-in1"/>
        <Object type="out" x="0.5" y="1" perimetry="1" as="add-out"/>
      </Array>
    </mxCell>
  </root>
</mxGraphModel>```

答:
I solved it by myself, hope the answer can help you if you have the same question.

I checked the code of mxMultiplicity.js, and tried to override the prototype function checkType. In this way, when it check if the teminal you connect with is the disable cell, if the value is an object, it will check if value is instance of the type.

mxMultiplicity.prototype.checkType = function(graph, value, type, attr, attrValue) {
            if (value != null) {
                if (typeof value == 'object') {
                    if (value instanceof type) {
                        return value[attr] == attrValue;
                    } else {
                        return false;
                    }
                } else if (!isNaN(value.nodeType)) {
                    return mxUtils.isNode(value, type, attr, attrValue);
                } else {
                    return value == type;
                }
            }
            return false;
        }```
</div>
</div>
</p>

<p>The connection rule can be this, and <code>Table</code> is my constructor.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>graph.multiplicities.push(new mxMultiplicity(
    false, Table, null, null, 0, 0, null,
    'can not input to table', 'null'
));</code>```

Body:
I solved it by myself, hope the answer can help you if you have the same question.

I checked the code of mxMultiplicity.js, and tried to override the prototype function checkType. In this way, when it check if the teminal you connect with is the disable cell, if the value is an object, it will check if value is instance of the type.

mxMultiplicity.prototype.checkType = function(graph, value, type, attr, attrValue) {
            if (value != null) {
                if (typeof value == 'object') {
                    if (value instanceof type) {
                        return value[attr] == attrValue;
                    } else {
                        return false;
                    }
                } else if (!isNaN(value.nodeType)) {
                    return mxUtils.isNode(value, type, attr, attrValue);
                } else {
                    return value == type;
                }
            }
            return false;
        }

The connection rule can be this, and Table is my constructor.

graph.multiplicities.push(new mxMultiplicity(
    false, Table, null, null, 0, 0, null,
    'can not input to table', 'null'
));


问:
How do we connect our docker app to a locally running postgres?
I'm looking for a way to connect a docker container app so it can access Postgres database via https://postgresapp.com/

Was wondering if there are certain ports to open and what the yml file would look like to enable docker-compose to work with locally running postgres.

Thanks!

答:
You have to make changes in postgres config files in host machine, especially

1) pg_hba.conf
2) postgres.conf

You can find above configuration in /var/lib/postgresql/[version]/ path

First check your docker0 bridge interface  it might be 172.17.0.0/16, if not change accordingly.

make changes in postgresql.conf path will be same as pg_hba.conf.

listenaddress to "*"

Then in pg_hba.conf add rule as

host all all 172.17.0.0/16 md5.

Then in docker application use host ip address to connect to postures running in host.


问:
UITextField password mode show dot immediately when typing
We can set secureTextEntry property on UITextField to hide password. But there is a problem, when typing a number/letter,the textField would show the typing letter/number for a while before it becomes dot. What I want is when user types, the letter/number must immediately become dot. How can I achieve that, can anyone help me?

答:
I don't think you can change that behavior by because it is built into UITextField. You could try to peek inside the class and see if there are any variables that you can mess with, but such code easily breaks after iOS updates.

You could use a font that has dots instead, and leave secureTextEntry on false.