问:
python: arrays produced by a regular expression in a loop "unexpected indent error"
when I run the following code I get an error "IdentationError: unexpected indent". But I don't know why and how can I solve it. the error is in the first if statement.</p>

```<code>import re
import xlrd
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
UOB = [sheet.cell_value(r,14) for r in range(sheet.nrows)]
count = {}
Myset = set()
for x in range (sheet.nrows):
    match = re.findall(",*([\w]*[College]*[Department]*[\w ]*),[ ]
[The]*Uni[\w.]*[ ]of[ ]Bahr[ai]*[ei]*n,*([\w ]*[College]*[Department]*[\w ]*),",UOB[x])
    if match[0][0]!='':
        if match[0][0] in Myset:
            count[match[0][0]]+=1
        else:
            Myset.add(match[0][0])
            count[match[0][0]]=1

    else:
        if match[0][1] in Myset:
            count[match[0][1]]+=1
        else:
            Myset.add(match[0][1])
            count[match[0][1]]=1
</code>```

答:
set your string to a variable and clean it up to fit on multiple lines correctly:</p>

```<code>z = (   ",*([\w]*[College]*[Department]*[\w ]*),"     +
        "[ ][The]*Uni[\w.]*[ ]of[ ]Bahr[ai]*[ei]*n,"  +
        "*([\w ]*[College]*[Department]*[\w ]*),"     )

for x in range (sheet.nrows):
    match = re.findall(z,UOB[x])
</code>```

Body:
when I run the following code I get an error "IdentationError: unexpected indent". But I don't know why and how can I solve it. the error is in the first if statement.

import re
import xlrd
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
UOB = [sheet.cell_value(r,14) for r in range(sheet.nrows)]
count = {}
Myset = set()
for x in range (sheet.nrows):
    match = re.findall(",*([\w]*[College]*[Department]*[\w ]*),[ ]
[The]*Uni[\w.]*[ ]of[ ]Bahr[ai]*[ei]*n,*([\w ]*[College]*[Department]*[\w ]*),",UOB[x])
    if match[0][0]!='':
        if match[0][0] in Myset:
            count[match[0][0]]+=1
        else:
            Myset.add(match[0][0])
            count[match[0][0]]=1

    else:
        if match[0][1] in Myset:
            count[match[0][1]]+=1
        else:
            Myset.add(match[0][1])
            count[match[0][1]]=1

Body:
set your string to a variable and clean it up to fit on multiple lines correctly:

z = (   ",*([\w]*[College]*[Department]*[\w ]*),"     +
        "[ ][The]*Uni[\w.]*[ ]of[ ]Bahr[ai]*[ei]*n,"  +
        "*([\w ]*[College]*[Department]*[\w ]*),"     )

for x in range (sheet.nrows):
    match = re.findall(z,UOB[x])


来源: stackexchange

问:
access NodeJS process.env in client side
I am solving a challenging ctf problem in which, the flag is in process.env of nodejs server. I can access source code of server ( bcs they public by express.static....) So is there anyway to access process.env of nodejs in client side?</p>

答:
There is a misunderstanding. express.static, is not giving you access to the server Javascript code. Instead it allows you to use selected code on both the server and the client side.

This allows you to share code on both sides, but it will never allow you to execute code on the client side in the server context.

This means, that you will not be able to execute server specific code on the client side like process.env.

You have basically two choices to get access on the client side to that flag :

you write the flag into the markup of the web page

you make an ajax request to the server that responds with this information.

ContentLicense: CC BY-SA 3.0


问:
C#, getting cookies with different names
I set cookies based on the referral links and they all start with the same letters, lets say "google", but they end with _xxx, _yyy, _zzz or whatever is the reference.

Now, when I try to get the cookies later, I have the problem that I don't want to check for all of the different cookies, I would like to check for all cookies that start with "google" and based on that I will start a script that goes on with processing.

```<code>if (Request.Cookies("google"))
{
    run other stuff
}
</code>```

Any idea how I can add StartWith or something to it? I am a newbie, so not really that into C# yet.

Thanks in advance,

Pat

答:
If you prefer, use lambda expression, this way

```<code>var cookie = Request.Cookies.AllKeys.FirstOrDefault(s => s.Contains("yourName"));
</code>```

Hope this help!

ContentLicense: CC BY-SA 2.5

Body:
I set cookies based on the referral links and they all start with the same letters, lets say "google", but they end with _xxx, _yyy, _zzz or whatever is the reference.

Now, when I try to get the cookies later, I have the problem that I don't want to check for all of the different cookies, I would like to check for all cookies that start with "google" and based on that I will start a script that goes on with processing.

if (Request.Cookies("google"))
{
    run other stuff
}

Any idea how I can add StartWith or something to it? I am a newbie, so not really that into C# yet.

Thanks in advance,

Pat

Body:
If you prefer, use lambda expression, this way

var cookie = Request.Cookies.AllKeys.FirstOrDefault(s => s.Contains("yourName"));

Hope this help!


问:
Unable to use Visual Studio project on different computer
I was working on a project (winforms, C++/Cli) on my desktop. When I copy project files to use it in my laptop, designer do not open.

 References to the 3rd party library[MetroFramework] is properly linked (project compile & run fine, no build error)
 but if I open designer I receive the following error

C++ CodeDom parser error: Line:99,Column:27 --unknown type".please
  make sure that the assembly that contains this type is referenced. if
  this is a part of your development project, make sure that the project
  has been successfully built"

code at line 99:

```<code>this->metroTabControl1 = (gcnew MetroFramework::Controls::MetroTabControl());
</code>```

Note: In designer, if I click on ignore & Continue, I get plain win form. Here if I drag & drop MetroFramework's UI control (metroTabControl) it display's fine. but if i close & reopen designer again i see the same error!!

Tried few suggestions from here & here, none of them worked!

答: Remove all toolbox items and references. Provide full path in vcproj. Remove and then connect the respective DLL required.</p>

Body:
I was working on a project (winforms, C++/Cli) on my desktop. When I copy project files to use it in my laptop, designer do not open.

 References to the 3rd party library[MetroFramework] is properly linked (project compile & run fine, no build error)
 but if I open designer I receive the following error

C++ CodeDom parser error: Line:99,Column:27 --unknown type".please
  make sure that the assembly that contains this type is referenced. if
  this is a part of your development project, make sure that the project
  has been successfully built"

code at line 99:

this->metroTabControl1 = (gcnew MetroFramework::Controls::MetroTabControl());

Note: In designer, if I click on ignore & Continue, I get plain win form. Here if I drag & drop MetroFramework's UI control (metroTabControl) it display's fine. but if i close & reopen designer again i see the same error!!

Tried few suggestions from here & here, none of them worked!


问:
Object reference not set to an instance of an object. but the Properties are accessable
I am passing a IList into another class which looks as follows:

```<code>public class KundenViewModel
{
    public IList<Kunde> _kunden;

    /// <summary>
    /// Add a list of Kunde to the View
    /// </summary>
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    /// <summary>
    /// Add one Object of Kunde to the View
    /// </summary>
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}
</code>```

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance

答: The error message probably refers to the _kunden collection. It is probably not initialized.</p>

Body:
I am passing a IList into another class which looks as follows:

public class KundenViewModel
{
    public IList<Kunde> _kunden;

    ///
    /// Add a list of Kunde to the View
    ///
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    ///
    /// Add one Object of Kunde to the View
    ///
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance


问:
Error 405 sending HTTP Post request from Android to C# Webservice
I try to send HTTP Post Request from an Android application to a C# RESTful web service.
For some reason I get a response code 405 as soon as it's connected.

If I try to send POST Request using a C# client that I made, the code works fine and I get a response successfully.

The code from Android (running on a service ofcourse):

```<code>String url = "http://myurl.com/Service1.svc/login/2";
String postDataParams = "{"username":"Ryrud","password":"Pups"}";

//Connect
            httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
            int responseCode = httpcon.getResponseCode();
            Log.d("zzz", "RCode: " + responseCode); // Getting in log: "RCode: 405"
            httpcon.setDoOutput(true);
            httpcon.setRequestMethod("POST");
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.connect();

//Post data
                DataOutputStream wr = new DataOutputStream(httpcon.getOutputStream());
                wr.writeBytes(postDataParams);
                wr.flush();
                wr.close();
</code>```

RESTful Webservice code:

```<code>[OperationContract]
       [WebInvoke(Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           UriTemplate = "login/{id}")]
           login login(string id, login userpass);
</code>```

答: Do not ask for a response code before you write the data to the outputstream.</p>

Body:
I try to send HTTP Post Request from an Android application to a C# RESTful web service.
For some reason I get a response code 405 as soon as it's connected.

If I try to send POST Request using a C# client that I made, the code works fine and I get a response successfully.

The code from Android (running on a service ofcourse):

String url = "http://myurl.com/Service1.svc/login/2";
String postDataParams = "{"username":"Ryrud","password":"Pups"}";

//Connect
            httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
            int responseCode = httpcon.getResponseCode();
            Log.d("zzz", "RCode: " + responseCode); // Getting in log: "RCode: 405"
            httpcon.setDoOutput(true);
            httpcon.setRequestMethod("POST");
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.connect();

//Post data
                DataOutputStream wr = new DataOutputStream(httpcon.getOutputStream());
                wr.writeBytes(postDataParams);
                wr.flush();
                wr.close();

RESTful Webservice code:

[OperationContract]
       [WebInvoke(Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           UriTemplate = "login/{id}")]
           login login(string id, login userpass);


问:
Macro to add text to a selected range in a Word Table
I am trying to write a Macro that allows the user to select a range of cells in a Word Table to populate Column 4 with a specific text "SOLD".

Below is my VBA Macro code so far, but it only types the text in the first Column 4 (rather than the selected range of column 4's)

```<code>Dim iSelectionRowEnd As Integer
Dim iSelectionRowStart As Integer
Dim cl1 As Cell
Dim cl2 As Cell
Dim tbl As Table
Dim rng As Range

ActiveDocument.Bookmarks.Add Name:="MacroStartPosition", Range:=Selection.Range

If Selection.Information(wdWithInTable) = False Then
    MsgBox "Selection is not in a table."
Else

    iSelectionRowEnd = Selection.Information(wdEndOfRangeRowNumber)
    Selection.Collapse Direction:=wdCollapseStart

    iSelectionRowStart = Selection.Information(wdEndOfRangeRowNumber)

    Set tbl = Selection.Tables(1)
    Set cl1 = tbl.Cell(iSelectionRowStart, 4)
    Set cl2 = tbl.Cell(iSelectionRowEnd, 4)
    Set rng = cl1.Range.Duplicate
    rng.End = cl2.Range.End
    rng.text = ("SALE")

End If
Selection.Collapse Direction:=wdCollapseStart

If ActiveDocument.Bookmarks.Exists("MacroStartPosition") = True Then
    ActiveDocument.Bookmarks("MacroStartPosition").Select
    ActiveDocument.Bookmarks("MacroStartPosition").Delete
Else
    MsgBox "The original cursor position could not be restored."
End If

Selection.Collapse Direction:=wdCollapseStart
</code>```

I tried to follow a similar code in Excel and apply it to Word, but I am getting errors. See below Excel.

```<code>ActiveCell.FormulaR1C1 = "SALE"
Selection.AutoFill Destination:=Range("D3:D7"), Type:=xlFillDefault
Range("D3:D7").Select
</code>```

答:
This works for me. Instead of rng.text = ("SALE") use:

```<code>For i = iSelectionRowStart To iSelectionRowEnd
    tbl.Cell(i, 4).Range.Text = "SALE"
Next
</code>```

Body:
I am trying to write a Macro that allows the user to select a range of cells in a Word Table to populate Column 4 with a specific text "SOLD".

Below is my VBA Macro code so far, but it only types the text in the first Column 4 (rather than the selected range of column 4's)

Dim iSelectionRowEnd As Integer
Dim iSelectionRowStart As Integer
Dim cl1 As Cell
Dim cl2 As Cell
Dim tbl As Table
Dim rng As Range

ActiveDocument.Bookmarks.Add Name:="MacroStartPosition", Range:=Selection.Range

If Selection.Information(wdWithInTable) = False Then
    MsgBox "Selection is not in a table."
Else

    iSelectionRowEnd = Selection.Information(wdEndOfRangeRowNumber)
    Selection.Collapse Direction:=wdCollapseStart

    iSelectionRowStart = Selection.Information(wdEndOfRangeRowNumber)

    Set tbl = Selection.Tables(1)
    Set cl1 = tbl.Cell(iSelectionRowStart, 4)
    Set cl2 = tbl.Cell(iSelectionRowEnd, 4)
    Set rng = cl1.Range.Duplicate
    rng.End = cl2.Range.End
    rng.text = ("SALE")

End If
Selection.Collapse Direction:=wdCollapseStart

If ActiveDocument.Bookmarks.Exists("MacroStartPosition") = True Then
    ActiveDocument.Bookmarks("MacroStartPosition").Select
    ActiveDocument.Bookmarks("MacroStartPosition").Delete
Else
    MsgBox "The original cursor position could not be restored."
End If

Selection.Collapse Direction:=wdCollapseStart

I tried to follow a similar code in Excel and apply it to Word, but I am getting errors. See below Excel.

ActiveCell.FormulaR1C1 = "SALE"
Selection.AutoFill Destination:=Range("D3:D7"), Type:=xlFillDefault
Range("D3:D7").Select

Body:
This works for me. Instead of rng.text = ("SALE") use:

For i = iSelectionRowStart To iSelectionRowEnd
    tbl.Cell(i, 4).Range.Text = "SALE"
Next


问:
ScrollTop() function, scroll time
When function is called, the page scrolls up to the top, but I need to wait for as long as the animate time is set to, to be able to scroll down again. for example if I say

$('html, body').animate({ scrollTop: 0 }, 800);

It makes me wait for a while to be able to scroll down again, but if I write

$('html, body').animate({ scrollTop: 0 }, 10);

It scrolls up a lot faster, but I will be able to immediately scroll down again! How can I use 800 (so the animate acts cooler) but avoid waiting for scrolling down again?

```<code>$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.goToTop').fadeIn();
    } else {
        $('.goToTop').fadeOut();
    }
    $('#goToTop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 800);
        return false;
    });
});
</code>```

答:
You need to write a setTimeout function inside the callback function of .animate() (the one which scrolls the window to top) in order to scroll down BACK to its earlier position. Working fiddle here.

$(document).ready(function(){
    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('#goToTop').fadeIn();
        } else {
            $('#goToTop').fadeOut();
        }
    });
    var duration_ms = 800;
    $('#goToTop').click(function () {
        var last_scroll = $(window).scrollTop();
        $('html, body').animate({ scrollTop: 0 }, duration_ms, function(){
         setTimeout(function(){
                 $('html, body').animate({ scrollTop: last_scroll }, duration_ms);
           }, duration_ms);
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#goToTop{
    cursor: pointer;
    display: none;
    position: fixed;
    bottom: 15px;
    right: 15px;
}</code>```

```
  a
  b
  c
  d
  q
  w
  e
  r
  t
  y
  u
  i
  o
  p
  a
  s
  d
  f
  g
  h
  j
  k
  l
  z
  x
  c
  v
  b
  n
  m
  <span id="goToTop">go to top</span>
``````

Title: ScrollTop() function, scroll time

Body:
When function is called, the page scrolls up to the top, but I need to wait for as long as the animate time is set to, to be able to scroll down again. for example if I say

$('html, body').animate({ scrollTop: 0 }, 800);

It makes me wait for a while to be able to scroll down again, but if I write

$('html, body').animate({ scrollTop: 0 }, 10);

It scrolls up a lot faster, but I will be able to immediately scroll down again! How can I use 800 (so the animate acts cooler) but avoid waiting for scrolling down again?

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.goToTop').fadeIn();
    } else {
        $('.goToTop').fadeOut();
    }
    $('#goToTop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 800);
        return false;
    });
});

Body:
You need to write a setTimeout function inside the callback function of .animate() (the one which scrolls the window to top) in order to scroll down BACK to its earlier position. Working fiddle here.

$(document).ready(function(){
    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('#goToTop').fadeIn();
        } else {
            $('#goToTop').fadeOut();
        }
    });
    var duration_ms = 800;
    $('#goToTop').click(function () {
        var last_scroll = $(window).scrollTop();
        $('html, body').animate({ scrollTop: 0 }, duration_ms, function(){
         setTimeout(function(){
                 $('html, body').animate({ scrollTop: last_scroll }, duration_ms);
           }, duration_ms);
        });
    });
});

