问:
Struggling with a UnhandledPromiseRejectionWarning
I'm struggling to see where the promise rejection is emerging in the following:

```<code>MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)
                return (db, missing);
            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });
</code>```

What I see in the console is

```<code>making promises: function
making promises2
RAW RES []
RES:  undefined
Final Err: undefined
(node:7026) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'close' of undefined
(node:7026) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

I have two questions:

why is RES undefined - I would expect it to be []

why am I ending up at "Final Err" as there should be no rejections occuring in this script

答:
So the error was that I was returning - as Dominik stated:

```<code>return (db, missing);
</code>```

That should have been

```<code>return {db, missing};
</code>```

But in my .then I was pattern matching for

```<code>{db, results}
</code>```

and results could not be found as I was returning a field called missing

Body:
I'm struggling to see where the promise rejection is emerging in the following:

MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)
                return (db, missing);
            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });

What I see in the console is

making promises: function
making promises2
RAW RES []
RES:  undefined
Final Err: undefined
(node:7026) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'close' of undefined
(node:7026) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I have two questions:

why is RES undefined - I would expect it to be []

why am I ending up at "Final Err" as there should be no rejections occuring in this script

Body:
So the error was that I was returning - as Dominik stated:

return (db, missing);

That should have been

return {db, missing};

But in my .then I was pattern matching for

{db, results}

and results could not be found as I was returning a field called missing


来源: stackexchange

问:
how to call stored procedure in EF6 with output parameters
i have a stored procedure which returns a parameter containing string in it i don't know how to call it and get the output parameter to show on my view

```<code>ALTER PROCEDURE [dbo].[sp_test]
@room_type varchar(40)
,@room_price_min float
,@room_price_max    float
,@room_number   varchar(30)
,@new varchar(50) output
as
;
--select @room_no
if exists(select room_number from Rooms_ms where room_number=@room_number)
begin
    set @new='Room Already Exists'
    select @new
    return
end

insert into Rooms_ms(room_type,room_price_min,room_price_max,room_number) values
(@room_type,@room_price_min,@room_price_max,@room_number)

set @new='Successfully'
select  @new
return
</code>```

I'm trying to catch it like below but don't know how to exactly do it.

```<code> var result=   db.sp_test(a, b, 0, c);
</code>```

Thank you

答:
You can implement the following to retrieve the data for a stored procedure call

```<code>using(var db = new iConext())
 {
   var details = db.Database.SqlQuery<iType>("exec iProc @param", new SqlParameter("@param", iValue));
 }
</code>```

iType is int or string or long or can be a ComplexType

@param is one or more required parameters

iContext is for your db connection

ContentLicense: CC BY-SA 3.0

Body:
i have a stored procedure which returns a parameter containing string in it i don't know how to call it and get the output parameter to show on my view

ALTER PROCEDURE [dbo].[sp_test]
@room_type varchar(40)
,@room_price_min float
,@room_price_max    float
,@room_number   varchar(30)
,@new varchar(50) output
as
;
--select @room_no
if exists(select room_number from Rooms_ms where room_number=@room_number)
begin
    set @new='Room Already Exists'
    select @new
    return
end

insert into Rooms_ms(room_type,room_price_min,room_price_max,room_number) values
(@room_type,@room_price_min,@room_price_max,@room_number)

set @new='Successfully'
select  @new
return

I'm trying to catch it like below but don't know how to exactly do it.

 var result=   db.sp_test(a, b, 0, c);

Thank you

Body:
You can implement the following to retrieve the data for a stored procedure call

using(var db = new iConext())
 {
   var details = db.Database.SqlQuery<iType>("exec iProc @param", new SqlParameter("@param", iValue));
 }

iType is int or string or long or can be a ComplexType

@param is one or more required parameters

iContext is for your db connection


问:
How to display 1000 000 as 1Million
How can i implement 'k' or 'm' prefixer to my code? I am not sure how to add it to my code.

i want the number 1000 to display as 1k how can i make the prefixer in my code. can someone please help me add it to my code please.

答:
```<code>if (number >= 1000000) {
    document.write((number / 1000000).toFixed(2) + "M")
}
else if (number >= 1000) {
    document.write((number / 1000).toFixed(2) + "K");
}
else {
    document.write(number)
}
</code>```

Title: How to display 1000 000 as 1Million


问:
OpenCV 2.4 VideoCapture not working on Windows
I'm using Python bindings to OpenCV 2.4 installed with following instructions.

My problem is similar to this one, but I need Windows machine solution.

Problem: when I try to use

```<code>cap = cv2.VideoCapture(0)
print cap.grab()
</code>```

it works fine, but the following code

```<code>cap = cv2.VideoCapture(filename)
print cap.grab()
</code>```

always return False.

Path to the file is correct, absolute and has no spaces.

I tried on two machines with Windows XP and Windows 7 with similar results. On Linux (Ubuntu) it works fine for me.

答:
For anaconda environment
copy opencv_ffmpeg249_64.dll from C:\Python27\
rename its version according to your opencv correct version
and past it to
C:\Users\KHALID\Anaconda2\Library\bin

Body:
I'm using Python bindings to OpenCV 2.4 installed with following instructions.

My problem is similar to this one, but I need Windows machine solution.

Problem: when I try to use

cap = cv2.VideoCapture(0)
print cap.grab()

it works fine, but the following code

cap = cv2.VideoCapture(filename)
print cap.grab()

always return False.

Path to the file is correct, absolute and has no spaces.

I tried on two machines with Windows XP and Windows 7 with similar results. On Linux (Ubuntu) it works fine for me.


问:
Adding/updating 'news' to an app without updating the app
I am attempting to create a simple app by using html/css in Cordova. However I am stuck in one area and that is updating the news page content. I don't really know what method I can use to achieve this without having to update the whole app and resubmitting onto the store and I don't really know what I need to google to get the answer so I thought I would ask here and hopefully someone can help me out?

Thank you.

答: Basically you need to have some sort of server where you would store your news content and later download it through API to your app.</p>


问:
Jquery: Closest() div remove not working
Jquery closest div remove not working i found same question on stackoverflow but these answered not resolve my problem

closest div remove js fiddle here

```<code><script>
$(document).ready(function(){
    var counter = 4;
    var name = 1;
    var qty = 1;
    var price = 1;
    $('#addproduct').click(function() {
        $('#dynamicInput').append('<div class="clearfix"></div><div class="pdd" id="dlt"><div class="col-sm-3"><div class="row">' + (counter++)+' <label>Product Name</label></div></div><div class="col-sm-3"><div class="row"><select name="productnm'+(name++)+'"><option>Select Product</option><option>Rice</option><option>Fried Rice</option><option>Biryani</option></select></div></div><div class="col-sm-3"><div class="row"><label>Quantity</label></div></div><div class="col-sm-1 row"><div class="row qunatity-number"><input type="number" name="qunatity'+(qty++)+'" value="1" /></div></div><div class="col-sm-2"><div class="row qunatity-totalprice"><input type="text" name="totalprice'+(price++)+'" placeholder="Total Price" disabled /></div></div><a class="deleter" ><i class="fa fa-trash-o" aria-hidden="true"></i></a></div> ');
    });
    $('.deleter').click(function(){
       $(this).closest("#dlt").remove();
     });

});