#goToTop{
    cursor: pointer;
    display: none;
    position: fixed;
    bottom: 15px;
    right: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
  a
  b
  c
  d
  q
  w
  e
  r
  t
  y
  u
  i
  o
  p
  a
  s
  d
  f
  g
  h
  j
  k
  l
  z
  x
  c
  v
  b
  n
  m
  <span id="goToTop">go to top</span>
</pre>


问:
Python try except fail to catch RemoteDataError
I am using the following code to read data from yahoo finance from a list symbols downloaded from nasdaq.

```<code>pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01','2017-03-30') for i in symbols}

for df_name in pnls:
    try:
        pnls.get(df_name).to_csv("/Users/Jiong/Documents/data/{}_data.csv".format(df_name), index=True, header=True)
    except:
        print("error {}".format(df_name))
    else:
        print("done {}".format(df_name))
</code>```

Guess some symbols may not be valid and Yahoo Finance throws RemoteDataError Exception.

The code above is supposed to continue on, but it stopped still at the errors.

Isn't except to catch all exceptions? or this is run time error ?

Anyway to get the code ignores it and continue? Thanks. See errors below running

```<code>118         if params is not None and len(params) > 0:
119             url = url + "?" + urlencode(params)
--> 120         raise RemoteDataError('Unable to read URL: {0}'.format(url))
121
122     def _read_lines(self, out):
</code>```

```<code>RemoteDataError: Unable to read URL: http://ichart.finance.yahoo.com/table.csv?c=1985&f=2017&s=MITT%5EA&g=d&ignore=.csv&d=2&e=30&a=0&b=1
</code>```

答:
You need to handle the raise exception or it will halt at the place of raised. So, if a raise exception is not caught and handled, it will be interrupted.

What you need is something like this :

```<code>except RemoteDataError as exp :
    print('Unable to read URL: {0}'.format(url))
</code>```

You can refer to this documentation for more details on errors.

Body:
I am using the following code to read data from yahoo finance from a list symbols downloaded from nasdaq.

pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01','2017-03-30') for i in symbols}

for df_name in pnls:
    try:
        pnls.get(df_name).to_csv("/Users/Jiong/Documents/data/{}_data.csv".format(df_name), index=True, header=True)
    except:
        print("error {}".format(df_name))
    else:
        print("done {}".format(df_name))

Guess some symbols may not be valid and Yahoo Finance throws RemoteDataError Exception.

The code above is supposed to continue on, but it stopped still at the errors.

Isn't except to catch all exceptions? or this is run time error ?

Anyway to get the code ignores it and continue? Thanks. See errors below running

118         if params is not None and len(params) > 0:
119             url = url + "?" + urlencode(params)
--> 120         raise RemoteDataError('Unable to read URL: {0}'.format(url))
121
122     def _read_lines(self, out):

RemoteDataError: Unable to read URL: http://ichart.finance.yahoo.com/table.csv?c=1985&f=2017&s=MITT%5EA&g=d&ignore=.csv&d=2&e=30&a=0&b=1

Body:
You need to handle the raise exception or it will halt at the place of raised. So, if a raise exception is not caught and handled, it will be interrupted.

What you need is something like this :

except RemoteDataError as exp :
    print('Unable to read URL: {0}'.format(url))

You can refer to this documentation for more details on errors.


问:
How to convert office file to image
I am searching from last two days but did not find any thing.

My requirement is to create a document viewer in my web application (C#.Net) and I don't want to use any third party tool for this. Can I convert the files in image or PDF or in any common formate which can be easly render on web page. I also can not use Introp object.

Any help will be highly appreciated

答:
I believe what you need is an intermediate representation of the documents which can be converted into an image for the viewer to display.

Lets me try to explain with the below diagram:

Title: How to convert office file to image


问:
Change value of materialize select box by jquery
I want to change materialize select box value by jquery.

I am using $('#myselect').val('1'); on onchange event of other select box but it not works.

```<code>$("#select1").change(function() {
    $('#myselect').val('1');
});
</code>```

答:
This is similar to what logikal answered but I think is cleaner:</p>

```<code>$(".your-component-class").change(function(){

   //your code..

   //re-initialize component
   $(this).material_select();
});
</code>```

Body:
I want to change materialize select box value by jquery.

I am using $('#myselect').val('1'); on onchange event of other select box but it not works.

$("#select1").change(function() {
    $('#myselect').val('1');
});

Body:
This is similar to what logikal answered but I think is cleaner:

$(".your-component-class").change(function(){

   //your code..

   //re-initialize component
   $(this).material_select();
});


问:
C++: What are some general ways to make code more efficient for use with large numbers?
Please when answering this question try to be as general as possible to help the wider community, rather than just specifically helping my issue (although helping my issue would be great too ;) )

I seem to be encountering this problem time and time again with the simple problems on Project Euler. Most commonly are the problems that require a computation of the prime numbers - these without fail always fail to terminate for numbers greater than about 60,000.

My most recent issue is with Problem 12:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Here is my code:

```<code>#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {

int numberOfDivisors = 500;

//I begin by looping from 1, with 1 being the 1st triangular number, 2 being the second, and so on.
for (long long int i = 1;; i++) {
    long long int triangularNumber = (pow(i, 2) + i)/2
    //Once I have the i-th triangular, I loop from 1 to itself, and add 1 to count each time I encounter a divisor, giving the total number of divisors for each triangular.
    int count = 0;
    for (long long int j = 1; j <= triangularNumber; j++) {
        if (triangularNumber%j == 0) {
            count++;
        }
    }
    //If the number of divisors is 500, print out the triangular and break the code.
    if (count == numberOfDivisors) {
        cout << triangularNumber << endl;
        break;
    }
}

}
</code>```

This code gives the correct answers for smaller numbers, and then either fails to terminate or takes an age to do so!

So firstly, what can I do with this specific problem to make my code more efficient?

Secondly, what are some general tips both for myself and other new C++ users for making code more efficient? (I.e. applying what we learn here in the future.)

Thanks!

答:
The key problem is that your end condition is bad.  You are supposed to stop when count > 500, but you look for an exact match of count == 500, therefore you are likely to blow past the correct answer without detecting it, and keep going ... maybe forever.

If you fix that, you can post it to code review. They might say something like this:

Break it down into separate functions for finding the next triangle number, and counting the factors of some number.

When you find the next triangle number, you execute pow. I perform a single addition.

For counting the number of factors in a number, a google search might help. (e.g. http://www.cut-the-knot.org/blue/NumberOfFactors.shtml )  You can build a list of prime numbers as you go, and use that to quickly find a prime factorization, from which you can compute the number of factors without actually counting them. When the numbers get big, that loop gets big.

Body:
Please when answering this question try to be as general as possible to help the wider community, rather than just specifically helping my issue (although helping my issue would be great too ;) )

I seem to be encountering this problem time and time again with the simple problems on Project Euler. Most commonly are the problems that require a computation of the prime numbers - these without fail always fail to terminate for numbers greater than about 60,000.

My most recent issue is with Problem 12:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Here is my code:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {

int numberOfDivisors = 500;

//I begin by looping from 1, with 1 being the 1st triangular number, 2 being the second, and so on.
for (long long int i = 1;; i++) {
    long long int triangularNumber = (pow(i, 2) + i)/2
    //Once I have the i-th triangular, I loop from 1 to itself, and add 1 to count each time I encounter a divisor, giving the total number of divisors for each triangular.
    int count = 0;
    for (long long int j = 1; j <= triangularNumber; j++) {
        if (triangularNumber%j == 0) {
            count++;
        }
    }
    //If the number of divisors is 500, print out the triangular and break the code.
    if (count == numberOfDivisors) {
        cout << triangularNumber << endl;
        break;
    }
}

}

This code gives the correct answers for smaller numbers, and then either fails to terminate or takes an age to do so!

So firstly, what can I do with this specific problem to make my code more efficient?

Secondly, what are some general tips both for myself and other new C++ users for making code more efficient? (I.e. applying what we learn here in the future.)

Thanks!


问:
getting null values when trying to pass values to xml response in web service from model class
```<code>/**
 * ConnectDB2.java , i'm fetching data from database and setting values to model class.
 */
  package org.com.repair.spotify.repair.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.ws.rs.Path;

import org.com.repair.spotify.repair.model.RepairDetails;

/**
 * @author www.javaworkspace.com
 *
 */
@Path("/connectDB2")
public class ConnectDB2 {
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    String deviceName;
    String deviceModel;
    String ticketId;
    String issue;
    String deviceType;

    public ConnectDB2() {
        try {

            Class.forName("com.ibm.db2.jcc.DB2Driver");
            connection = DriverManager.getConnection(
                    "jdbc:db2://localhost:50000/HELLO", "db2admin", "admin");
            statement = connection.createStatement();

            resultSet = statement.executeQuery("SELECT * FROM DEVICE ");
            while (resultSet.next()) {
                System.out.println("DEVICE BRAND:" + resultSet.getString(1)
                        + " || ISSUE: " + resultSet.getString(2) + " ||MODEL:"
                        + resultSet.getString(3) + "||TYPE:"
                        + resultSet.getString(4));
                RepairDetails Rd = new RepairDetails();
                Rd.setDeviceModel(resultSet.getString(1));
                Rd.setIssue(resultSet.getString(2));
                Rd.setDeviceType(resultSet.getString(3));
                Rd.setDeviceType(resultSet.getString(4));

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
</code>```

/RepairDetails.java==> my Model class/

```<code>package org.com.repair.spotify.repair.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class RepairDetails {

    String deviceName;
    String deviceModel;
    String ticketId;
    String issue;
    String deviceType;

    public RepairDetails() {

    }

    public RepairDetails(String deviceName, String deviceModel,
            String ticketId, String issue, String deviceType) {
        super();
        this.deviceName = deviceName;
        this.deviceModel = deviceModel;
        this.ticketId = ticketId;
        this.issue = issue;
        this.deviceType = deviceType;
    }

    public String getDeviceName() {
        System.out.println("getter" + deviceName);
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        System.out.println("setter" + deviceName);
        this.deviceName = deviceName;
    }

    public String getDeviceModel() {
        return deviceModel;
    }

    public void setDeviceModel(String deviceModel) {
        System.out.println("setter" + deviceModel);
        this.deviceModel = deviceModel;
    }

    public String getTicketId() {
        return ticketId;
    }

    public void setTicketId(String ticketId) {
        this.ticketId = ticketId;
    }

    public String getIssue() {
        return issue;
    }

    public void setIssue(String issue) {
        System.out.println("setter" + issue);
        this.issue = issue;
    }

    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        System.out.println("setter" + deviceType);
        this.deviceType = deviceType;
    }

}
</code>```

//the service class from where i'm trying get values from model, but i'm fetching null value which is further passed on getRepairdetails()

```<code>package org.com.repair.spotify.repair.service;
import java.util.ArrayList;
import java.util.List;

import org.com.repair.spotify.repair.db.ConnectDB2;
import org.com.repair.spotify.repair.model.*;

public class RepairService {

    public RepairService() {
        ConnectDB2 db = new ConnectDB2();
    }

    public List<RepairDetails> getRepairService()

    {
        System.out.println("getRepairDetails-->2");
        RepairDetails Rd = new RepairDetails();

        System.out.println("hey im firing");
        RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
                Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
                "Mobile");
        List<RepairDetails> list = new ArrayList<RepairDetails>();
        list.add(RD1);
        return list;

    }

}
</code>```

Kindly help me why null values are returned by getter ???

答:
Let's start with examining the RepairDetails class. This one implements a POJO (Plain old Java object) and contains two constructors.

public RepairDetails()

public RepairDetails(String, String, String, String, String)