</script>
</code>```

答:
Here is the solution for you https://jsfiddle.net/woeot0L4/1/

```<code>$(document).on('click', '.deleter',function(){
   $(this).parent().remove();
});
</code>```

Since you are appending the deleter class element dynamically, click will not work. Either you need to bind an event to the class or use document on click.

Body:
Here is the solution for you https://jsfiddle.net/woeot0L4/1/

$(document).on('click', '.deleter',function(){
   $(this).parent().remove();
});

Since you are appending the deleter class element dynamically, click will not work. Either you need to bind an event to the class or use document on click.


问:
How can fetch data from json through php?
I have a json context, i want some data from that json, My json is

```<code>{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}
{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}
</code>```

I need action and api_url data from json. I try something and i get upto

```<code> {"config": {"action": "test", "user_id": "219096271813", "endpoint_url": "http://debasisa.testbase.info/demo-push.php", "webhook_id": "430339"}, "api_url": "https://www.dem.com/{api-endpoint-to-fetch-object-details}/"}
</code>```

But i have no idea, how to get action and api_url value from this content in PHP.

答:
Try this</p>

```<code>$level1 = '{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}';
$data = json_decode($level1);
$newdata = json_decode($data->req_payload);
$action = $newdata->config->action;
</code>```

Body:
I have a json context, i want some data from that json, My json is

{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}
{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}

I need action and api_url data from json. I try something and i get upto

 {"config": {"action": "test", "user_id": "219096271813", "endpoint_url": "http://debasisa.testbase.info/demo-push.php", "webhook_id": "430339"}, "api_url": "https://www.dem.com/{api-endpoint-to-fetch-object-details}/"}

But i have no idea, how to get action and api_url value from this content in PHP.

Body:
Try this

$level1 = '{
"req_payload": "{\"config\": {\"action\": \"test\", \"user_id\": \"219096271813\", \"endpoint_url\": \"http:\/\/debasisa.testbase.info\/demo-push.php\", \"webhook_id\": \"430339\"}, \"api_url\": \"https:\/\/www.demo.com\/{api-endpoint-to-fetch-object-details}\/\"}"
}';
$data = json_decode($level1);
$newdata = json_decode($data->req_payload);
$action = $newdata->config->action;


问:
expected `;' before "pennies"? C++ Debugging (Code Completed)
Can anyone tell me why I get an error on my last cout?

```<code>#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}
</code>```

答:
As well as the missing <<, your penn, five, ten, twentyfive and fifty string variables are all out of scope by the time you get to that cout.

You can't do this:

```<code>if (quarters >= 1)
{
    string twentyfive = " quarters.";
}
else
{
    string twentyfive = " quarter.";
}
</code>```

As the string no longer exists when it leaves the scope of those braces.
If you want to do it like that you need to declare the variable outside the braces first.

```<code>string twentyfive = " quarter.";
if (quarters >= 1)
{
    twentyfive = " quarters.";
}
</code>```

Or use the ternary operator to neaten it up:

```<code>string twentyfive = (quarters > 1 ? " quarters." : " quarter.");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Can anyone tell me why I get an error on my last cout?

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}

Body:
As well as the missing <<, your penn, five, ten, twentyfive and fifty string variables are all out of scope by the time you get to that cout.

You can't do this:

if (quarters >= 1)
{
    string twentyfive = " quarters.";
}
else
{
    string twentyfive = " quarter.";
}

As the string no longer exists when it leaves the scope of those braces.
If you want to do it like that you need to declare the variable outside the braces first.

string twentyfive = " quarter.";
if (quarters >= 1)
{
    twentyfive = " quarters.";
}

Or use the ternary operator to neaten it up:

string twentyfive = (quarters > 1 ? " quarters." : " quarter.");


问:
Total Physical Memory retrieved from Win32_ComputerSystem doesn't match with DirectX tool value
I am trying to retrieve the total physical memory available value of my machine through Win32_OperatingSystem class in C#. Below is how I am retrieving this value.

```<code> ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
        ManagementObjectCollection moc = mc.GetInstances();
        if (moc.Count != 0)
        {
            foreach (ManagementObject MO in mc.GetInstances())
            {
                try
                {
                    computerSystemDetails["TotalPhysicalMemory"] = (MO["TotalPhysicalMemory"] == null) ? new string[] { } : new string[] { MO["TotalPhysicalMemory"].ToString() };
                }
                catch (Exception ex)
                {
                    logger.Error("GetSystemDetails", "Error occurred when retrieving the computer system information", ex);
                }
            }
        }
        return computerSystemDetails;
</code>```

The value I'm getting from the above is 16243 MB. But when I use DirectX Diagnostic tool I am getting the value 16384MB. What is the explanation for this difference? Please advice.

答:
The documentation for that property explains why:

Be aware that, under some circumstances, this property may not return an accurate value for the physical memory. For example, it is not accurate if the BIOS is using some of the physical memory. For an accurate value, use the Capacity property in Win32_PhysicalMemory instead.

Body:
I am trying to retrieve the total physical memory available value of my machine through Win32_OperatingSystem class in C#. Below is how I am retrieving this value.

 ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
        ManagementObjectCollection moc = mc.GetInstances();
        if (moc.Count != 0)
        {
            foreach (ManagementObject MO in mc.GetInstances())
            {
                try
                {
                    computerSystemDetails["TotalPhysicalMemory"] = (MO["TotalPhysicalMemory"] == null) ? new string[] { } : new string[] { MO["TotalPhysicalMemory"].ToString() };
                }
                catch (Exception ex)
                {
                    logger.Error("GetSystemDetails", "Error occurred when retrieving the computer system information", ex);
                }
            }
        }
        return computerSystemDetails;

The value I'm getting from the above is 16243 MB. But when I use DirectX Diagnostic tool I am getting the value 16384MB. What is the explanation for this difference? Please advice.


问:
No module Flask.ext.paginate using python
I'm trying to test the following code on Github  https://github.com/rohitsakala/CassandraRestfulAPI by following the instructions, unfortunately the execution does not work, and I have the following errors :

Thank's

答: That error is what you would see if the version of Python that you're using to run your server doesn't have flask_paginate installed. Try running pip install -U flask_paginate.


问:
TYPO3 Repository completely deleting
I have typo3 version 7.6.18. $this->someRepository->remove($object);
it's just set delete = 1 in DB. I need remove completely, using repository query. Is it possible? How to do it ? </p>

答: Just avoid defining delete option in ctrl section of TCA for your table. This is the flag that toggles "soft deletion" which is what you are encountering.

Title: TYPO3 Repository completely deleting


问:
Load lib files in production
I've upgraded one of my apps from Rails 4.2.6 to Rails 5.0.0. The Upgrade Guide says, that the Autoload feature is now disabled in production by default.

Now I always get an error on my production server since I load all lib files with autoload in the application.rb file.

```<code>module MyApp
    class Application < Rails::Application
        config.autoload_paths += %W( lib/ )
    end