So when you create the object with the first constructor, that means you are not setting anything to the fields, that means that the values are initialized to null.

Now let's examine the RepairService class. There you have this code in the getRepairService() method.

```<code>RepairDetails Rd = new RepairDetails();

RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
        Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
        "Mobile");

List<RepairDetails> list = new ArrayList<RepairDetails>();
list.add(RD1);
</code>```

Here we have the following observations:

Rd is an object created with the first constructor, so effectively the values in Rd will be null.

You are constructing RD1 with values got from Rd meaning that they will be null too.

I hope you get it now.

Body:
/**
 * ConnectDB2.java , i'm fetching data from database and setting values to model class.
 */
  package org.com.repair.spotify.repair.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.ws.rs.Path;

import org.com.repair.spotify.repair.model.RepairDetails;

/**
 * @author www.javaworkspace.com
 *
 */
@Path("/connectDB2")
public class ConnectDB2 {
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    String deviceName;
    String deviceModel;
    String ticketId;
    String issue;
    String deviceType;

    public ConnectDB2() {
        try {

            Class.forName("com.ibm.db2.jcc.DB2Driver");
            connection = DriverManager.getConnection(
                    "jdbc:db2://localhost:50000/HELLO", "db2admin", "admin");
            statement = connection.createStatement();

            resultSet = statement.executeQuery("SELECT * FROM DEVICE ");
            while (resultSet.next()) {
                System.out.println("DEVICE BRAND:" + resultSet.getString(1)
                        + " || ISSUE: " + resultSet.getString(2) + " ||MODEL:"
                        + resultSet.getString(3) + "||TYPE:"
                        + resultSet.getString(4));
                RepairDetails Rd = new RepairDetails();
                Rd.setDeviceModel(resultSet.getString(1));
                Rd.setIssue(resultSet.getString(2));
                Rd.setDeviceType(resultSet.getString(3));
                Rd.setDeviceType(resultSet.getString(4));

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

/RepairDetails.java==> my Model class/

package org.com.repair.spotify.repair.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class RepairDetails {

    String deviceName;
    String deviceModel;
    String ticketId;
    String issue;
    String deviceType;

    public RepairDetails() {

    }

    public RepairDetails(String deviceName, String deviceModel,
            String ticketId, String issue, String deviceType) {
        super();
        this.deviceName = deviceName;
        this.deviceModel = deviceModel;
        this.ticketId = ticketId;
        this.issue = issue;
        this.deviceType = deviceType;
    }

    public String getDeviceName() {
        System.out.println("getter" + deviceName);
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        System.out.println("setter" + deviceName);
        this.deviceName = deviceName;
    }

    public String getDeviceModel() {
        return deviceModel;
    }

    public void setDeviceModel(String deviceModel) {
        System.out.println("setter" + deviceModel);
        this.deviceModel = deviceModel;
    }

    public String getTicketId() {
        return ticketId;
    }

    public void setTicketId(String ticketId) {
        this.ticketId = ticketId;
    }

    public String getIssue() {
        return issue;
    }

    public void setIssue(String issue) {
        System.out.println("setter" + issue);
        this.issue = issue;
    }

    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        System.out.println("setter" + deviceType);
        this.deviceType = deviceType;
    }

}

//the service class from where i'm trying get values from model, but i'm fetching null value which is further passed on getRepairdetails()

package org.com.repair.spotify.repair.service;
import java.util.ArrayList;
import java.util.List;

import org.com.repair.spotify.repair.db.ConnectDB2;
import org.com.repair.spotify.repair.model.*;

public class RepairService {

    public RepairService() {
        ConnectDB2 db = new ConnectDB2();
    }

    public List<RepairDetails> getRepairService()

    {
        System.out.println("getRepairDetails-->2");
        RepairDetails Rd = new RepairDetails();

        System.out.println("hey im firing");
        RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
                Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
                "Mobile");
        List<RepairDetails> list = new ArrayList<RepairDetails>();
        list.add(RD1);
        return list;

    }

}

Kindly help me why null values are returned by getter ???

Body:
Let's start with examining the RepairDetails class. This one implements a POJO (Plain old Java object) and contains two constructors.

public RepairDetails()

public RepairDetails(String, String, String, String, String)

So when you create the object with the first constructor, that means you are not setting anything to the fields, that means that the values are initialized to null.

Now let's examine the RepairService class. There you have this code in the getRepairService() method.

RepairDetails Rd = new RepairDetails();

RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
        Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
        "Mobile");

List<RepairDetails> list = new ArrayList<RepairDetails>();
list.add(RD1);

Here we have the following observations:

Rd is an object created with the first constructor, so effectively the values in Rd will be null.

You are constructing RD1 with values got from Rd meaning that they will be null too.

I hope you get it now.


问:
Google Protobuf Empty List Showing Size 1
I am using Google Protobuf with Java. I am having problem with sending empty repeated string.

```<code>message OurPokemonMessage {
        ....
        repeated string learnableMoves = 10;
}
</code>```

Now when I use Protobuf method to add a collection (which is empty) like this :

```<code>message.addAllLearnableMoves(someEmptyListOfString);
</code>```

Now when I create a new List of String using this message I get one element in the list which is an Empty List.

This is how I create List of string using the message :

```<code>new ArrayList<>(message.getLearnableMovesList())
</code>```

This array list contains an empty string element. So I debugged the message and evaluated 2 conditions and found weird results.

```<code>message.getLearnableMovesList()//clearly shows empty list

     (com.google.protobuf.UnmodifiableLazyStringList) [] //Empty

message.getLearnableMovesList().size()//shows the size of list is 1
     (int) 1 //Size is 1
</code>```

Has anyone faces any similar problems? Is there any way to resolve this?

答: So I realised later on that there was no issue with protobuf library. The issue was that in my learnableMove field, I was adding an empty string which when printed using toString() was showing [] whereas the size of the list was 1.</p>

Body:
I am using Google Protobuf with Java. I am having problem with sending empty repeated string.

message OurPokemonMessage {
        ....
        repeated string learnableMoves = 10;
}

Now when I use Protobuf method to add a collection (which is empty) like this :

message.addAllLearnableMoves(someEmptyListOfString);

Now when I create a new List of String using this message I get one element in the list which is an Empty List.

This is how I create List of string using the message :

new ArrayList<>(message.getLearnableMovesList())

This array list contains an empty string element. So I debugged the message and evaluated 2 conditions and found weird results.

message.getLearnableMovesList()//clearly shows empty list

     (com.google.protobuf.UnmodifiableLazyStringList) [] //Empty

message.getLearnableMovesList().size()//shows the size of list is 1
     (int) 1 //Size is 1

Has anyone faces any similar problems? Is there any way to resolve this?


问:
Why do these two images not wanna go on top of each other?
http://lucasdebelder.be/googledoodle/

I want to have the planet (bottom image) on top of the top image (the blue background/space). I have a main div class:"center" set on 'position: absolute' and around both of those images is separately a div wrapped with position: relative; but somehow they don't want to go and sit on top of each other, I've also tried it with z-index but that doesn't work either.

Thanks in advance.

答:
i changed all css. Here sample:

```<code>.center {
    position: relative;
    text-align: center;
    width: 900px;
    margin: auto;
    overflow: hidden;
    height: 500px;
}
.space_achtergrond {
    width: 100%;
    z-index: 0;
    position: absolute;
    height: auto;
    bottom: 0;
}
.planeet_achtergrond {
    width: 100%;
    height: auto;
    z-index: 100;
    position: absolute;
    bottom: -15px;
}
form {
    position: absolute;
    bottom: 15px;
    z-index: 999;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
}
</code>```

use overflow:hidden outer div.

if you want place divs inside a div with position:absolute, use position:relative for parent div.

if you want to stick a div bottom, use only bottom:0

Body:
i changed all css. Here sample:

.center {
    position: relative;
    text-align: center;
    width: 900px;
    margin: auto;
    overflow: hidden;
    height: 500px;
}
.space_achtergrond {
    width: 100%;
    z-index: 0;
    position: absolute;
    height: auto;
    bottom: 0;
}
.planeet_achtergrond {
    width: 100%;
    height: auto;
    z-index: 100;
    position: absolute;
    bottom: -15px;
}
form {
    position: absolute;
    bottom: 15px;
    z-index: 999;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
}

use overflow:hidden outer div.

if you want place divs inside a div with position:absolute, use position:relative for parent div.

if you want to stick a div bottom, use only bottom:0


问:
Employee Classes - Python
Write a class named Employee that holds the following data about an employee in attributes: name, ID number, department, and job title.

Once you have written the class, write a program that creates three Employee objects to hold the following data:

Susan Meyers - 47899 - Accounting - Vice President
Mark Jones - 39119 - IT - Programmer
Joy Rogers - 81774 - Manufacturing - Engineer

^ This is the problem I'm stuck on. I believe I have the first part of the code correct, but I don't understand what to do for the second part of the program to create Employee objects.

Here is my code so far...

emp.py file

```<code>#create a class named Employee
class Employee:

    #initialize the attributes
    def __init__(self, name, id, department, title):
        self.__name = name
        self.__id = id
        self.__department = department
        self.__title = title

    #set the attributes
    def set_name(self, name):
        self.__name = name

    def set_id(self, id):
        self.__id = id

    def set_department(self, department):
        self.__department = department

    def set_title(self, title):
        self.__title = title

    #return the attributes
    def get_name(self):
        return self.__name

    def get_id(self):
        return self.__id

    def get_department(self):
        return self.__department

    def get_title(self):
        return self.__title

    #return the objects state as a string

    def __str__(self):
        return 'Name: ' + self.__name + \
               '\nID number: ' + self.__id + \
               '\nDepartment: ' + self.__department + \
               '\nTitle: ' + self.__title
</code>```

and here is my main function where the second part is going to go...

```<code> import emp

def main():
    #Create three employee objects
    emp1 = emp.Employee('name', 'id', 'department', 'title')
    emp2 = emp.Employee('name', 'id', 'department', 'title')
    emp3 = emp.Employee('name', 'id', 'department', 'title')

    #create three Employee objects for each attribute
    emp1.set_name('Susan Meyers')
    emp1.set_id('47899')
    emp1.set_department('Accounting')
    emp1.set_title('Vice President')

    emp2.set_name('Mark Jones')
    emp2.set_id('39119')
    emp2.set_department('IT')
    emp2.set_title('Programmer')

    emp3.set_name('Joy Rogersr')
    emp3.set_id('81774')
    emp3.set_department('Manufacturing')
    emp3.set_title('Engineer')

    print()
    print(emp1)
    print()
    print(emp2)
    print()
    print(emp3)

main()
</code>```

So with this code, I am now getting the correct answer of this:

```<code>Employee 1:
Name: Susan Meyers
ID number: 47899
Department: Accounting
Title: Vice President

Employee 2:
Name: Mark Jones
ID number: 39119
Department: IT
Title: Programmer

Employee 3:
Name: Joy Rogers
ID number: 81774
Title: Programmer

Process finished with exit code 0
</code>```

答:
Take a look at this

You have inpored you python file emp.py that has the class 'Employee' with import emp statement.
Now ,

```<code>emp1=emp.Employee('kee',1,'CSE','SE')
print emp1
</code>```

Will create the object and stores its pointer to emp1.

Title: Employee Classes - Python

Body:
Write a class named Employee that holds the following data about an employee in attributes: name, ID number, department, and job title.

Once you have written the class, write a program that creates three Employee objects to hold the following data:

Susan Meyers - 47899 - Accounting - Vice President
Mark Jones - 39119 - IT - Programmer
Joy Rogers - 81774 - Manufacturing - Engineer

^ This is the problem I'm stuck on. I believe I have the first part of the code correct, but I don't understand what to do for the second part of the program to create Employee objects.

Here is my code so far...

emp.py file

#create a class named Employee
class Employee:

    #initialize the attributes
    def __init__(self, name, id, department, title):
        self.__name = name
        self.__id = id
        self.__department = department
        self.__title = title

    #set the attributes
    def set_name(self, name):
        self.__name = name

    def set_id(self, id):
        self.__id = id

    def set_department(self, department):
        self.__department = department

    def set_title(self, title):
        self.__title = title

    #return the attributes
    def get_name(self):
        return self.__name

    def get_id(self):
        return self.__id

    def get_department(self):
        return self.__department

    def get_title(self):
        return self.__title

    #return the objects state as a string

    def __str__(self):
        return 'Name: ' + self.__name + \
               '\nID number: ' + self.__id + \
               '\nDepartment: ' + self.__department + \
               '\nTitle: ' + self.__title

and here is my main function where the second part is going to go...

 import emp

def main():
    #Create three employee objects
    emp1 = emp.Employee('name', 'id', 'department', 'title')
    emp2 = emp.Employee('name', 'id', 'department', 'title')
    emp3 = emp.Employee('name', 'id', 'department', 'title')

    #create three Employee objects for each attribute
    emp1.set_name('Susan Meyers')
    emp1.set_id('47899')
    emp1.set_department('Accounting')
    emp1.set_title('Vice President')

    emp2.set_name('Mark Jones')
    emp2.set_id('39119')
    emp2.set_department('IT')
    emp2.set_title('Programmer')

    emp3.set_name('Joy Rogersr')
    emp3.set_id('81774')
    emp3.set_department('Manufacturing')
    emp3.set_title('Engineer')

    print()
    print(emp1)
    print()
    print(emp2)
    print()
    print(emp3)

main()

So with this code, I am now getting the correct answer of this:

Employee 1:
Name: Susan Meyers
ID number: 47899
Department: Accounting
Title: Vice President

Employee 2:
Name: Mark Jones
ID number: 39119
Department: IT
Title: Programmer

Employee 3:
Name: Joy Rogers
ID number: 81774
Title: Programmer

Process finished with exit code 0

Body:
Take a look at this

You have inpored you python file emp.py that has the class 'Employee' with import emp statement.
Now ,

emp1=emp.Employee('kee',1,'CSE','SE')
print emp1

Will create the object and stores its pointer to emp1.


问:
Laravel error (Invalid datetime format: 1292 Incorrect date value)
I`m trying to create page for add user details to database via form values.it gives me this error when I press the submit button.

Here is my migration field.

```<code> $table->date('gce_ol_year');
</code>```

Here is the relevant form attribute

```<code>     <div class="form-group">
        <label>GCE(O/L) Year:</label>
    <input class="form-control" name="gce_ol_year" type="month" value="2011-08" id="example-month-input">
  </div>
</code>```

Here is the relevant controller attribute

```<code>$item ->gce_ol_year = $request ->gce_ol_year;
</code>```

How can I fix this error?

答:
In your controller add Carbon

```<code>$item->gce_ol_year = \Carbon\Carbon::parse($request->gce_ol_year);
</code>```

If it still does not work, fix the value in your input value to include the day like value="2011-08-01".

WHY?

Because your input is of Datetime format. If you want to only save the year, change your migration from $table->datetime('gce_ol_year') to $table->string('gce_ol_year'). If you don't want to use a string, integer could also work.

ContentLicense: CC BY-SA 4.0

Body:
I`m trying to create page for add user details to database via form values.it gives me this error when I press the submit button.

Here is my migration field.

 $table->date('gce_ol_year');

Here is the relevant form attribute

        GCE(O/L) Year:
    <input class="form-control" name="gce_ol_year" type="month" value="2011-08" id="example-month-input">

Here is the relevant controller attribute

$item ->gce_ol_year = $request ->gce_ol_year;

How can I fix this error?

Body:
In your controller add Carbon

$item->gce_ol_year = \Carbon\Carbon::parse($request->gce_ol_year);

If it still does not work, fix the value in your input value to include the day like value="2011-08-01".

WHY?

Because your input is of Datetime format. If you want to only save the year, change your migration from $table->datetime('gce_ol_year') to $table->string('gce_ol_year'). If you don't want to use a string, integer could also work.


问:
Two parts, consolidate Column A while adding corresponding values from Column B
I am trying to add values in Column B based on data in Column A.  Additionally I am looking to remove duplicates from Column A in a separate output on another sheet.  Here is how the data looks:

Excel Screenshot

I've tried SUMIF and VLOOKUP based on some similar posts but neither have worked.  I know I could use remove duplicates manually but would like to have a formula solution such that the data is automatically consolidated.

Thank you in advance.

答:
You can do this using formula to avoid manual consolidation, try the below set of formulas

In the cell A2, enter the below formula

```<code>=IFERROR(INDEX($F$2:$F$7, MATCH(0, INDEX(COUNTIF($A$1:A1, $F$2:$F$7), 0, 0), 0)), "")
</code>```

In the cell B2, enter the below formula

```<code>=if(A2="","",SUMIF($F$2:$F$7,A2,$G$2:$G$7))
</code>```

The $F$2:$F$7 and $G$2:$G$7 references in the above formulas are the data. If it is from different sheet, then you may need to replace these accordingly.

Once you enter the same in A2 and B2, copy the same in rest of the rows, and you will get what you want.

Body:
You can do this using formula to avoid manual consolidation, try the below set of formulas

In the cell A2, enter the below formula

=IFERROR(INDEX($F$2:$F$7, MATCH(0, INDEX(COUNTIF($A$1:A1, $F$2:$F$7), 0, 0), 0)), "")

In the cell B2, enter the below formula

=if(A2="","",SUMIF($F$2:$F$7,A2,$G$2:$G$7))

The $F$2:$F$7 and $G$2:$G$7 references in the above formulas are the data. If it is from different sheet, then you may need to replace these accordingly.

Once you enter the same in A2 and B2, copy the same in rest of the rows, and you will get what you want.


问:
In the process of React / Redux development, what is the proper way to install bootstrap?
I could do npm install --save bootstrap, but then it sits in node_modules.

One way is downloading the zip file and pulling needed files from it, but it doesn't feel you are using the standard ways of npm / webpack. So what is the standard way of doing it?

答:
You need to install some dependencies to configure Bootstrap in react

First install the following loaders and dependencies

```<code>npm install react react-dom bootstrap babel-preset-react --save

npm install webpack css-loader style-loader file-loader url-loader babel-core babel-loader babel-preset-es2015 --save-dev
</code>```

Now in your webpack you need to configure these loaders

```<code>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      },
      {
        test: /\.png$/,
        loader: "url-loader?limit=100000"
      },
      {
        test: /\.jpg$/,
        loader: "file-loader"
      },
      {
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff'
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream'
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file'
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml'
      }
    ]
  },
};
</code>```

After this you need to import Bootstrap css in your entry file for example index.js like

```<code>import 'bootstrap/dist/css/bootstrap.css';
</code>```

Body:
You need to install some dependencies to configure Bootstrap in react

First install the following loaders and dependencies

npm install react react-dom bootstrap babel-preset-react --save

npm install webpack css-loader style-loader file-loader url-loader babel-core babel-loader babel-preset-es2015 --save-dev

Now in your webpack you need to configure these loaders

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      },
      {
        test: /\.png$/,
        loader: "url-loader?limit=100000"
      },
      {
        test: /\.jpg$/,
        loader: "file-loader"
      },
      {
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff'
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream'
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file'
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml'
      }
    ]
  },
};

After this you need to import Bootstrap css in your entry file for example index.js like

import 'bootstrap/dist/css/bootstrap.css';


问:
Can't install selenium.webdriver.common.keys packages on python 2.7?
I have pip 9.0.1 and selenium 3.3.1 when a make pip install keys or try from selenium.webdriver.common.keys import keys from pycharm prompts this  Could not find a version that satisfies the requirement keys (from versions: ) No matching distribution found for keys

Im using pycharm last version. I search throw all the web but im newbie some sayed that is a network problem. Others that it's path environment are bad. But how im suposed to know all that the are millions of path enviroment i don't wanna screw up all i have made a project that i want to work in the future. I have been messing around with the terminal searching for archive's permission.. I wish i could give you more info about the problem but i search a lot and there isnt a quite good answer to begin to start solve the problem ..

Thanks ..

答:
It's included in the selenium package. You're just trying to import it wrong, Keys is capitalized.</p>

```<code>from selenium.webdriver.common.keys import Keys
</code>```

Body:
It's included in the selenium package. You're just trying to import it wrong, Keys is capitalized.

from selenium.webdriver.common.keys import Keys


问:
Angular 2 subscribe/unsubscribe through a button
I m trying to check the internet connection. Whenever connection is lost, i want to show an alert to the user and if user clicks on the refresh button i want to check the connection again... But when i unsubscribe when the connection is lost, i cant subscribe again.
what am i doing wrong ?

```<code>  constructor( private alertController: AlertController ){

                    let connection = this.checkConnection().subscribe(data => {
                      let alert = this.alertController.create({
                          title: 'Error',
                          subTitle: "You lost connection !",
                          buttons: [ {
                     text: 'Refresh',
                     handler: () => {
                     connection.subscribe();
                }}]
               });

                  if(data == false){
                      alert.present();
                      connection.unsubscribe();
                  }
              }
                 );

        checkConnection() {

                   return Observable
                    .interval(500)
                    .map(() => {
                    return navigator.onLine;
                    });
                 }
</code>```

UPDATE:

```<code>     let refresh$ = new Subject();
          let connection$ = refresh$.mergeMap(() => {
                        return Observable
                                .interval(50)
                                .map(() => navigator.onLine)
                                .filter(onLine => !onLine)
                                .take(1);
                      });

                      refresh$.next();

            connection$.subscribe(data => {
                    console.log(data)

            })
</code>```

答:
I think you're misunderstanding how observables work.

When you unsubscribe from an observable, you, as the consumer of the observable, are telling the observable that you no longer want any more values to be emitted to you. That's the signal to the observable to tear down its producer of values. So, unsubscribe is a one way street - there's no going back.

But you can probably still achieve what you want. From your code, it seems as though there is a navigator.onLine boolean that you can check to determine if you're currently online or not. And, if that boolean is false, you want to show a prompt telling the user that they are disconnected. In addition, it seems as though you want to stop checking for a connection at that point, until the user clicks 'Refresh' and then at that point, you want to resume checking.

If I'm getting your flow correct, then you can achieve that with using an observable chain.

Basically, you need multiple observables that you compose to get the effect that you want.

```<code>let refresh$ = new Subject();
let connection$ = refresh$.mergeMap(() => {
                    // on each refresh,
                    // create a new observable that checks every 50ms,
                    // but only emits if we are not online
                    return Observable
                            .interval(50)
                            .map(() => navigator.isOnline)
                            .filter(isOnline => !isOnline)  //only emit a when we go offline
                            .take(1);  // just need a single value to notify us to bring up our alert prompt
                  });
</code>```

So, in the example above, refresh$ is a Subject that you call next() on whenever you want to start checking for an offline connection. You'll call refresh.next() manually for your first check, and then call refresh$.next() on each press of the refresh button after that.

connection$ is your observable that you subscribe to where you show your alert box whenever it receives a value.

I may not have gotten your precise use case correct - i had to guess based on the code you submitted - but hopefully this gets you thinking as to how you can go about achieving the result you want.