end
</code>```

For now, I've set the config.enable_dependency_loading to true but I wonder if there is a better solution to this. There must be a reason that Autoloading is disabled in production by default.

答:
I just used config.eager_load_paths instead of config.autoload_paths like mention akostadinov on github comment:
https://github.com/rails/rails/issues/13142#issuecomment-275492070

```<code># config/application.rb
...
# config.autoload_paths << Rails.root.join('lib')
config.eager_load_paths << Rails.root.join('lib')
</code>```

It works on development and production environment.

Thanks Johan for suggestion to replace #{Rails.root}/lib with Rails.root.join('lib')!

ContentLicense: CC BY-SA 4.0

Title: Load lib files in production

Body:
I've upgraded one of my apps from Rails 4.2.6 to Rails 5.0.0. The Upgrade Guide says, that the Autoload feature is now disabled in production by default.

Now I always get an error on my production server since I load all lib files with autoload in the application.rb file.

module MyApp
    class Application < Rails::Application
        config.autoload_paths += %W( lib/ )
    end
end

For now, I've set the config.enable_dependency_loading to true but I wonder if there is a better solution to this. There must be a reason that Autoloading is disabled in production by default.

Body:
I just used config.eager_load_paths instead of config.autoload_paths like mention akostadinov on github comment:
https://github.com/rails/rails/issues/13142#issuecomment-275492070

# config/application.rb
...
# config.autoload_paths << Rails.root.join('lib')
config.eager_load_paths << Rails.root.join('lib')

It works on development and production environment.

Thanks Johan for suggestion to replace #{Rails.root}/lib with Rails.root.join('lib')!


答:
```<code>$output = json_decode($input);
</code>```

You can use $output->req_payload->config->action and $outout->api_url if your JSON is a single object. If it is an array, then you will have to iterate its elements. And if it is like the one you have shown in your question, then it is invalid JSON.

Title: How can fetch data from json through php?

Body:
$output = json_decode($input);

You can use $output->req_payload->config->action and $outout->api_url if your JSON is a single object. If it is an array, then you will have to iterate its elements. And if it is like the one you have shown in your question, then it is invalid JSON.


问:
./configure: error: the HTTP gzip module requires the zlib library
I am new to dockers/containers.

I am trying to run a fork with a fix I have put in for openSSL vulnerability of mup-frontend using the following command:

```<code>docker build ./
</code>```

It compiles to a point then errors with

```<code>./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.
</code>```

I am running a mac so installed zlib with brew. I have searched long and hard but cannot find much on this error.

Because of this error it also fails to build on automation in docker.io

答:
The Dockerfile you reference at

https://github.com/meteorhacks/mup-frontend-server/blob/master/Dockerfile

starts with

FROM debian

so you will need to have such a line in your Dockerfile, before the place where you need zlib

RUN apt-get update && apt-get install -y \
    zlib \
    --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*

in one RUN, you update, install and clean

Body:
I am new to dockers/containers.

I am trying to run a fork with a fix I have put in for openSSL vulnerability of mup-frontend using the following command:

docker build ./

It compiles to a point then errors with

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

I am running a mac so installed zlib with brew. I have searched long and hard but cannot find much on this error.

Because of this error it also fails to build on automation in docker.io


问:
Element removing while collection iterating
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

```<code>    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }
</code>```

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

答:
There is usually a better way to do this rather than use iterator.remove(). e.g. in your case, the loop is the same as

```<code>if(list.size()> 5) list.remove(5);
</code>```

If you do need to use iterator.remove() you can still use a for loop.

```<code>for(Iterator iterator = list.iterator(); iterator.hasNext();) {
    final Object o = iterator.next();

    if (++count == 5)
       iterator.remove();

    o.toString();
}
</code>```

Body:
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

Body:
There is usually a better way to do this rather than use iterator.remove(). e.g. in your case, the loop is the same as

if(list.size()> 5) list.remove(5);

If you do need to use iterator.remove() you can still use a for loop.

for(Iterator iterator = list.iterator(); iterator.hasNext();) {
    final Object o = iterator.next();

    if (++count == 5)
       iterator.remove();

    o.toString();
}


问:
Is Event Sourcing applicable for batch inputs?
I have a use case where the inputs to the application comes in batches of XML files. For example, a nightly batch of bank transactions. I am trying to see if I can use event sourcing to create a log of events. Based on what I read so far, the examples seems to be based on user driven input (click streams, updates from a user interface etc.,). Is event sourcing using a distributed log mechanism(like Kafka) a valid approach for batch/file based inputs?

Below is the approach I would like to take:

Accept input as a batch in file/xml

Run some basic validations in the memory.

Convert the batch input into a series of events

Write the event log to a Kafka topic(s).

Use the event log to store the data into the database, send the events
to a search engine, update caches, run spark jobs to do aggregations
etc.,

Repeat the process for other incoming batches.

If this approach is not efficient, what other options are available for distributed processing of such inputs?

答:
Are your inputs coming from something that looks like an event storage? I.e. a database that acts as an immutable source of truth, of append only events.

If that is the case, you have the foundation to use event sourcing, and additionally CQRS. (They're not the same thing)

What you would have to realize is that the so called write side / command side... has already been done for you.

The incoming batch of XML files with transactions... each transaction is an event already. It doesn't sound like you need to convert these to events, to then put these into Kafka. You can just map these to something you can put into Kafka, and then all subscribers of the topics can do stuff accordingly.

Effectively you would be implementing the read side of Event Sourcing + CQRS.

In practical terms, unless you are going to be doing things on the write side (where the xml files are generated / where user input is received)... I wouldn't worry too much about the subtleties of event sourcing as it relates to DDD and CQRS. I would simply think of what you're doing as a way to distribute your data to multiple services.

And make sure to consider how caches, search engines, etc. will only be updated whenever you get those XML files.


问:
Working of malloc in C
I am a beginner with C. I am wondering, how's malloc working.
Here is a sample code, I wrote on while trying to understand it's working.

CODE:

```<code>#include<stdio.h>
#include<stdlib.h>
int main() {
  int i;
  int *array = malloc(sizeof *array);
  for (i = 0; i < 5; i++) {
    array[i] = i+1;
  }
  printf("\nArray is: \n");
  for (i = 0; i < 5; i++) {
    printf("%d ", array[i]);
  }
  free(array);
  return 0;
}
</code>```

OUTPUT:

```<code>Array is:
1 2 3 4 5
</code>```

In the program above, I have only allocated space for 1 element, but the array now holds 5 elements. So as the programs runs smoothly without any error, what is the purpose of realloc().

Could anybody explain why?

Thanks in advance.

答:
This is typical undefined behavior (UB).

You are not allowed to code like that. As a beginner, think it is a mistake, a fault, a sin, something very dirty etc.

Could anybody explain why?

If you need to understand what is really happening (and the details are complex) you need to dive into your implementation details (and you don't want to). For example, on Linux, you could study the source code of your C standard library, of the kernel, of the compiler, etc. And you need to understand the machine code generated by the compiler (so with GCC compile with gcc -S -O1 -fverbose-asm to get an .s assembler file).

See also this (which has more references).

Read as soon as possible Lattner's blog on What Every C programmer should know about undefined behavior. Every one should have read it!

The worst thing about UB is that sadly, sometimes, it appears to "work" like you want it to (but in fact it does not).

So learn as quickly as possible to avoid UB systematically.

BTW, enabling all warnings in the compiler might help (but perhaps not in your particular case). Take the habit to compile with gcc -Wall -Wextra -g if using GCC.

Notice that your program don't have any arrays. The array variable is a pointer (not an array) so is very badly named. You need to read more about pointers and C dynamic memory allocation.

```<code> int *array = malloc(sizeof *array); //WRONG
</code>```

is very wrong. The name array is very poorly chosen (it is a pointer, not an array; you should spend days in reading what is the difference - and what do "arrays decay into pointers" mean). You allocate for a sizeof(*array) which is exactly the same as sizeof(int) (and generally 4 bytes, at least on my machine). So you allocate space for only one int element. Any access beyond that (i.e. with any even small positive index, e.g. array[1] or array[i] with some positive i) is undefined behavior. And you don't even test against failure of malloc (which can happen).

If you want to allocate memory space for (let's say) 8 int-s, you should use:

```<code>int* ptr = malloc(sizeof(int) * 8);
</code>```

and of course you should check against failure, at least:

```<code>if (!ptr) { perror("malloc"); exit(EXIT_FAILURE); };
</code>```

and you need to initialize that array (the memory you've got contain unpredictable junk), e.g.

```<code>for (int i=0; i<8; i++) ptr[i] = 0;
</code>```

or you could clear all bits (with the same result on all machines I know of) using

```<code>memset(ptr, 0, sizeof(int)*8);
</code>```

Notice that even after a successful such malloc (or a failed one) you always have sizeof(ptr) be the same (on my Linux/x86-64 box, it is 8 bytes), since it is the size of a pointer (even if you malloc-ed a memory zone for a million int-s).

In practice, when you use C dynamic memory allocation you need to know conventionally the allocated size of that pointer. In the code above, I used 8 in several places, which is poor style. It would have been better to at least

```<code>  #define MY_ARRAY_LENGTH 8
</code>```

and use MY_ARRAY_LENGTH everywhere instead of 8, starting with

```<code> int* ptr = malloc(MY_ARRAY_LENGTH*sizeof(int));
</code>```

In practice, allocated memory has often a runtime defined size, and you would keep somewhere (in a variable, a parameter, etc...) that size.

Study the source code of some existing free software project (e.g. on github), you'll learn very useful things.

Read also (perhaps in a week or two) about flexible array members. Sometimes they are very useful.

Title: Working of malloc in C

Body:
I am a beginner with C. I am wondering, how's malloc working.
Here is a sample code, I wrote on while trying to understand it's working.

CODE:

#include<stdio.h>
#include<stdlib.h>
int main() {
  int i;
  int *array = malloc(sizeof *array);
  for (i = 0; i < 5; i++) {
    array[i] = i+1;
  }
  printf("\nArray is: \n");
  for (i = 0; i < 5; i++) {
    printf("%d ", array[i]);
  }
  free(array);
  return 0;
}

OUTPUT:

Array is:
1 2 3 4 5

In the program above, I have only allocated space for 1 element, but the array now holds 5 elements. So as the programs runs smoothly without any error, what is the purpose of realloc().

Could anybody explain why?

Thanks in advance.

Body:
This is typical undefined behavior (UB).

You are not allowed to code like that. As a beginner, think it is a mistake, a fault, a sin, something very dirty etc.

Could anybody explain why?

If you need to understand what is really happening (and the details are complex) you need to dive into your implementation details (and you don't want to). For example, on Linux, you could study the source code of your C standard library, of the kernel, of the compiler, etc. And you need to understand the machine code generated by the compiler (so with GCC compile with gcc -S -O1 -fverbose-asm to get an .s assembler file).

See also this (which has more references).

Read as soon as possible Lattner's blog on What Every C programmer should know about undefined behavior. Every one should have read it!

The worst thing about UB is that sadly, sometimes, it appears to "work" like you want it to (but in fact it does not).

So learn as quickly as possible to avoid UB systematically.

BTW, enabling all warnings in the compiler might help (but perhaps not in your particular case). Take the habit to compile with gcc -Wall -Wextra -g if using GCC.

Notice that your program don't have any arrays. The array variable is a pointer (not an array) so is very badly named. You need to read more about pointers and C dynamic memory allocation.

 int *array = malloc(sizeof *array); //WRONG

is very wrong. The name array is very poorly chosen (it is a pointer, not an array; you should spend days in reading what is the difference - and what do "arrays decay into pointers" mean). You allocate for a sizeof(*array) which is exactly the same as sizeof(int) (and generally 4 bytes, at least on my machine). So you allocate space for only one int element. Any access beyond that (i.e. with any even small positive index, e.g. array[1] or array[i] with some positive i) is undefined behavior. And you don't even test against failure of malloc (which can happen).

If you want to allocate memory space for (let's say) 8 int-s, you should use:

int* ptr = malloc(sizeof(int) * 8);

and of course you should check against failure, at least:

if (!ptr) { perror("malloc"); exit(EXIT_FAILURE); };

and you need to initialize that array (the memory you've got contain unpredictable junk), e.g.

for (int i=0; i<8; i++) ptr[i] = 0;

or you could clear all bits (with the same result on all machines I know of) using

memset(ptr, 0, sizeof(int)*8);

Notice that even after a successful such malloc (or a failed one) you always have sizeof(ptr) be the same (on my Linux/x86-64 box, it is 8 bytes), since it is the size of a pointer (even if you malloc-ed a memory zone for a million int-s).

In practice, when you use C dynamic memory allocation you need to know conventionally the allocated size of that pointer. In the code above, I used 8 in several places, which is poor style. It would have been better to at least

  #define MY_ARRAY_LENGTH 8

and use MY_ARRAY_LENGTH everywhere instead of 8, starting with

 int* ptr = malloc(MY_ARRAY_LENGTH*sizeof(int));

In practice, allocated memory has often a runtime defined size, and you would keep somewhere (in a variable, a parameter, etc...) that size.

Study the source code of some existing free software project (e.g. on github), you'll learn very useful things.

Read also (perhaps in a week or two) about flexible array members. Sometimes they are very useful.


问:
Python OO, self calling other functions inside class?
I am new to object oriented concepts, and I've tried solving this problem using OO technique. I have solved it using normal programming technique, but I cant get it to work with OO technique.

here is the problem:
https://www.hackerrank.com/challenges/30-nested-logic?utm_campaign=30_days_of_code_continuous&utm_medium=email&utm_source=daily_reminder

What I've tried:
At first, I only called student1.print(). that didnt work so I called parseDate() and calculateFine().
I put self in all the variables in my student class as I fail to truly understand why or how self works.

Apologizes if I incorrectly labeled the title, but I didnt know what else to write, as I am not certain what exactly is the problem in my code.

```<code>class getFine():
    def __init__ (self,expectedDate,actualDate):
        self.expectedDate = expectedDate
        self.actualDate = actualDate

    def parseDates(self):
        self.ya = self.actualDate[0]
        self.ma = self.actualDate[1]
        self.da = self.actualDate[0]

        self.ye = self.expectedDate[0]
        self.me = self.expectedDate[1]
        self.de = self.expectedDate[2]

    def calculateFine(self):
        self.fine = 0
        if(self.ya>self.ye):
            self.fine = 10000
        elif self.ya==self.ye:
            if(self.ma>self.me):
                self.fine = 500 * (self.ma-self.me)
            elif(self.ma==self.me) and (self.da>self.de):
                self.fine = 15 * (self.da-self.de)

    def print(self):
        print(self.fine)

def main():
    expectedDate = str(input().split(" "))
    actualDate = str(input().split(" "))
    student1 = getFine(expectedDate, actualDate)
    student1.parseDates()
    student1.calculateFine()
    student1.print()

if __name__ == "__main__":
    main()
</code>```

答:
Your dates are strings, which you then want to subtract from each other. First convert them to integers or floats using something like this:

```<code>expectedDate = [int(i) for i in (input().split(" "))]
actualDate = [int(i) for i in (input().split(" "))]
</code>```

Does this solve your problem?

If you want to only call the getFine.print() function and not the other funtions, you could call these class methods in the getFine.print() method. Since you probably want to separate the year month and date on every function call, you could move that part to the init method

```<code>class getFine():
    def __init__ (self,expectedDate,actualDate):
        self.expectedDate = expectedDate
        self.actualDate = actualDate

        self.ya = self.actualDate[0]
        self.ma = self.actualDate[1]
        self.da = self.actualDate[2]    # typo here 0 --> 2

        self.ye = self.expectedDate[0]
        self.me = self.expectedDate[1]
        self.de = self.expectedDate[2]

    def calculateFine(self):
        self.fine = 0
        if(self.ya>self.ye):
            self.fine = 10000
        elif self.ya==self.ye:
            if(self.ma>self.me):
                self.fine = 500 * (self.ma-self.me)
            elif(self.ma==self.me) and (self.da>self.de):
                self.fine = 15 * (self.da-self.de)

    def print(self):
        self.calculateFine()
        print(self.fine)

expectedDate = [int(i) for i in (input().split(" "))]
actualDate = [int(i) for i in (input().split(" "))]
student1 = getFine(expectedDate, actualDate)
student1.print()
</code>```

Body:
I am new to object oriented concepts, and I've tried solving this problem using OO technique. I have solved it using normal programming technique, but I cant get it to work with OO technique.

here is the problem:
https://www.hackerrank.com/challenges/30-nested-logic?utm_campaign=30_days_of_code_continuous&utm_medium=email&utm_source=daily_reminder

What I've tried:
At first, I only called student1.print(). that didnt work so I called parseDate() and calculateFine().
I put self in all the variables in my student class as I fail to truly understand why or how self works.

Apologizes if I incorrectly labeled the title, but I didnt know what else to write, as I am not certain what exactly is the problem in my code.

class getFine():
    def __init__ (self,expectedDate,actualDate):
        self.expectedDate = expectedDate
        self.actualDate = actualDate

    def parseDates(self):
        self.ya = self.actualDate[0]
        self.ma = self.actualDate[1]
        self.da = self.actualDate[0]

        self.ye = self.expectedDate[0]
        self.me = self.expectedDate[1]
        self.de = self.expectedDate[2]

    def calculateFine(self):
        self.fine = 0
        if(self.ya>self.ye):
            self.fine = 10000
        elif self.ya==self.ye:
            if(self.ma>self.me):
                self.fine = 500 * (self.ma-self.me)
            elif(self.ma==self.me) and (self.da>self.de):
                self.fine = 15 * (self.da-self.de)

    def print(self):
        print(self.fine)

def main():
    expectedDate = str(input().split(" "))
    actualDate = str(input().split(" "))
    student1 = getFine(expectedDate, actualDate)
    student1.parseDates()
    student1.calculateFine()
    student1.print()

if __name__ == "__main__":
    main()

Body:
Your dates are strings, which you then want to subtract from each other. First convert them to integers or floats using something like this:

expectedDate = [int(i) for i in (input().split(" "))]
actualDate = [int(i) for i in (input().split(" "))]

Does this solve your problem?

If you want to only call the getFine.print() function and not the other funtions, you could call these class methods in the getFine.print() method. Since you probably want to separate the year month and date on every function call, you could move that part to the init method

class getFine():
    def __init__ (self,expectedDate,actualDate):
        self.expectedDate = expectedDate
        self.actualDate = actualDate

        self.ya = self.actualDate[0]
        self.ma = self.actualDate[1]
        self.da = self.actualDate[2]    # typo here 0 --> 2

        self.ye = self.expectedDate[0]
        self.me = self.expectedDate[1]
        self.de = self.expectedDate[2]

    def calculateFine(self):
        self.fine = 0
        if(self.ya>self.ye):
            self.fine = 10000
        elif self.ya==self.ye:
            if(self.ma>self.me):
                self.fine = 500 * (self.ma-self.me)
            elif(self.ma==self.me) and (self.da>self.de):
                self.fine = 15 * (self.da-self.de)

    def print(self):
        self.calculateFine()
        print(self.fine)

expectedDate = [int(i) for i in (input().split(" "))]
actualDate = [int(i) for i in (input().split(" "))]
student1 = getFine(expectedDate, actualDate)
student1.print()


问:
Upload images to temporary image folder
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .

What i did:

Creating form as :

```<code><form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>
</code>```

Php code :

```<code>$uploaddir = 'images/';
     // echo $uploaddir;
        $target = "$uploaddir".basename($_FILES['image']['name']);
              echo $target;

        $image = $_FILES['image']['name'];
    $sql="insert into News2(image_News2)
    values($image)";
    $res=mysqli_query($con,$sql);
    copy($_FILES['tmp_name']['name'],$target,true);