Body:
I m trying to check the internet connection. Whenever connection is lost, i want to show an alert to the user and if user clicks on the refresh button i want to check the connection again... But when i unsubscribe when the connection is lost, i cant subscribe again.
what am i doing wrong ?

  constructor( private alertController: AlertController ){

                    let connection = this.checkConnection().subscribe(data => {
                      let alert = this.alertController.create({
                          title: 'Error',
                          subTitle: "You lost connection !",
                          buttons: [ {
                     text: 'Refresh',
                     handler: () => {
                     connection.subscribe();
                }}]
               });

                  if(data == false){
                      alert.present();
                      connection.unsubscribe();
                  }
              }
                 );

        checkConnection() {

                   return Observable
                    .interval(500)
                    .map(() => {
                    return navigator.onLine;
                    });
                 }

UPDATE:

     let refresh$ = new Subject();
          let connection$ = refresh$.mergeMap(() => {
                        return Observable
                                .interval(50)
                                .map(() => navigator.onLine)
                                .filter(onLine => !onLine)
                                .take(1);
                      });

                      refresh$.next();

            connection$.subscribe(data => {
                    console.log(data)

            })

Body:
I think you're misunderstanding how observables work.

When you unsubscribe from an observable, you, as the consumer of the observable, are telling the observable that you no longer want any more values to be emitted to you. That's the signal to the observable to tear down its producer of values. So, unsubscribe is a one way street - there's no going back.

But you can probably still achieve what you want. From your code, it seems as though there is a navigator.onLine boolean that you can check to determine if you're currently online or not. And, if that boolean is false, you want to show a prompt telling the user that they are disconnected. In addition, it seems as though you want to stop checking for a connection at that point, until the user clicks 'Refresh' and then at that point, you want to resume checking.

If I'm getting your flow correct, then you can achieve that with using an observable chain.

Basically, you need multiple observables that you compose to get the effect that you want.

let refresh$ = new Subject();
let connection$ = refresh$.mergeMap(() => {
                    // on each refresh,
                    // create a new observable that checks every 50ms,
                    // but only emits if we are not online
                    return Observable
                            .interval(50)
                            .map(() => navigator.isOnline)
                            .filter(isOnline => !isOnline)  //only emit a when we go offline
                            .take(1);  // just need a single value to notify us to bring up our alert prompt
                  });

So, in the example above, refresh$ is a Subject that you call next() on whenever you want to start checking for an offline connection. You'll call refresh.next() manually for your first check, and then call refresh$.next() on each press of the refresh button after that.

connection$ is your observable that you subscribe to where you show your alert box whenever it receives a value.

I may not have gotten your precise use case correct - i had to guess based on the code you submitted - but hopefully this gets you thinking as to how you can go about achieving the result you want.


问:
C++11 mode or settings for emacs?
I'm running Emacs 23.3.1 (Ubuntu, Oneiric package) and emacs doesn't appear to understand any of the new C++11 keywords, constexpr, thread_local, etc. Also it doesn't understand that '>>' is now permitted in template parameters, or the new 'enum class' syntax. Is there an updated or alternative module somewhere? Or failing that, some settings to make emacs more C++11 friendly in the mean time?</p>

答:
For me, the two most pressing pain points with font-locking of modern C++ code have been

the fact that auto is highlighted as a keyword (and not a type) and thus the following identifier would normally not higlight as a variable declaration, and

that highlighting simply goes crazy when presented with some code (for an example, try rtags' src/ClangIndexer.cpp) and then e.g fails to highlight top-level constructs such as function definitions.

After a bit of experimentation, I arrived at a solution that works well for me and addresses both points.

The first one is achieved by modifying lisp/progmodes/cc-langs.el (copying to one's load-path and then modifying also works) to remove "auto" from

```<code>(c-lang-defconst c-modifier-kwds
  "Keywords that can prefix normal declarations of identifiers
</code>```

and add it to c++-font-lock-extra-types (e.g. via Customize).

For the second one, emptying c++-font-lock-extra-types (except for keeping "auto") helps.

Title: C++11 mode or settings for emacs?

Body:
For me, the two most pressing pain points with font-locking of modern C++ code have been

the fact that auto is highlighted as a keyword (and not a type) and thus the following identifier would normally not higlight as a variable declaration, and

that highlighting simply goes crazy when presented with some code (for an example, try rtags' src/ClangIndexer.cpp) and then e.g fails to highlight top-level constructs such as function definitions.

After a bit of experimentation, I arrived at a solution that works well for me and addresses both points.

The first one is achieved by modifying lisp/progmodes/cc-langs.el (copying to one's load-path and then modifying also works) to remove "auto" from

(c-lang-defconst c-modifier-kwds
  "Keywords that can prefix normal declarations of identifiers

and add it to c++-font-lock-extra-types (e.g. via Customize).

For the second one, emptying c++-font-lock-extra-types (except for keeping "auto") helps.


问:
Doctrine does not generate database schema ManyToMany relation
Doctrine does not generate  database schema for ManyToMany relation.

c:\Bitnami\wampstack-5.6.30-0\apache2\htdocs\typejoy.biz>php vendor\doctrine\orm\bin\doctrine orm:schema-tool:create

creates two tables for two entities testChi and testPar, but does not create the @JoinTable "tParChiMTM".

ENtity testChi

```<code><?php

namespace LogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\ManyToMany;
use LogBundle\Entity\testPar;

/**
 * @Table(name="ttestchi")
 * @Entity()
 */
class testChi {

    /**
     * @var integer
     *
     * @Column(name="id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
/** @Column ( name="name", type="string", length=50, unique=false, nullable=true) */
     private $name;

/** @ManyToMany ( targetEntity="testPar", mappedBy="chiMTM") */
     private $parMTM;

    public function __construct() {
        $this->chiMTM = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Get name
     *
     * @return integer
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name
     * @param integer $name
     * @return name
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

  //make you have to serialize, deserialize entity here ???
    /**
     * Get parMTM
     *
     * @return LogBundle\Entity\ParMTM
     */
    public function getParMTM()
    {
        return $this->parMTM;
    }

    /**
     * Remove parMTM
     *
     * @param \LogBundle\Entity\testPar $parMTM
     */
    public function removeParMTM (\LogBundle\Entity\testPar $parMTM)
    {
        if ( $this->hasParMTM($parMTM) ) {
            $this->parMTM->removeElement($parMTM);
        }
    }

    /**
     * Add parMTM
     *
     * @param \LogBundle\Entity\testPar $parMTM
     *
     * @return ParMTM
     */
    public function addParMTM(\LogBundle\Entity\testPar $parMTM)
    {
        if ( !$this->hasParMTM($parMTM) ) {
            $this->parMTM[] = $parMTM;
        }

        return $this;
    }

    /**
     * @param \LogBundle\Entity\testPar $parMTM
     * @return bool
     */
    public function hasParMTM($parMTM)
    {
        if( $this->getParMTM() ) {
            return $this->getParMTM()->contains($parMTM);
        }
    }

    /**
     * Return Entity as string
     *
     * @return string String representation of this class
     */
    public function __toString()
    {
        return strval($this->id);
    }

 }
</code>```

Entity testPar

```<code><?php

namespace LogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\ManyToMany;
use LogBundle\Entity\testChi;

/**
 * @Table(name="ttestpar")
 * @Entity()
 */
class testPar {

    /**
     * @var integer
     *
     * @Column(name="id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
/** @Column ( name="name", type="string", length=50, unique=false, nullable=true) */
     private $name;

/** @ManyToMany ( targetEntity="testChi", inversedBy="parMTM") */
/** @JoinTable ( name="tParChiMTM") */
     private $chiMTM;

    public function __construct() {
        $this->chiMTM = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Get name
     *
     * @return integer
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name
     * @param integer $name
     * @return name
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

  //make you have to serialize, deserialize entity here ???
    /**
     * Get chiMTM
     *
     * @return LogBundle\Entity\ChiMTM
     */
    public function getChiMTM()
    {
        return $this->chiMTM;
    }

    /**
     * Remove chiMTM
     *
     * @param \LogBundle\Entity\testChi $chiMTM
     */
    public function removeChiMTM (\LogBundle\Entity\testChi $chiMTM)
    {
        if ( $this->hasChiMTM($chiMTM) ) {
            $this->chiMTM->removeElement($chiMTM);
        }
    }

    /**
     * Add chiMTM
     *
     * @param \LogBundle\Entity\testChi $chiMTM
     *
     * @return ChiMTM
     */
    public function addChiMTM(\LogBundle\Entity\testChi $chiMTM)
    {
        if ( !$this->hasChiMTM($chiMTM) ) {
            $this->chiMTM[] = $chiMTM;
        }

        return $this;
    }

    /**
     * @param \LogBundle\Entity\testChi $chiMTM
     * @return bool
     */
    public function hasChiMTM($chiMTM)
    {
        if( $this->getChiMTM() ) {
            return $this->getChiMTM()->contains($chiMTM);
        }
    }

    /**
     * Return Entity as string
     *
     * @return string String representation of this class
     */
    public function __toString()
    {
        return strval($this->id);
    }

 }
</code>```

c:\Bitnami\wampstack-5.6.30-0\apache2\htdocs\typejoy.biz>php vendor\doctrine\orm\bin\doctrine orm:schema-tool:create

creates two tables, but does not create the @JoinTable "tParChiMTM".

答:
The reason was in annotations :

CORRECT

```<code>/**
 * @ManyToMany ( targetEntity="testPar", mappedBy="chiMTM") */

/**
 *  @ManyToMany ( targetEntity="testChi", inversedBy="parMTM")
 * ( name="tParChiMTM") */
     private $chiMTM;
</code>```

You can not start each line with /**, only the first line shall contain this, the subsequent lines can start only with single *.

WRONG:

```<code>/** @ManyToMany ( targetEntity="testChi", inversedBy="parMTM") */
/** @JoinTable ( name="tParChiMTM") */
</code>```

Body:
Doctrine does not generate  database schema for ManyToMany relation.

c:\Bitnami\wampstack-5.6.30-0\apache2\htdocs\typejoy.biz>php vendor\doctrine\orm\bin\doctrine orm:schema-tool:create

creates two tables for two entities testChi and testPar, but does not create the @JoinTable "tParChiMTM".

ENtity testChi

<?php

namespace LogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\ManyToMany;
use LogBundle\Entity\testPar;

/**
 * @Table(name="ttestchi")
 * @Entity()
 */
class testChi {

    /**
     * @var integer
     *
     * @Column(name="id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
/** @Column ( name="name", type="string", length=50, unique=false, nullable=true) */
     private $name;

/** @ManyToMany ( targetEntity="testPar", mappedBy="chiMTM") */
     private $parMTM;

    public function __construct() {
        $this->chiMTM = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Get name
     *
     * @return integer
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name
     * @param integer $name
     * @return name
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

  //make you have to serialize, deserialize entity here ???
    /**
     * Get parMTM
     *
     * @return LogBundle\Entity\ParMTM
     */
    public function getParMTM()
    {
        return $this->parMTM;
    }

    /**
     * Remove parMTM
     *
     * @param \LogBundle\Entity\testPar $parMTM
     */
    public function removeParMTM (\LogBundle\Entity\testPar $parMTM)
    {
        if ( $this->hasParMTM($parMTM) ) {
            $this->parMTM->removeElement($parMTM);
        }
    }

    /**
     * Add parMTM
     *
     * @param \LogBundle\Entity\testPar $parMTM
     *
     * @return ParMTM
     */
    public function addParMTM(\LogBundle\Entity\testPar $parMTM)
    {
        if ( !$this->hasParMTM($parMTM) ) {
            $this->parMTM[] = $parMTM;
        }

        return $this;
    }

    /**
     * @param \LogBundle\Entity\testPar $parMTM
     * @return bool
     */
    public function hasParMTM($parMTM)
    {
        if( $this->getParMTM() ) {
            return $this->getParMTM()->contains($parMTM);
        }
    }

    /**
     * Return Entity as string
     *
     * @return string String representation of this class
     */
    public function __toString()
    {
        return strval($this->id);
    }

 }

Entity testPar

<?php

namespace LogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\ManyToMany;
use LogBundle\Entity\testChi;

/**
 * @Table(name="ttestpar")
 * @Entity()
 */
class testPar {

    /**
     * @var integer
     *
     * @Column(name="id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
/** @Column ( name="name", type="string", length=50, unique=false, nullable=true) */
     private $name;

/** @ManyToMany ( targetEntity="testChi", inversedBy="parMTM") */
/** @JoinTable ( name="tParChiMTM") */
     private $chiMTM;

    public function __construct() {
        $this->chiMTM = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Get name
     *
     * @return integer
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name
     * @param integer $name
     * @return name
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

  //make you have to serialize, deserialize entity here ???
    /**
     * Get chiMTM
     *
     * @return LogBundle\Entity\ChiMTM
     */
    public function getChiMTM()
    {
        return $this->chiMTM;
    }

    /**
     * Remove chiMTM
     *
     * @param \LogBundle\Entity\testChi $chiMTM
     */
    public function removeChiMTM (\LogBundle\Entity\testChi $chiMTM)
    {
        if ( $this->hasChiMTM($chiMTM) ) {
            $this->chiMTM->removeElement($chiMTM);
        }
    }

    /**
     * Add chiMTM
     *
     * @param \LogBundle\Entity\testChi $chiMTM
     *
     * @return ChiMTM
     */
    public function addChiMTM(\LogBundle\Entity\testChi $chiMTM)
    {
        if ( !$this->hasChiMTM($chiMTM) ) {
            $this->chiMTM[] = $chiMTM;
        }

        return $this;
    }

    /**
     * @param \LogBundle\Entity\testChi $chiMTM
     * @return bool
     */
    public function hasChiMTM($chiMTM)
    {
        if( $this->getChiMTM() ) {
            return $this->getChiMTM()->contains($chiMTM);
        }
    }

    /**
     * Return Entity as string
     *
     * @return string String representation of this class
     */
    public function __toString()
    {
        return strval($this->id);
    }

 }

c:\Bitnami\wampstack-5.6.30-0\apache2\htdocs\typejoy.biz>php vendor\doctrine\orm\bin\doctrine orm:schema-tool:create

creates two tables, but does not create the @JoinTable "tParChiMTM".

Body:
The reason was in annotations :

CORRECT

/**
 * @ManyToMany ( targetEntity="testPar", mappedBy="chiMTM") */

/**
 *  @ManyToMany ( targetEntity="testChi", inversedBy="parMTM")
 * ( name="tParChiMTM") */
     private $chiMTM;

You can not start each line with /**, only the first line shall contain this, the subsequent lines can start only with single *.

WRONG:

/** @ManyToMany ( targetEntity="testChi", inversedBy="parMTM") */
/** @JoinTable ( name="tParChiMTM") */


答:
Import emp.py

```<code>    from emp import Employee
</code>```

Go ahead and create 3 Employee objects:

```<code>    def main():
        emp1 = Employee("name", id, department, title)
        emp2 = Employee("name", id, department, title)
        emp3 = Employee("name", id, department, title)
</code>```

Title: Employee Classes - Python

Body:
Import emp.py

    from emp import Employee

Go ahead and create 3 Employee objects:

    def main():
        emp1 = Employee("name", id, department, title)
        emp2 = Employee("name", id, department, title)
        emp3 = Employee("name", id, department, title)


问:
c# how to get just date from sql server date column and display in textbox
when i get the date from the selected row and send to a text box in a different form it shows as 04/01/2017 00:00:00 but i just want the date.
this is how i select the row and get the date from the table.

```<code>public static string Dedob;

private void dgvEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dgvEmployee.Rows[e.RowIndex];
        Dename = row.Cells["Name"].Value.ToString();
        Dedob =  row.Cells["DOB"].Value.ToString();
        Deaddress = row.Cells["ADDRESS"].Value.ToString();
        Deusername = row.Cells["USERNAME"].Value.ToString();
    }
}
</code>```

then on form2

```<code>tbdob.Text = form1.Dedob;
</code>```

then the textbox just shows 04/01/2017 00:00:00 how can i remove the time :/

any help would be appreciated.

答:
try:

```<code>    Dedob =  row.Cells["DOB"].Value.ToString("d MMM yyyy");
</code>```

You can see more templates here: https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx

Body:
when i get the date from the selected row and send to a text box in a different form it shows as 04/01/2017 00:00:00 but i just want the date.
this is how i select the row and get the date from the table.

public static string Dedob;

private void dgvEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dgvEmployee.Rows[e.RowIndex];
        Dename = row.Cells["Name"].Value.ToString();
        Dedob =  row.Cells["DOB"].Value.ToString();
        Deaddress = row.Cells["ADDRESS"].Value.ToString();
        Deusername = row.Cells["USERNAME"].Value.ToString();
    }
}

then on form2

tbdob.Text = form1.Dedob;

then the textbox just shows 04/01/2017 00:00:00 how can i remove the time :/

any help would be appreciated.

Body:
try:

    Dedob =  row.Cells["DOB"].Value.ToString("d MMM yyyy");

You can see more templates here: https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx


问:
How to create a fragment of an activity in android studio?
I want to call a new activity when a list item is clicked from the drawer. I searched over the internet and what I got was to call the fragment of that activity. So, I wanted to know how to make a fragment of an activity.

P.S.- Sorry, if this question is silly. I'm still a noob.

答:
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Here the full explanation from android official developer guide.

Also on android developer guide you can find the code to properly create and use a fragment.

Create a fragment class:

```<code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_view, container, false);
    }
}
</code>```

Then you have to add the fragment to the activity layout:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

    <fragment android:name="com.example.android.fragments.ExampleFragment"
              android:id="@+id/example_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

</LinearLayout>
</code>```

Finally you can add the layout to your activity:

```<code>import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_from_exampleLayout);
    }
}
</code>```

I took those examples from the android developer guide that i put above.

Anyway if i have understood your question this code should work:

```<code>list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            Intent intent = new Intent(ThisClass.this, ClassToCall.class);
            startActivity(intent);

    }
});
</code>```

This will start a new activity when a list item is clicked using an intent, but it doesn't need fragments.

Body:
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Here the full explanation from android official developer guide.

Also on android developer guide you can find the code to properly create and use a fragment.

Create a fragment class:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_view, container, false);
    }
}