</code>```

What this code actually do is only inserting the image into the database not copying the image into the images folder.

What i searched for and found :

You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.

So i what i really wanted to do is :

1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.

答:
PHP Code :

```<code>     if (isset($_FILES['image']['name']) && $_FILES['image']['error']
     == 0) {
     $uploads_dir = '/uploads';
     $temp_file = $_FILES['image']['tmp_name'];
     $name = basename($_FILES["image"]["name"]);
     if(move_uploaded_file($temp_file, "$uploads_dir/$name")){
     //Fire Insert Query For Insert image name in your database
     }
     else
     {
      echo "Error !! , Your image not uploaded.";
     }
    }
   ?>
</code>```

Title: Upload images to temporary image folder

Body:
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .

What i did:

Creating form as :

<form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>

Php code :

$uploaddir = 'images/';
     // echo $uploaddir;
        $target = "$uploaddir".basename($_FILES['image']['name']);
              echo $target;

        $image = $_FILES['image']['name'];
    $sql="insert into News2(image_News2)
    values($image)";
    $res=mysqli_query($con,$sql);
    copy($_FILES['tmp_name']['name'],$target,true);

What this code actually do is only inserting the image into the database not copying the image into the images folder.

What i searched for and found :

You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.

So i what i really wanted to do is :

1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.

Body:
PHP Code :

     if (isset($_FILES['image']['name']) && $_FILES['image']['error']
     == 0) {
     $uploads_dir = '/uploads';
     $temp_file = $_FILES['image']['tmp_name'];
     $name = basename($_FILES["image"]["name"]);
     if(move_uploaded_file($temp_file, "$uploads_dir/$name")){
     //Fire Insert Query For Insert image name in your database
     }
     else
     {
      echo "Error !! , Your image not uploaded.";
     }
    }
   ?>


问:
Yosys optimizes away ring oscillator on ice40 FPGA
Im trying to implement a simple ring oscillator for an ice40 FPGA using yosys (0.7) as follows:

```<code>module ringosc(input clkin,
               output out);

   (* keep="true" *)
   wire [100:0]              ring;

   assign ring[100:1] = ~ring[99:0];
   assign ring[0]     = ~ring[100];

   assign out = ring[0];

endmodule
</code>```

However, it seems to get optimized away even though I am using the keep attribute. I can see this in the yosys log output:

```<code>7.14.2. Executing OPT_EXPR pass (perform const folding).
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$292' (double_invert) in module `\lfsr' with constant driver `\trng.ring [62] = \trng.ring [60]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$293' (double_invert) in module `\lfsr' with constant driver `\trng.ring [63] = \trng.ring [59]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$294' (double_invert) in module `\lfsr' with constant driver `\trng.ring [64] = \trng.ring [58]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$295' (double_invert) in module `\lfsr' with constant driver `\trng.ring [65] = \trng.ring [57]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$296' (double_invert) in module `\lfsr' with constant driver `\trng.ring [66] = \trng.ring [56]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$297' (double_invert) in module `\lfsr' with constant driver `\trng.ring [67] = \trng.ring [55]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$298' (double_invert) in module `\lfsr' with constant driver `\trng.ring [68] = \trng.ring [54]'.
...
</code>```

How can I prevent yosys from doing this?

答:
Instantiate logic cells manually, like it is done in this example project:
http://svn.clifford.at/handicraft/2015/ringosc/

(The project is from this video I made in 2015:

https://www.youtube.com/watch?v=UFqWjZudOho)

Body:
Im trying to implement a simple ring oscillator for an ice40 FPGA using yosys (0.7) as follows:

module ringosc(input clkin,
               output out);

   (* keep="true" *)
   wire [100:0]              ring;

   assign ring[100:1] = ~ring[99:0];
   assign ring[0]     = ~ring[100];

   assign out = ring[0];

endmodule

However, it seems to get optimized away even though I am using the keep attribute. I can see this in the yosys log output:

7.14.2. Executing OPT_EXPR pass (perform const folding).
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$292' (double_invert) in module `\lfsr' with constant driver `\trng.ring [62] = \trng.ring [60]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$293' (double_invert) in module `\lfsr' with constant driver `\trng.ring [63] = \trng.ring [59]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$294' (double_invert) in module `\lfsr' with constant driver `\trng.ring [64] = \trng.ring [58]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$295' (double_invert) in module `\lfsr' with constant driver `\trng.ring [65] = \trng.ring [57]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$296' (double_invert) in module `\lfsr' with constant driver `\trng.ring [66] = \trng.ring [56]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$297' (double_invert) in module `\lfsr' with constant driver `\trng.ring [67] = \trng.ring [55]'.
Replacing $_NOT_ cell `$auto$simplemap.cc:37:simplemap_not$298' (double_invert) in module `\lfsr' with constant driver `\trng.ring [68] = \trng.ring [54]'.
...

How can I prevent yosys from doing this?


问:
Laravel 5, check if class is registered in the container
Is there any way to check if a class exists in Laravel 5?

I had this solution for Laravel 4: try to make a specific class, and if I get a ReflectionException, I use a generic class.

In Laravel 5 looks like I can't intercept the ReflectionException and I get a "Whoops".

I was wondering if there is some better way to do this.

```<code>try {
    $widgetObject = \App::make($widget_class);
} catch (ReflectionException $e) {
    $widgetObject = \App::make('WidgetController');
    $widgetObject->widget($widget);
}
</code>```

答:
Use the getProvider method on the Application container:

```<code>if (app()->getProvider($classname)) {
   // Do what you want when it exists.
 }
</code>```

It's been available since 5.0 and can be viewed here.

Body:
Is there any way to check if a class exists in Laravel 5?

I had this solution for Laravel 4: try to make a specific class, and if I get a ReflectionException, I use a generic class.

In Laravel 5 looks like I can't intercept the ReflectionException and I get a "Whoops".

I was wondering if there is some better way to do this.

try {
    $widgetObject = \App::make($widget_class);
} catch (ReflectionException $e) {
    $widgetObject = \App::make('WidgetController');
    $widgetObject->widget($widget);
}

Body:
Use the getProvider method on the Application container:

if (app()->getProvider($classname)) {
   // Do what you want when it exists.
 }

It's been available since 5.0 and can be viewed here.


问:
Keyboard covers textfield in JSQMessagesViewController
I am implementing the JSQMessagesViewController library for messaging. I have small issue with the keyboard, when the textfield ist edited, the keyboard covers the textfield, and i should slide it down to see what did i write.
They have a class JSQMessagesKeyboardController which is handling the keyboard..

I tried this solution from here: iPhone Keyboard Covers UITextField but nothing changed.

Does someone had the same problem, would you share possible solutions?

答:
override </p>

```<code> func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
   keyboardController.beginListeningForKeyboard()
 }
</code>```

Body:
override

 func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
   keyboardController.beginListeningForKeyboard()
 }


问:
How to avoid overfitting on a simple feed forward network
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

```<code># Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

```<code>model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))
</code>```

Here are the graphs for 500 epochs

答:
The first example gave a validation accuracy > 75% and the second one gave an accuracy of < 65% and if you compare the losses for epochs below 100, its  less than < 0.5 for the first one and the second one was > 0.6. But how is the second case better?.

The second one to me is a case of under-fitting:  the model doesnt have enough capacity to learn. While the first case has a problem of over-fitting because its training was not stopped when overfitting started (early stopping).  If the training was stopped at say 100 epoch, it would be a far better model compared between the two.

The goal should be to obtain small prediction error in unseen data and for that you increase the capacity of the network till a point beyond which overfitting starts to happen.

So how to avoid over-fitting in this particular case? Adopt early stopping.

CODE CHANGES: To include early stopping and input scaling.

```<code> # input scaling
 scaler = StandardScaler()
 X = scaler.fit_transform(X)

 # Early stopping
 early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=3, verbose=1, mode='auto')

 # create model - almost the same code
 model = Sequential()
 model.add(Dense(12, input_dim=8, activation='relu', name='first_input'))
 model.add(Dense(500, activation='relu', name='first_hidden'))
 model.add(Dropout(0.5, name='dropout_1'))
 model.add(Dense(8, activation='relu', name='second_hidden'))
 model.add(Dense(1, activation='sigmoid', name='output_layer')))

 history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb, early_stop])
</code>```

The Accuracy and loss graphs:

Body:
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

# Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

Here are the graphs for 500 epochs

Body:
The first example gave a validation accuracy > 75% and the second one gave an accuracy of < 65% and if you compare the losses for epochs below 100, its  less than < 0.5 for the first one and the second one was > 0.6. But how is the second case better?.

The second one to me is a case of under-fitting:  the model doesnt have enough capacity to learn. While the first case has a problem of over-fitting because its training was not stopped when overfitting started (early stopping).  If the training was stopped at say 100 epoch, it would be a far better model compared between the two.

The goal should be to obtain small prediction error in unseen data and for that you increase the capacity of the network till a point beyond which overfitting starts to happen.

So how to avoid over-fitting in this particular case? Adopt early stopping.

CODE CHANGES: To include early stopping and input scaling.

 # input scaling
 scaler = StandardScaler()
 X = scaler.fit_transform(X)

 # Early stopping
 early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=3, verbose=1, mode='auto')

 # create model - almost the same code
 model = Sequential()
 model.add(Dense(12, input_dim=8, activation='relu', name='first_input'))
 model.add(Dense(500, activation='relu', name='first_hidden'))
 model.add(Dropout(0.5, name='dropout_1'))
 model.add(Dense(8, activation='relu', name='second_hidden'))
 model.add(Dense(1, activation='sigmoid', name='output_layer')))

 history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb, early_stop])

The Accuracy and loss graphs:


答:
The fact that the program runs smoothly does not mean it is correct!
Try to increase the 5 in the for loop to some extent (500000, for instance, should suffices). At some point, it will stop working giving you a SEGFAULT.

This is called Undefined Behaviour.

valgrind would also warn you about the issue with something like the following.

```<code>==16812== Invalid write of size 4
==16812==    at 0x40065E: main (test.cpp:27)
</code>```

If you dont know what valgrind is check this out: How do I use valgrind to find memory leaks?. (BTW it's a fantastic tool)

This should help gives you some more clarifications: Accessing unallocated memory C++

Title: Working of malloc in C

Body:
The fact that the program runs smoothly does not mean it is correct!
Try to increase the 5 in the for loop to some extent (500000, for instance, should suffices). At some point, it will stop working giving you a SEGFAULT.

This is called Undefined Behaviour.

valgrind would also warn you about the issue with something like the following.

==16812== Invalid write of size 4
==16812==    at 0x40065E: main (test.cpp:27)

If you dont know what valgrind is check this out: How do I use valgrind to find memory leaks?. (BTW it's a fantastic tool)

This should help gives you some more clarifications: Accessing unallocated memory C++


问:
Intro rule for ∀x∈S (Isabelle)
Usually when you have a goal beginning ∀x you can write something like

```<code>show "∀x. Px"
proof (rule allI)
</code>```

but this doesn't seem to work when you have something beginning ∀x∈S. For example, I tried

```<code>show "∀x∈S. P x"
proof (rule allI)
</code>```

which gives the message

```<code>Failed to apply initial proof method
</code>```

This surprised me, since I thought ∀x∈S. P x was probably syntactic sugar for ∀x. x∈S --> P x, in which case it should work.

This is similar to a question I previously asked

Intro rule for "∀r>0" in Isabelle

but I think that this time the answer might be different.

答:
It is not just syntax; it is its own constant called Ball, and the introduction rule is called ballI.

If you ctrl-click onto `∀x∈A", it should take you straight to the definition, where you can see what it is called. Additionally, you can use the ‘Find theorems’ panel in Isabelle to find lemmas related to it.

Title: Intro rule for ∀x∈S (Isabelle)

Body:
Usually when you have a goal beginning ∀x you can write something like

show "∀x. Px"
proof (rule allI)

but this doesn't seem to work when you have something beginning ∀x∈S. For example, I tried

show "∀x∈S. P x"
proof (rule allI)

which gives the message

Failed to apply initial proof method

This surprised me, since I thought ∀x∈S. P x was probably syntactic sugar for ∀x. x∈S --> P x, in which case it should work.

This is similar to a question I previously asked

Intro rule for "∀r>0" in Isabelle

but I think that this time the answer might be different.


答:
```<code>yum install -y httpd-devel pcre perl pcre-devel zlib zlib-devel GeoIP GeoIP-devel

Download required packages

cd
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.10.tar.gz
wget http://zlib.net/zlib-1.2.5.tar.gz
wget ftp://ftp.openssl.org/source/openssl-0.9.8o.tar.gz

Now you have to untar these files.
tar -xvf zlib-1.2.5.tar.gz
tar -xvf pcre-8.10.tar.gz
tar -xvf openssl-0.9.8o.tar.gz
</code>```

Body:
I am new to dockers/containers.

I am trying to run a fork with a fix I have put in for openSSL vulnerability of mup-frontend using the following command:

docker build ./

It compiles to a point then errors with

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

I am running a mac so installed zlib with brew. I have searched long and hard but cannot find much on this error.

Because of this error it also fails to build on automation in docker.io


问:
is it possible to change first value of KEY_ID in sqlite android?
in database i use this code
        KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
that cause the KEY_ID start from 1 to ...

but i want to start from 0 instead of 1
is it possible ?

答:
The documentation says:

The ROWID chosen for the new row is at least one larger than the largest ROWID that has ever before existed in that same table. If the table has never before contained any data, then a ROWID of 1 is used.

So it is not possible to start from zero, except by manually inserting the value 0 for the first row.


问:
How empty input value when success submit in jquery
I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:

```<code>$(document).ready(function(){
    $("#Insert").click(function(){
        var email = $("#email").val();
        var title = $("title").val();
        var text = $("text").val();
        var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
        $("#contactResualt").html(data);

        });
    });
});
</code>```

//ajax.php

```<code>if(isset($_POST['cSend'])){
  if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
    echo '<div class="alert alert-warning">Fill empty fields</div>';
}
else{
    $email = $_POST['email'];
    $title = $_POST['title'];
    $text = $_POST['text'];
    $Contactus = new Contactus();
    $resualt = $Contactus->SendPM($email,$title,$text);
        if($resualt){
        echo '<div class="alert alert-success">Insertion was successful</div>';
        }
        else{
        echo '<div class="alert alert-warning">Insertion failed</div>';
        }
    }
}
</code>```

So, I just want the information to be correctly inserted, Inputs will be cleared.

答:
You can clear the input field by using $('input').val('');