Then you have to add the fragment to the activity layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

    <fragment android:name="com.example.android.fragments.ExampleFragment"
              android:id="@+id/example_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

</LinearLayout>

Finally you can add the layout to your activity:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_from_exampleLayout);
    }
}

I took those examples from the android developer guide that i put above.

Anyway if i have understood your question this code should work:

list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            Intent intent = new Intent(ThisClass.this, ClassToCall.class);
            startActivity(intent);

    }
});

This will start a new activity when a list item is clicked using an intent, but it doesn't need fragments.


问:
Javascript - Callback after all nested forEach loops are completed
I'm sure this is a fairly simple task, but I'm not able to wrap my head around it at this time. I've got a nested set of forEach loops, and I need to have a callback for when all the loops are done running.

I'm open to using async.js

This is what I'm working with:

```<code>const scanFiles = function(accounts, cb) {
  let dirs = ['pending', 'done', 'failed'];
  let jobs = [];

  accounts.forEach(function(account) {
    dirs.forEach(function(dir) {
      fs.readdir(account + '/' + dir, function(err, files) {
         files.forEach(function(file) {
            //do something
            //add file to jobs array
            jobs.push(file);
         });
      });
    });
  });

  //return jobs array once all files have been added
  cb(jobs);
}
</code>```

答:
If you use asyc library https://caolan.github.io/async/docs.html, your code will be much faster. (forEach is blocking [JavaScript, Node.js: is Array.forEach asynchronous?). </p>

```<code>const scanFiles = function (accounts, cb) {
let dirs = ['pending', 'done', 'failed'];
let jobs = [];

async.each(accounts, function (account, accountCallback) {
    async.each(dirs, function (dir, dirCallback) {

        fs.readdir(account + '/' + dir, function (err, files) {
            if(err) console.log(err);

            async.each(files, function (file, fileCallback) {
                //do something
                //add file to jobs array
                jobs.push(file);
                fileCallback();

            }, dirCallback);

        });
    }, accountCallback);
}, function (err) {
    //return jobs array once all files have been added
    if (err) throw err;
    cb(jobs)
});
</code>```

<p>};</p>

Body:
I'm sure this is a fairly simple task, but I'm not able to wrap my head around it at this time. I've got a nested set of forEach loops, and I need to have a callback for when all the loops are done running.

I'm open to using async.js

This is what I'm working with:

const scanFiles = function(accounts, cb) {
  let dirs = ['pending', 'done', 'failed'];
  let jobs = [];

  accounts.forEach(function(account) {
    dirs.forEach(function(dir) {
      fs.readdir(account + '/' + dir, function(err, files) {
         files.forEach(function(file) {
            //do something
            //add file to jobs array
            jobs.push(file);
         });
      });
    });
  });

  //return jobs array once all files have been added
  cb(jobs);
}

Body:
If you use asyc library https://caolan.github.io/async/docs.html, your code will be much faster. (forEach is blocking [JavaScript, Node.js: is Array.forEach asynchronous?).

const scanFiles = function (accounts, cb) {
let dirs = ['pending', 'done', 'failed'];
let jobs = [];

async.each(accounts, function (account, accountCallback) {
    async.each(dirs, function (dir, dirCallback) {

        fs.readdir(account + '/' + dir, function (err, files) {
            if(err) console.log(err);

            async.each(files, function (file, fileCallback) {
                //do something
                //add file to jobs array
                jobs.push(file);
                fileCallback();

            }, dirCallback);

        });
    }, accountCallback);
}, function (err) {
    //return jobs array once all files have been added
    if (err) throw err;
    cb(jobs)
});

};


问:
HERE WeGo access to running application information
Is there a way to programmatically request current status information (location, tta, speed) from an active instance of the HERE WeGo app?  I know I can use an alternate method for location but would like to access TTA and possibly additional current status information from a running GPS program without requiring the user to input data. Example: Current time, location, speed, ETA(TTA), logged with the click of a button or voice command.  I would specifically like to be able to use HERE because of its off-line capabilities.</p>

答: No that is not possible. It would violate the user's privacy and allow an unsuspecting application to track the user :)</p>


答:
If the row.Cells["DOB"].Value type is DateTime, than:</p>

```<code>Dedob =  row.Cells["DOB"].Value.ToString("MM/dd/yyyy");
</code>```

Title: c# how to get just date from sql server date column and display in textbox

Body:
If the row.Cells["DOB"].Value type is DateTime, than:

Dedob =  row.Cells["DOB"].Value.ToString("MM/dd/yyyy");


问:
Compression to Improve Hard Disk Write Performance
On a modern system can local hard disk write speeds be improved by compressing the output stream?

This question derives from a case I'm working with where a program serially generates and dumps around 1-2GB of text logging data to a raw text file on the hard disk and I think it is IO bound. Would I expect to be able to decrease runtimes by compressing the data before it goes to disk or would the overhead of compression eat up any gain I could get? Would having an idle second core affect this?

I know this would be affected by how much CPU is being used to generate the data so rules of thumb on how much idle CPU time would be needed would be good.

I recall a video talk where someone used compression to improve read speeds for a database but IIRC compressing is a lot more CPU intensive than decompressing.

答:
This used to be something that could improve performance in quite a few applications way back when.  I'd guess that today it's less likely to pay off, but it might in your specific circumstance, particularly if the data you're logging is easily compressible,

However, as Shog9 commented:

Rules of thumb aren't going to help
  you here. It's your disk, your CPU,
  and your data. Set up a test case and
  measure throughput and CPU load with
  and without compression - see if it's
  worth the tradeoff.

OwnerDisplayName: BCS

LastEditorDisplayName: BCS

OwnerDisplayName: Michael Burr