```<code>$(document).ready(function(){
$("#Insert").click(function(){
    var email = $("#email").val();
    var title = $("title").val();
    var text = $("text").val();
    var cSend = true;
    $.post("ajax.php",
    {email:email,title:title,text:text,cSend:cSend},function(data){
    var json_obj = $.parseJSON(data);//parse JSON
    $("#contactResualt").html(json_obj.msg);
          if(json_obj.status){
            $('input').val('');
         }
    });
    });
});
</code>```

Ajax.php

```<code>if(isset($_POST['cSend'])){
 if (empty($_POST['email']) || empty($_POST['title']) ||
 empty($_POST['text'])){
 $result['status'] = false;
  $result['msg'] =  '<div class="alert alert-warning">Fill empty
 fields</div>';
 }
 else{
 $email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
    if($resualt){
    $result['status'] = true;
    $result['msg'] = '<div class="alert alert-success">Insertion was successful</div>';
    }
    else{
    $result['status'] = false;
    $result['msg'] =  '<div class="alert alert-warning">Insertion failed</div>';
    }
   }
   echo json_encode($result);
}
</code>```

Body:
I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:

$(document).ready(function(){
    $("#Insert").click(function(){
        var email = $("#email").val();
        var title = $("title").val();
        var text = $("text").val();
        var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
        $("#contactResualt").html(data);

        });
    });
});

//ajax.php

if(isset($_POST['cSend'])){
  if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
    echo '
Fill empty fields
';
}
else{
    $email = $_POST['email'];
    $title = $_POST['title'];
    $text = $_POST['text'];
    $Contactus = new Contactus();
    $resualt = $Contactus->SendPM($email,$title,$text);
        if($resualt){
        echo '
Insertion was successful
';
        }
        else{
        echo '
Insertion failed
';
        }
    }
}

So, I just want the information to be correctly inserted, Inputs will be cleared.

Body:
You can clear the input field by using $('input').val('');

$(document).ready(function(){
$("#Insert").click(function(){
    var email = $("#email").val();
    var title = $("title").val();
    var text = $("text").val();
    var cSend = true;
    $.post("ajax.php",
    {email:email,title:title,text:text,cSend:cSend},function(data){
    var json_obj = $.parseJSON(data);//parse JSON
    $("#contactResualt").html(json_obj.msg);
          if(json_obj.status){
            $('input').val('');
         }
    });
    });
});

Ajax.php

if(isset($_POST['cSend'])){
 if (empty($_POST['email']) || empty($_POST['title']) ||
 empty($_POST['text'])){
 $result['status'] = false;
  $result['msg'] =  '<div class="alert alert-warning">Fill empty
 fields</div>';
 }
 else{
 $email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
    if($resualt){
    $result['status'] = true;
    $result['msg'] = '<div class="alert alert-success">Insertion was successful</div>';
    }
    else{
    $result['status'] = false;
    $result['msg'] =  '<div class="alert alert-warning">Insertion failed</div>';
    }
   }
   echo json_encode($result);
}


问:
Jquery: Closest() div remove not working
Jquery closest div remove not working i found same question on stackoverflow but these answered not resolve my problem

closest div remove js fiddle here

```<code><script>
$(document).ready(function(){
    var counter = 4;
    var name = 1;
    var qty = 1;
    var price = 1;
    $('#addproduct').click(function() {
        $('#dynamicInput').append('<div class="clearfix"></div><div class="pdd" id="dlt"><div class="col-sm-3"><div class="row">' + (counter++)+' <label>Product Name</label></div></div><div class="col-sm-3"><div class="row"><select name="productnm'+(name++)+'"><option>Select Product</option><option>Rice</option><option>Fried Rice</option><option>Biryani</option></select></div></div><div class="col-sm-3"><div class="row"><label>Quantity</label></div></div><div class="col-sm-1 row"><div class="row qunatity-number"><input type="number" name="qunatity'+(qty++)+'" value="1" /></div></div><div class="col-sm-2"><div class="row qunatity-totalprice"><input type="text" name="totalprice'+(price++)+'" placeholder="Total Price" disabled /></div></div><a class="deleter" ><i class="fa fa-trash-o" aria-hidden="true"></i></a></div> ');
    });
    $('.deleter').click(function(){
       $(this).closest("#dlt").remove();
     });

});

</script>
</code>```

答: Since you add your elements afterwards to the dom, the click-event is not bound to your .deleter. you have to invoke it every time you create a new element like this: https://jsfiddle.net/woeot0L4/5/


问:
Android - How to pass another activity application context from java class extends fragments to asynctask?
Hi I am trying to make application that has view pager and tablayout. So when I choose 'friends' tab layout it will call java class named FragFriends.java,

In this class I want to inflate layout where recycler view adapter is filled with data from database that I retrieve using asynctask method in class PHPuserlist.java

However my application suddenly stopped

Here is the the FragFriends.java

```<code>public class FragmentFriends extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup    container, @Nullable Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.activity_user_view,container,false);// The activity that contains recyclerview
    View dview = inflater.inflate(R.layout.activity_profile,container,false); //This is the activity that contains tablayout
    PHPUserList phpUserList = new PHPUserList(dview.getContext());
    phpUserList.execute();
    return rootview;
}

}
</code>```

I have implement this recycler view with intent and it work just fine. But I need to use this with fragment
Pleas help me

This is the logcat

```<code>05-27 16:55:12.198 14031-14031/com.rumahdosen.www.rumahdosen E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.rumahdosen.www.rumahdosen, PID: 14031
        java.lang.NullPointerException
        at com.rumahdosen.www.rumahdosen.PHPUserList.onPreExecute(PHPUserList.java:82)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
        at android.os.AsyncTask.execute(AsyncTask.java:535)
        at com.rumahdosen.www.rumahdosen.FragmentFriends.onCreateView(FragmentFriends.java:20)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
        at android.view.View.measure(View.java:16834)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5292)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

Below is the PHPUserList.java

```<code>public class PHPUserList extends AsyncTask<Void,UserList,Void> {

private Context context;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserList> arrayList = new ArrayList<>();

PHPUserList(Context ctx){

    this.context = ctx;
    activity = (Activity)ctx;
}
@Override
protected Void doInBackground(Void... params) {
    try {
        URL url = new URL("http://njtwicomp.pe.hu/listuser.php");
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine())!=null)
        {
            stringBuilder.append(line+"\n");
        }

        httpURLConnection.disconnect();
        String json_string = stringBuilder.toString().trim();
        JSONObject jsonObject = new JSONObject(json_string);
        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
        int count = 0;
        while(count<jsonArray.length()){
            JSONObject JO = jsonArray.getJSONObject(count);
            count++;
            UserList userList = new UserList(JO.getString("Name"),JO.getString("Username"));
            publishProgress(userList);
        }
        Log.d("JSON STRING", json_string);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPreExecute() {
    recyclerView = (RecyclerView) activity.findViewById(R.id.RVUserList);
    layoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new RecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
}

@Override
protected void onProgressUpdate(UserList... values) {
    arrayList.add(values[0]);
    adapter.notifyDataSetChanged();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
}
}
</code>```

I try to find the recyclerview by id in another activity while I set the activity as the activity of the passed context. But I don't know how to fix that

So how do I get the activity which is not the context that I passed in asynctask?

答:
just use getContext();

This does the work.
In case you need to use the  Activity Context then Have static context of  ClassName.this

Body:
Hi I am trying to make application that has view pager and tablayout. So when I choose 'friends' tab layout it will call java class named FragFriends.java,

In this class I want to inflate layout where recycler view adapter is filled with data from database that I retrieve using asynctask method in class PHPuserlist.java

However my application suddenly stopped

Here is the the FragFriends.java

public class FragmentFriends extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup    container, @Nullable Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.activity_user_view,container,false);// The activity that contains recyclerview
    View dview = inflater.inflate(R.layout.activity_profile,container,false); //This is the activity that contains tablayout
    PHPUserList phpUserList = new PHPUserList(dview.getContext());
    phpUserList.execute();
    return rootview;
}

}

I have implement this recycler view with intent and it work just fine. But I need to use this with fragment
Pleas help me

This is the logcat

05-27 16:55:12.198 14031-14031/com.rumahdosen.www.rumahdosen E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.rumahdosen.www.rumahdosen, PID: 14031
        java.lang.NullPointerException
        at com.rumahdosen.www.rumahdosen.PHPUserList.onPreExecute(PHPUserList.java:82)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
        at android.os.AsyncTask.execute(AsyncTask.java:535)
        at com.rumahdosen.www.rumahdosen.FragmentFriends.onCreateView(FragmentFriends.java:20)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
        at android.view.View.measure(View.java:16834)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5292)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)

Below is the PHPUserList.java

public class PHPUserList extends AsyncTask<Void,UserList,Void> {

private Context context;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserList> arrayList = new ArrayList<>();

PHPUserList(Context ctx){

    this.context = ctx;
    activity = (Activity)ctx;
}
@Override
protected Void doInBackground(Void... params) {
    try {
        URL url = new URL("http://njtwicomp.pe.hu/listuser.php");
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine())!=null)
        {
            stringBuilder.append(line+"\n");
        }

        httpURLConnection.disconnect();
        String json_string = stringBuilder.toString().trim();
        JSONObject jsonObject = new JSONObject(json_string);
        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
        int count = 0;
        while(count<jsonArray.length()){
            JSONObject JO = jsonArray.getJSONObject(count);
            count++;
            UserList userList = new UserList(JO.getString("Name"),JO.getString("Username"));
            publishProgress(userList);
        }
        Log.d("JSON STRING", json_string);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPreExecute() {
    recyclerView = (RecyclerView) activity.findViewById(R.id.RVUserList);
    layoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new RecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
}

@Override
protected void onProgressUpdate(UserList... values) {
    arrayList.add(values[0]);
    adapter.notifyDataSetChanged();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
}
}

I try to find the recyclerview by id in another activity while I set the activity as the activity of the passed context. But I don't know how to fix that

So how do I get the activity which is not the context that I passed in asynctask?


问:
Notepad ++ doesn't save document on exit?
Situation:

Open a text file in n++, make some modification, press ALT-F4 or Close program.
The N++ won't ask "Do you want to save your changes". Instead it quits and text file on hdd remains unchanged.

But when I open the N++ again, the MODIFIED file is still in there. Red tab is indicating unsaved changes and I can save it by ctrl-s. I can also save it by closing the tab (n++ will ask).

I want to save the file automatically every time I close the n++. All of my other istallations does that but this. I could not find any settings in the n++ options. Any idea?

答:
This facility is controlled via menu => Settings => Preferences => Backup.

UnCHECK:
"Enable Session Snapshot and Periodic Backup"

Configuración / Preferencias / Backup
Quitar CHECKS a
Recordar la sesión actual en el próximo inicio


问:
With HTML5 canvas, how to calculate the final point coordinates with an offset?
On a HTML5 canvas object, I have to subtract a distance from a destination point, to give the final destination on the same line.

So, first I have calculated the distance between the source and target points, with the Pythagorean theorem, but my memories of Thales's theorem are too faulty to find the final point (on same line), with the right x and y attributes.

```<code>function getDistance (from, to){
    return Math.hypot(to.x - from.x, to.y - from.y);
}
function getFinalTo (from, to, distanceToSubstract){

    //with Pythagore we obtain the distance between the 2 points
    var originalDistance = getDistance(from, to);
    var finalDistance = originalDistance - distanceToSubstract;

    //Now, I was thinking about Thales but all my tries are wrong
    //Here some of ones, I need to get finalTo properties to draw an arrow to a node without

    var finalTo = new Object;
    finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x);
    finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y);

    return finalTo;
}
</code>```

Indeed, the arrowhead be hidden by the round node that can be about 100 pixels of radius, so I try to get the final point.

Thanks a lot.
Regards,

答:
You can use simple proportion by distance ratio:
(I did not account for round cap)

```<code>ratio = finalDistance / originalDistance
finalTo.x = from.x + (to.x - from.x) * ratio;
finalTo.y = from.y + (to.y - from.y) * ratio;
</code>```

Your approach was attempt to use linear interpolation, but you erroneously mixed distances (in pixels, meters etc) with ratios (dimensionless - is this term right?)

```<code>ratio = finalDistance / originalDistance
finalTo.x = ((1 - ratio) * from.x) + (ratio * to.x);
finalTo.y = ((1 - ratio) * from.y) + (ratio * to.y);
</code>```

Note that both approaches is really the same formula.

Body:
On a HTML5 canvas object, I have to subtract a distance from a destination point, to give the final destination on the same line.

So, first I have calculated the distance between the source and target points, with the Pythagorean theorem, but my memories of Thales's theorem are too faulty to find the final point (on same line), with the right x and y attributes.

function getDistance (from, to){
    return Math.hypot(to.x - from.x, to.y - from.y);
}
function getFinalTo (from, to, distanceToSubstract){

    //with Pythagore we obtain the distance between the 2 points
    var originalDistance = getDistance(from, to);
    var finalDistance = originalDistance - distanceToSubstract;

    //Now, I was thinking about Thales but all my tries are wrong
    //Here some of ones, I need to get finalTo properties to draw an arrow to a node without

    var finalTo = new Object;
    finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x);
    finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y);

    return finalTo;
}

Indeed, the arrowhead be hidden by the round node that can be about 100 pixels of radius, so I try to get the final point.

Thanks a lot.
Regards,

Body:
You can use simple proportion by distance ratio:
(I did not account for round cap)

ratio = finalDistance / originalDistance
finalTo.x = from.x + (to.x - from.x) * ratio;
finalTo.y = from.y + (to.y - from.y) * ratio;

Your approach was attempt to use linear interpolation, but you erroneously mixed distances (in pixels, meters etc) with ratios (dimensionless - is this term right?)

ratio = finalDistance / originalDistance
finalTo.x = ((1 - ratio) * from.x) + (ratio * to.x);
finalTo.y = ((1 - ratio) * from.y) + (ratio * to.y);

Note that both approaches is really the same formula.


问:
multiple sqlcmd commands in a batch file
I have multiple sqlcmd commands to run at a time from a batch file. Each statement when executed separately works perfectly. But if I give like a 5 sqlsmd commands in a bat file it only executes the first one and then I see 1> in my command line screen and nothing happens. How to resolve this?

Note: CALL statement before each line didn't work That is the only solution i found in my reseach

example of what i'm doing::

```<code>sqlcmd -S servername-q "EXEC msdb.dbo.prc_Backup @BackupType = 'L'       ,@DBName = 'db' ,@BackupDir = 'J:\MSSQL10.MSSQLSERVER\MSSQL\Backup\db2dba' ,@RetainHours = 47       , @create_sub_dir = 0      " >> C:\tlogresult.txt
sqlcmd -S servername -q "EXEC msdb.dbo.prc_Backup @BackupType = 'L'      ,@DBName = 'DB2RuntimeMigration' ,@BackupDir = 'J:\MSSQL10.MSSQLSERVER\MSSQL\Backup\DB2RuntimeMigration' ,@RetainHours = 47         , @create_sub_dir = 0      " >> C:\tlogresult.txt
</code>```

答:
Try capital Q

don't use
[-q "cmdline query"]

but instead use
[-Q "cmdline query" and exit]

Body:
I have multiple sqlcmd commands to run at a time from a batch file. Each statement when executed separately works perfectly. But if I give like a 5 sqlsmd commands in a bat file it only executes the first one and then I see 1> in my command line screen and nothing happens. How to resolve this?

Note: CALL statement before each line didn't work That is the only solution i found in my reseach

example of what i'm doing::

sqlcmd -S servername-q "EXEC msdb.dbo.prc_Backup @BackupType = 'L'       ,@DBName = 'db' ,@BackupDir = 'J:\MSSQL10.MSSQLSERVER\MSSQL\Backup\db2dba' ,@RetainHours = 47       , @create_sub_dir = 0      " >> C:\tlogresult.txt
sqlcmd -S servername -q "EXEC msdb.dbo.prc_Backup @BackupType = 'L'      ,@DBName = 'DB2RuntimeMigration' ,@BackupDir = 'J:\MSSQL10.MSSQLSERVER\MSSQL\Backup\DB2RuntimeMigration' ,@RetainHours = 47         , @create_sub_dir = 0      " >> C:\tlogresult.txt