问:
Wait for service to start - while loop
I'm looking to improve my code to handle a service not starting. Consider this simple code:

```<code>while ((Get-Service $service).Status -eq 'Stopped')
{
    Start-Service $service -ErrorAction SilentlyContinue -Verbose:$false
}
</code>```

If there is a problem starting the service, I see WARNING: Waiting for service '...' to Start... 2-3 times, then it starts usually. My problem is when the service will not start due to error, the while is stuck in an infinite loop.

Is there a better way to handle this, and avoid the infinite loop?

答:
Here's one way to start a service and wait for a specified amount of time for it to start. It returns 0 if the service started successfully, or an error code if 1) the service doesn't exist, 2) the service is already running, or 3) the code timed out waiting for the service to start.</p>

```<code>$ERROR_SERVICE_REQUEST_TIMEOUT = 1053
$ERROR_SERVICE_ALREADY_RUNNING = 1056
$ERROR_SERVICE_DOES_NOT_EXIST  = 1060

function Start-Service {
  param(
    [String] $serviceName,
    [Int32] $timeoutSeconds
  )
  $service = Get-Service $serviceName
  if ( -not $service ) {
    return $ERROR_SERVICE_DOES_NOT_EXIST
  }
  if ( $service.Status -eq [ServiceProcess.ServiceControllerStatus]::Running ) {
    return $ERROR_SERVICE_ALREADY_RUNNING
  }
  $timeSpan = New-Object Timespan 0,0,$timeoutSeconds
  try {
    $service.Start()
    $service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running, $timeSpan)
    return 0
  }
  catch [Management.Automation.MethodInvocationException],[ServiceProcess.TimeoutException] {
    return $ERROR_SERVICE_REQUEST_TIMEOUT
  }
}
</code>```

Title: Wait for service to start - while loop

Body:
I'm looking to improve my code to handle a service not starting. Consider this simple code:

while ((Get-Service $service).Status -eq 'Stopped')
{
    Start-Service $service -ErrorAction SilentlyContinue -Verbose:$false
}

If there is a problem starting the service, I see WARNING: Waiting for service '...' to Start... 2-3 times, then it starts usually. My problem is when the service will not start due to error, the while is stuck in an infinite loop.

Is there a better way to handle this, and avoid the infinite loop?

Body:
Here's one way to start a service and wait for a specified amount of time for it to start. It returns 0 if the service started successfully, or an error code if 1) the service doesn't exist, 2) the service is already running, or 3) the code timed out waiting for the service to start.

$ERROR_SERVICE_REQUEST_TIMEOUT = 1053
$ERROR_SERVICE_ALREADY_RUNNING = 1056
$ERROR_SERVICE_DOES_NOT_EXIST  = 1060

function Start-Service {
  param(
    [String] $serviceName,
    [Int32] $timeoutSeconds
  )
  $service = Get-Service $serviceName
  if ( -not $service ) {
    return $ERROR_SERVICE_DOES_NOT_EXIST
  }
  if ( $service.Status -eq [ServiceProcess.ServiceControllerStatus]::Running ) {
    return $ERROR_SERVICE_ALREADY_RUNNING
  }
  $timeSpan = New-Object Timespan 0,0,$timeoutSeconds
  try {
    $service.Start()
    $service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running, $timeSpan)
    return 0
  }
  catch [Management.Automation.MethodInvocationException],[ServiceProcess.TimeoutException] {
    return $ERROR_SERVICE_REQUEST_TIMEOUT
  }
}


来源: stackexchange

问:
Return all records with Eloquent query filters

I'm building a form which allows the user to select from several options and retrieve results from the DB based on these. I've been successful in creating my query filters, but am running into issues when I want to add the option 'select records from all time' instead of by a specific year.

My code is as follows:

```<code>$order = (new Order)->newQuery();

    if ($request->has('report')) {
        if($request->report === 'all') {
            $order->where('status', 'approved')
            ->orWhere('status', 'pending')
            ->orWhere('status', 'denied');
        } else {
            $order->where('status', $request->report);
        }
    }

    if($request->has('supervisors')) {
        $order->where(function($query) use ($request) {
            foreach ($request->supervisors as $key => $supervisor) {
                if ($key == 0)  {
                    $query->where('supervisor_id', $supervisor);
                } else {
                    $query->orWhere('supervisor_id', $supervisor);
                }
            }
        });
    }

    if($request->dateFrom !== null) {
        $order->whereBetween('created_at',
            [
                Carbon::parse($request->dateFrom),
                Carbon::parse($request->dateTo)
            ]);
    } elseif($request->has('year') !== null) {
        $order->whereYear('created_at', $request->year);
    }
    if(isset($request->allTime)) {
        $order;
    }
    return $order->get();
</code>```

The problematic part is here:

```<code>if(isset($request->allTime)) {
    $order;
}
</code>```

My understanding is that if no filtering has taken place with dateFrom or Year then it should just return all items by default, but this isn't happening. I just receive a blank result.

Any ideas?

答:
If you dont need to add any filtering for all time then you can just omit it or leave the if block blank

```<code>if(isset($request->allTime)) { }
</code>```

You should also fix $request->has('year') !== null because it looks like 2 conditions in one
$request->has('year') always returns true or false depending on whether year exists in Request. true or false will never be == null

```<code>$request->has('year') && $request->year !== null
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm building a form which allows the user to select from several options and retrieve results from the DB based on these. I've been successful in creating my query filters, but am running into issues when I want to add the option 'select records from all time' instead of by a specific year.

My code is as follows:

$order = (new Order)->newQuery();

    if ($request->has('report')) {
        if($request->report === 'all') {
            $order->where('status', 'approved')
            ->orWhere('status', 'pending')
            ->orWhere('status', 'denied');
        } else {
            $order->where('status', $request->report);
        }
    }

    if($request->has('supervisors')) {
        $order->where(function($query) use ($request) {
            foreach ($request->supervisors as $key => $supervisor) {
                if ($key == 0)  {
                    $query->where('supervisor_id', $supervisor);
                } else {
                    $query->orWhere('supervisor_id', $supervisor);
                }
            }
        });
    }

    if($request->dateFrom !== null) {
        $order->whereBetween('created_at',
            [
                Carbon::parse($request->dateFrom),
                Carbon::parse($request->dateTo)
            ]);
    } elseif($request->has('year') !== null) {
        $order->whereYear('created_at', $request->year);
    }
    if(isset($request->allTime)) {
        $order;
    }
    return $order->get();

The problematic part is here:

if(isset($request->allTime)) {
    $order;
}

My understanding is that if no filtering has taken place with dateFrom or Year then it should just return all items by default, but this isn't happening. I just receive a blank result.

Any ideas?

Body:
If you dont need to add any filtering for all time then you can just omit it or leave the if block blank

if(isset($request->allTime)) { }

You should also fix $request->has('year') !== null because it looks like 2 conditions in one
$request->has('year') always returns true or false depending on whether year exists in Request. true or false will never be == null

$request->has('year') && $request->year !== null


问:
EditPlus Regex - How to replace group 1 followed by 0
I'm trying to replace with Regex's EditPlus, values that contain comma-separated numbers and two decimal points, so they have 3 decimal points, adding a zero to the end. But my attempts eventually delete the value of the group instead of adding the zero to the end. The text is from a csv file, tab separated, over 12000 lines.

The Text to replace (just example):

```<code>Car 48,589  27,56   NULL    NULL
Bike    NULL    12,258  NULL    45,896
Bus NULL    11,23   NULL    85,25
Truck   23,45   NULL    45,458  NULL
Boat    45,89   74,12   NULL    NULL
</code>```

Find Regex String:

```<code>(\t[0-9]{2},[0-9]{2})([^0-9]|$)
</code>```

Replace Regex String attempts:

```<code>1. $10$2   // delete String Group 1
2. $1\0$2  // make a copy of group 1 until the end
</code>```

The Expected result is:

```<code>Car 48,589  27,560  NULL    NULL
Bike    NULL    12,258  NULL    45,896
Bus NULL    11,230  NULL    85,250
Truck   23,450  NULL    45,458  NULL
Boat    45,890  74,120  NULL    NULL
</code>```

答:
The problem is that expression \10 does not mean \1 (the first fount instance) and 0. It means found instance number ten.

You can do the replacement in two steps: add some placeholder symbols that are not in you file, e.x. @@@@@

And in the second step replace the placeholder with 0

And the result is:

The \2 is needed to correctly work with the numbers at the end of line, like in line number 3.

Body:
I'm trying to replace with Regex's EditPlus, values that contain comma-separated numbers and two decimal points, so they have 3 decimal points, adding a zero to the end. But my attempts eventually delete the value of the group instead of adding the zero to the end. The text is from a csv file, tab separated, over 12000 lines.

The Text to replace (just example):

Car 48,589  27,56   NULL    NULL
Bike    NULL    12,258  NULL    45,896
Bus NULL    11,23   NULL    85,25
Truck   23,45   NULL    45,458  NULL
Boat    45,89   74,12   NULL    NULL

Find Regex String:

(\t[0-9]{2},[0-9]{2})([^0-9]|$)

Replace Regex String attempts:

1. $10$2   // delete String Group 1
2. $1\0$2  // make a copy of group 1 until the end

The Expected result is:

Car 48,589  27,560  NULL    NULL
Bike    NULL    12,258  NULL    45,896
Bus NULL    11,230  NULL    85,250
Truck   23,450  NULL    45,458  NULL
Boat    45,890  74,120  NULL    NULL


问:
jQuery - run a function when DOM changes
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

```<code>$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});
</code>```

Now I have several events hooked on different elements that can append html in the DOM, like:

```<code>$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});
</code>```

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(

答:
I have encountered a problem like this as well. There is no true way to have something run on dom change (that I know of). I have approached this via two different methods

Have a setTimeout calling the function every second or have the function triggered when the user moves the mouse. Both of these can caused slow downs if not handled correctly

Have a function called when the ajax is done. So just have doAjax() called every time you complete a query by having it in the success section.

You could also have the first ajax query bound the body tag, so anytime the user clicks something the ajax event would fire, and then check if the right criteria is met.

Edit: This might work. Add $("BODY ID/CLASS").change(function () {}); Not totally sure, as I am not the most fluent in jQuery.

ContentLicense: CC BY-SA 2.5

Body:
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});

Now I have several events hooked on different elements that can append html in the DOM, like:

$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(


问:
Android: resolving language resources (in app and in Play Store)
I'm a bit confused by the guidance here.

Prior to Android 7, it seems that the device tries the specific locale e.g. fr_FR and if there is no such language resource then it strips the country and looks in fr.

On this basis, given that I don't have a vast army of translators to translate into each and every local variant, I've been sticking translations into the parent folders, e.g. fr, de etc.  If the user doesn't like the variant being delivered, there is an option in the app to choose any other.

For Android 7 and above, the guidance seems to be to:

store resources in the most common parent dialect. For example, if you were storing Spanish resources in the values-es-rUS directory before, move them into the values-b+es+419 directory, which contains Latin American Spanish.

But surely if your Spanish translations are actually for es_US, then it doesn't make any sense to treat them as es_419 (because es_US and es_419 are different)?  Why not just leave them under es_US, because it seems that for Android 7 they would be found anyway (by traversing up and then down the tree) even if the device was set to es_ES and es_US was the only thing available?

For a small developer, with just one translation available for a particular language (e.g. only es_ES) is it still a reasonable strategy to stick it into the parent locale folder (e.g. es)?  That way, it should be delivered for any requested variant of Spanish, both pre and post Android 7?  But this goes against the above guidance.

And as for translations of app descriptions in the Play Store, it seems to me that there isn't any hierarchical resolution logic like there is in Android... there just seems to be a flat list of languages.  So say you only have a translation for Spanish (Spain) available, then in order for that to be used in the US, Latin America and Spain (on the basis that a different variant of Spanish is better than a machine translation of English), do you need to copy that into the US Spanish, Latin American Spanish AND Spanish Spanish slots... there isn't a generic "Spanish" slot?

答:
for the app, use generic folder as long as you don't have a regional variation : aka "es" not "es-US".
So the translation will be used by all ES speakers. (no matter the region)

then you may just overwrite some words like "color vs colour" for en-US vs en-GB.

for the google play store: I'm not sure. as the there is NO "es", but only "es-ES","es-xxx". and the logic seem to be different.


问:
Button to change color of
I am trying to make an interactive periodic table of elements. I need to change the background color of more  with the classname "nemetale" when a button is clicked. It's not working, I don't know what I am doing wrong.

There is the button

```<code> <button onclick="document.getElementsByClassName('.nemetale').style.backgroundColor = 'red';">Nemetale</button>
</code>```

There is one of the s.

```<code><table class="tabel_periodic">
  <!--Randul 1-->
  <tr>

   <td class="nemetale">
    <strong>1</strong><br>
    <acronym>H</acronym><br>
    <em>Hidrogen</em><br>
    <i>1,008</i>
   </td>
 ...
</code>```

答:
Make it like below by adding function:

```<code><button onclick="changeBackgroundColor()">Nemetale</button>
</code>```

put this into

```<code><script>
  function changeBackgroundColor(){
    document.getElementsByClassName('nemetale')[0].style.backgroundColor = 'red';
  }
</script>
</code>```

Title: Button to change color of <td>

Body:
I am trying to make an interactive periodic table of elements. I need to change the background color of more  with the classname "nemetale" when a button is clicked. It's not working, I don't know what I am doing wrong.

There is the button

 <button onclick="document.getElementsByClassName('.nemetale').style.backgroundColor = 'red';">Nemetale</button>

There is one of the s.

    1

    <acronym>H</acronym>

    Hidrogen

    1,008

 ...

Body:
Make it like below by adding function:

<button onclick="changeBackgroundColor()">Nemetale</button>

put this into

<script>
  function changeBackgroundColor(){
    document.getElementsByClassName('nemetale')[0].style.backgroundColor = 'red';
  }
</script>


问:
Replacing Text in Word with Currency from Excel
First time post, please go easy...
I wrote some code to replace placeholder text in a Word template, with text from an Excel file. (e.g. replaces all occurrences of Business_Name with Buddy's Dog Grooming) The code runs, and replaces everything as planned, but when it comes to replacing the Word text Total_FMV with the currency from Excel of $100,000, the code spits out 100000. Any thoughts on how I can get the text in Word to read $100,000 without the decimals?</p>

```<code>Private Sub OnSite_Builder_Click()

Template = "C:\Users\Me\Desktop\TEMPLATE.docx"
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(Template, ReadOnly:=True)

    wrdApp.Visible = True

    wrdApp.Selection.Find.ClearFormatting
    wrdApp.Selection.Find.Replacement.ClearFormatting

'Total FMV
With wrdApp.Selection.Find
    .Text = "Total_FMV"
    .Replacement.Text = Range("C28")
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

    wrdApp.Selection.Find.Execute Replace:=wdReplaceAll

End Sub
</code>```

答:
You could replace your .Replacement.Text = Range("C28") with:</p>

```<code>.Replacement.Text = Range("C28").NumberFormat = "$#,###"
</code>```

Body:
First time post, please go easy...
I wrote some code to replace placeholder text in a Word template, with text from an Excel file. (e.g. replaces all occurrences of Business_Name with Buddy's Dog Grooming) The code runs, and replaces everything as planned, but when it comes to replacing the Word text Total_FMV with the currency from Excel of $100,000, the code spits out 100000. Any thoughts on how I can get the text in Word to read $100,000 without the decimals?

Private Sub OnSite_Builder_Click()

Template = "C:\Users\Me\Desktop\TEMPLATE.docx"
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(Template, ReadOnly:=True)

    wrdApp.Visible = True

    wrdApp.Selection.Find.ClearFormatting
    wrdApp.Selection.Find.Replacement.ClearFormatting

'Total FMV
With wrdApp.Selection.Find
    .Text = "Total_FMV"
    .Replacement.Text = Range("C28")
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

    wrdApp.Selection.Find.Execute Replace:=wdReplaceAll

End Sub

Body:
You could replace your .Replacement.Text = Range("C28") with:

.Replacement.Text = Range("C28").NumberFormat = "$#,###"


问:
Css - Align
s
I am new to web design and I have 2
 tags that contain Announcement and Welcome data. I would like to align these next to eachother. But instead they are on top of each other.

I have tried floating one div left and the other right while giving widths to the divs. But I am still having a few issues. I am trying to align the announcement-area and welcome-area divs. Here is my code:

HTML:

```<code><body>
        <div id="page-wrap">
            <ul id="nav" align="center">
                <li class="home"><a href="#">Home</a></li>
            <li class="directory"><a ref="#">Directory</a></li>
                <li class="calender"><a href="#">Calender</a></li>
                <li class="photos"><a href="#">Photos</a></li>
                <li class="links"><a href="#">Links</a></li>
            </ul>

            <div id="main-content">
                <div id="welcome-area">
                    <img src="Images/welcome-header.jpg" alt="header top" />
                    <div id="welcome-content">
                        <p>
                            Welcome to the official website of the Lambda Chi Alpha Delta Beta Zeta Chapter at NSU.
                            This site will be used to inform members of events and show everyone what the fraternity
                            is up too. Take a look around!
                        </p>
                    </div>
                </div>

                <div id="announcements-area">
                    <img src="Images/announcements-top.jpg" alt="announcement top" />
                    <div id="announcements-content">
                        <h4 class="announcement-header">Website is Live!</h4>
                        <p class="metadata">Friday, 1/21/2011</p>

                        <p>
                            The new website for the Delta Beta Zeta Chapter
                            of Lambda Chi Alpha is now live. Welcome!
                        </p>
                    </div>
                </div>

                <div class="clear"></div>
            </div>

            <div id="footer">
            </div>
        </div>
</body>
</code>```

CSS:

```<code>#page-wrap{
    width:1040px;
    margin: 0 auto;
    background-image: url('../Images/content-background.jpg');
    background-repeat:repeat-y;
    }
    #main-content{
        padding-top:10x;
        padding-right:50px;
        padding-left:70px;
        }
        #announcements-area{
            background-image: url('../Images/announcements-content.jpg');
            background-repeat: repeat-y;
            float:left;
            }
            #announcements-content{
                padding-left:15px;
                padding-right:730px;
                padding-bottom:10px;
            }
        #welcome-area{
            background-image: url('../Images/welcome-content.jpg');
            background-repeat: repeat-y;
            float:right;
            }
            #welcome-content{

                padding-left:15px;
                padding-right:350px;
                padding-bottom:10px;
            }
#footer{
    min-height:185px;
    background-image: url('../Images/footer.jpg');
    background-repeat:no-repeat;
}
</code>```

Here is a screenshot of what the divs look like right now. They are on top of eachother. I want them next to eachother.

答:
Try removing the large padding on the left side of the welcome content and the right side of the announcement content.  That's probably making them wider than they appear and they can't fit side-by-side within the frame.

An invaluable tool to look at things like this is the firebug extension and the web developer toolbar.  Once you have firebug installed, you can right click on an element on the page, click "Inspect Element" and then you can mouse over it in the source and see where the paddings and margins are contributing to the size and placement of the elements.

In ZAX, Bryan

Title: Css - Align <Div>s

Body:
I am new to web design and I have 2
 tags that contain Announcement and Welcome data. I would like to align these next to eachother. But instead they are on top of each other.

I have tried floating one div left and the other right while giving widths to the divs. But I am still having a few issues. I am trying to align the announcement-area and welcome-area divs. Here is my code:

HTML:

Home

Directory

Calender

Photos

Links

                            Welcome to the official website of the Lambda Chi Alpha Delta Beta Zeta Chapter at NSU.
                            This site will be used to inform members of events and show everyone what the fraternity
                            is up too. Take a look around!

Website is Live!

Friday, 1/21/2011

                            The new website for the Delta Beta Zeta Chapter
                            of Lambda Chi Alpha is now live. Welcome!

CSS:

#page-wrap{
    width:1040px;
    margin: 0 auto;
    background-image: url('../Images/content-background.jpg');
    background-repeat:repeat-y;
    }
    #main-content{
        padding-top:10x;
        padding-right:50px;
        padding-left:70px;
        }
        #announcements-area{
            background-image: url('../Images/announcements-content.jpg');
            background-repeat: repeat-y;
            float:left;
            }
            #announcements-content{
                padding-left:15px;
                padding-right:730px;
                padding-bottom:10px;
            }
        #welcome-area{
            background-image: url('../Images/welcome-content.jpg');
            background-repeat: repeat-y;
            float:right;
            }
            #welcome-content{

                padding-left:15px;
                padding-right:350px;
                padding-bottom:10px;
            }
#footer{
    min-height:185px;
    background-image: url('../Images/footer.jpg');
    background-repeat:no-repeat;
}

Here is a screenshot of what the divs look like right now. They are on top of eachother. I want them next to eachother.


问:
SQL writing today -1460 days?
I have to change the code each day to make sure that is 4 years in the past based on list date. When I use '?' to set a parameter in excel it takes a long time to run. How can I hard code today -1460 days into this code? Below is current code. </p>

```<code>Select
MLB8.PROG_REPORT_ACCT_NUM_AND_PRACCT,
DCGI.Date_Listed,
DB.INITIAL_BALANCE,
DS.Last_Payment,
LV.Amt_Paid_On_Acct,
DB.Principal_Balance,
MLB7.INVENT_INVEN2
From
Clnt_General CG
Inner Join
Dbtr_Clnt_Generl_Inf DCGI on CG.Client_Num1=DCGI.Client
Inner Join
Dbtr_Status DS on DCGI.Account_Num1=DS.Account_Num1
Inner Join
Dbtr_Balances DB on DCGI.Account_Num1=DB.Account_Num1
Inner Join
Debtor_Master_Logic_Blocks7 MLB7 on DCGI.Account_Num1=MLB7.Account_Num1
Inner Join
Debtor_Master_Logic_Blocks8 MLB8 on DCGI.Account_Num1=MLB8.Account_Num1
Inner Join
Letter_Variables LV on DCGI.Account_Num1=LV.Account_Num1
Where
CG.Client_Num1=?
And
DCGI.Date_Listed>?
</code>```

答:
I didn't know you are using sql server.
other (normal :) ) DB support what I wrote.

try:

```<code>DCGI.Date_Listed>=DATEADD(day, -1460, cast(getdate() As Date))
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL writing today -1460 days?

Body:
I have to change the code each day to make sure that is 4 years in the past based on list date. When I use '?' to set a parameter in excel it takes a long time to run. How can I hard code today -1460 days into this code? Below is current code.

Select
MLB8.PROG_REPORT_ACCT_NUM_AND_PRACCT,
DCGI.Date_Listed,
DB.INITIAL_BALANCE,
DS.Last_Payment,
LV.Amt_Paid_On_Acct,
DB.Principal_Balance,
MLB7.INVENT_INVEN2
From
Clnt_General CG
Inner Join
Dbtr_Clnt_Generl_Inf DCGI on CG.Client_Num1=DCGI.Client
Inner Join
Dbtr_Status DS on DCGI.Account_Num1=DS.Account_Num1
Inner Join
Dbtr_Balances DB on DCGI.Account_Num1=DB.Account_Num1
Inner Join
Debtor_Master_Logic_Blocks7 MLB7 on DCGI.Account_Num1=MLB7.Account_Num1
Inner Join
Debtor_Master_Logic_Blocks8 MLB8 on DCGI.Account_Num1=MLB8.Account_Num1
Inner Join
Letter_Variables LV on DCGI.Account_Num1=LV.Account_Num1
Where
CG.Client_Num1=?
And
DCGI.Date_Listed>?

Body:
I didn't know you are using sql server.
other (normal :) ) DB support what I wrote.

try:

DCGI.Date_Listed>=DATEADD(day, -1460, cast(getdate() As Date))


问:
Problems with converting a C# code to VB.net
I have problems to convert the following piece of code into vb.net because I am not so experienced with lambda expressions. Especially the last line is my problem. Teleric Code Converter doesn't help me because of the last line. Could somebody help me? </p>

```<code>int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
</code>```

答:
Not used VB since VB6(!) - this works though:

```<code>    Dim numbers() = {1, 3, 4, 9, 2, 4}
    Dim numToRemove As Integer = 4
    Dim numIndex As Integer = Array.IndexOf(numbers, numToRemove)
    numbers = numbers.Where(Function(ByVal val, ByVal idx) idx <> numIndex).ToArray()
</code>```

(That's just a disclaimer as the above might not be best practices etc!)

Body:
I have problems to convert the following piece of code into vb.net because I am not so experienced with lambda expressions. Especially the last line is my problem. Teleric Code Converter doesn't help me because of the last line. Could somebody help me?

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();

Body:
Not used VB since VB6(!) - this works though:

    Dim numbers() = {1, 3, 4, 9, 2, 4}
    Dim numToRemove As Integer = 4
    Dim numIndex As Integer = Array.IndexOf(numbers, numToRemove)
    numbers = numbers.Where(Function(ByVal val, ByVal idx) idx <> numIndex).ToArray()

(That's just a disclaimer as the above might not be best practices etc!)


问:
A decent way to transform a const list reference argument then pass to another function?
Sorry for not addressing problem precisely in the title, here's the thing.

Let's say I'm an adapter, and I have to redirect a function to another,

which are listing below:

My owner would call my function and pass an argument to me first like this:

```<code>void receive (const list<Obj>& Larr){
    // do some transforming
    // Then call "send"
}
</code>```

And then I have to call someone else, but with the different container argument:

```<code>void send (const vector<Obj*>& Varr){
    // ....
}
</code>```

Because of the constraints of 'const', so apparently, I CANNOT just do 'push_back' pointer of the elements iteration by iteration like:

```<code>void receive (const list<Obj>& Larr){
    for (list<Obj>::const_iterator it = Larr.begin(); it != Larr.end(); it++)
        // vec is my class member
        vec.push_back(&(*it));    // compile error: no match function
        // Because expected element is (Obj*) rather than (const Obj*)
}
</code>```

So the only way I think of is to COPY every element in Larr, then push_back their address in the vector, which I'm about to broadcast :

```<code>void receive (const list<Obj>& Larr){
    vector<Obj> tmp(Larr.size());
    int i = 0;
    for (list<Obj>::const_iterator it = Larr.begin(); it != Larr.end(); it++, i++){
        tmp[i] = *it;
    }
    for (i = 0; i < tmp.size(); i++)
        vec.push_back(&tmp[i]);

    // Call send here;
    send(vec);  // The lifecyle of tmp is ensured, no need to worry about
}
</code>```

Now my question is, under this scenario, not allowing changing interface, is there any way that I can achieve this without copying every single element in the function?

答:
You are correct about the constraints of const, by definition it cannot be modified.  Your only options are to convert the list to a vector or overload your send method to support list types.

You may use the range based constructor to simplify your vector construction i.e.

```<code>std::vector<Obj> tmp{ Larr.begin(), Larr.end() };
</code>```

Body:
Sorry for not addressing problem precisely in the title, here's the thing.

Let's say I'm an adapter, and I have to redirect a function to another,

which are listing below:

My owner would call my function and pass an argument to me first like this:

void receive (const list<Obj>& Larr){
    // do some transforming
    // Then call "send"
}

And then I have to call someone else, but with the different container argument:

void send (const vector<Obj*>& Varr){
    // ....
}

Because of the constraints of 'const', so apparently, I CANNOT just do 'push_back' pointer of the elements iteration by iteration like:

void receive (const list<Obj>& Larr){
    for (list<Obj>::const_iterator it = Larr.begin(); it != Larr.end(); it++)
        // vec is my class member
        vec.push_back(&(*it));    // compile error: no match function
        // Because expected element is (Obj*) rather than (const Obj*)
}

So the only way I think of is to COPY every element in Larr, then push_back their address in the vector, which I'm about to broadcast :

void receive (const list<Obj>& Larr){
    vector<Obj> tmp(Larr.size());
    int i = 0;
    for (list<Obj>::const_iterator it = Larr.begin(); it != Larr.end(); it++, i++){
        tmp[i] = *it;
    }
    for (i = 0; i < tmp.size(); i++)
        vec.push_back(&tmp[i]);

    // Call send here;
    send(vec);  // The lifecyle of tmp is ensured, no need to worry about
}

Now my question is, under this scenario, not allowing changing interface, is there any way that I can achieve this without copying every single element in the function?

Body:
You are correct about the constraints of const, by definition it cannot be modified.  Your only options are to convert the list to a vector or overload your send method to support list types.

You may use the range based constructor to simplify your vector construction i.e.

std::vector<Obj> tmp{ Larr.begin(), Larr.end() };


答:
Working fiddle.

getElementsByClassName() : Returns an array-like object of all child elements which have all of the given class names.

The function .getElementsByClassmame() doesn't exist you should use .getElementsByClassName().

Since the .getElementsByClassName() return a list of elements you should return the first element instead using [0] like :

```<code>document.getElementsByClassName('nemetale')[0].style.backgroundColor  = 'red';
</code>```

var trs = document.getElementsByClassName('nemetale');

document.getElementById('change_color').addEventListener('click', function() {
  for (var i = 0; i < trs.length; i++) {
    changeColor(trs[i]);
  }
});

function changeColor(tr) {
  tr.style.backgroundColor = 'red';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="change_color">Nemetale</button>

<table class="tabel_periodic">
  <tr>
    <td class="nemetale">
      <strong>1</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>1,008</i>
    </td>
  </tr>
  <tr>
    <td class="nemetale">
      <strong>2</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>2,008</i>
    </td>
  </tr>
  <tr>
    <td class="nemetale">
      <strong>3</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>3,008</i>
    </td>
  </tr>
</table></code>```

Title: Button to change color of <td>

Body:
Working fiddle.

getElementsByClassName() : Returns an array-like object of all child elements which have all of the given class names.

The function .getElementsByClassmame() doesn't exist you should use .getElementsByClassName().

Since the .getElementsByClassName() return a list of elements you should return the first element instead using [0] like :

document.getElementsByClassName('nemetale')[0].style.backgroundColor  = 'red';

var trs = document.getElementsByClassName('nemetale');

document.getElementById('change_color').addEventListener('click', function() {
  for (var i = 0; i < trs.length; i++) {
    changeColor(trs[i]);
  }
});

function changeColor(tr) {
  tr.style.backgroundColor = 'red';
}

<button id="change_color">Nemetale</button>

<table class="tabel_periodic">
  <tr>
    <td class="nemetale">
      <strong>1</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>1,008</i>
    </td>
  </tr>
  <tr>
    <td class="nemetale">
      <strong>2</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>2,008</i>
    </td>
  </tr>
  <tr>
    <td class="nemetale">
      <strong>3</strong><br>
      <acronym>H</acronym><br>
      <em>Hidrogen</em><br>
      <i>3,008</i>
    </td>
  </tr>
</table>


问:
C linked list problems
I really need your help with my program. I'm a newbie in C and need to create a linked list in my project.

I use xcode on macOS.
My code is here:

```<code>typedef struct person
{
    char name[500];
    char telnum[16];
    char wohnort[500];
    struct person *next;

}person;

person *head=NULL;
void einlesen()
{
    person *p;
    char name[30];
    char telnum[16];
    char wohnort[30];
    //char buff1[15], buff2[15];
    int cnt=0;

    FILE *fp=fopen("Data2.txt", "r");
    if(fp==NULL)
    {
        printf("File konnte nicht geoeffnet werden!\n");
        exit(1);
    }
    while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)
    {

        cnt++;

        printf("Datei gefunden!\nDaten:%s, %s, %s\n", name, telnum, wohnort);

        if(head == NULL){
            head = (person*)malloc(sizeof(person));
            strcpy(head->name, name);
            strcpy(head->telnum, telnum);
            strcpy(head->wohnort, wohnort);
            head->next = NULL;
        }
        else{
            p = head;
            while(p->next != NULL)
            {
                p = p->next;
            }

            p->next = (person*)malloc(sizeof(person));
            strcpy(p->next->name,name);
            strcpy(p->next->telnum,telnum);
            strcpy(p->next->wohnort,wohnort);
            p->next->next = NULL;
        }

    }
    printf("Die Daten von %d Personen wurden eingelesen!\n\n", cnt);
    fclose(fp);
}

void addieren()
{   char name[30];
    char telnum[16];
    char wohnort[30];
    person *p = head;

    printf("Bitte den Namen der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", name);
    while(getchar() != '\n');
    printf("\nBitte die Telefunnumer der hinzufuegenden Person eingeben:\n");
    scanf(" %15s", telnum);
    while(getchar() != '\n');
    printf("\nBitte den Wohnort der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", wohnort);
    while(getchar() != '\n');

    if(p==NULL) return;
    while(p->next)
    {
        p=p->next;
    }
    p->next = (person*)malloc(sizeof(person));
    strcpy(p->next->name, name);
    strcpy(p->next->telnum, telnum);
    strcpy(p->next->wohnort, wohnort);
    p->next->next=NULL;
}
</code>```

and i have this in my main function:

```<code>int main()
{
    person *p1=head;

    einlesen();
    addieren();
    while(p1 !=NULL)
    {
        printf("Namen: %s\n", p1->name);
        p1=p1->next;
    }

    return 0;

}
</code>```

It's already read the data from the file and I wanted to add some new records to it and the print to the screen. This returns 0 and doesn't really print the list on the screen.

Later I need to add more functions to my program, like:
-deletefromlist
-modify element
-search in the linked list
-save to file
-and a menue

答:
I see no particular question, so I'll start by pointing out some errors, and perhaps when you've added a question (which ends in a question mark) you can ping me for an update.

```<code>while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)
</code>```

Let me just start off by saying I'm a huge advocate of reading the manual before using a function for the first time. In fact, I'm pretty sure it's expected of us, as programmers. Granted, we must learn which manuals to seek, because the internet is a dangerous place and people do occasionally lie. The OpenGroup manuals are good. For example, if you type into Google "Opengroup fscanf", you'll find the manual for fscanf, which will answer many questions I', sure...

The manual states that all whitespace is treated the same, as a directive which attempts to read and discard as much whitespace as possible. Hence, a plain space has the same meaning to \t in a format specifier (at least, in your context)... so if your question is something along the lines of "Why are all whitespaces treated the same?" then the answer is "because that's what the manual says it should do."

The fixed width field you're reading into can fail to translate, in a scenario the manual also describes where-by the first character tested failed to match the criteria ([A-z ], which looks highly suspect, and you'll probably realise by reading the manual that this isn't what you want). That would result in a return value (from scanf) of 0, which, to your code, looks like a successful read.

Here's an idiomatic guideline: Let's first count the number of objects that you want to read into... Here they are, copied verbatim from your code: &name, &telnum, &wohnort... There are three of them.

Now, take that number, three, and compare it to what fscanf returns... If these two numbers match, then you can use all three arguments safely (though as I note below, they may not necessarily contain the values that you expect them to contain).

You also shouldn't use the & (address-of) operator here for name, telnum or wohnort. The address-of operator on a char [10] array would result in a char (*)[10] expression, where-as you most certainly want a plain vanilla char * expression. Hence, the correct thing to do is to let Cs implicit "array expression to pointer expression" conversion do that for you.

Below is probably closer to what you want. My advice regarding the [A-z ] thing is that you list out each of the characters you want to include in those brackets, or use [^...] if you want to list out each of the characters you want to exclude. To be clear, there are no ranges in C format strings, in case that's what your question was about. e.g.:

```<code>while(fscanf(fp," %29[qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM ] %s %s", name, telnum, wohnort)==3)
</code>```

Note that it isn't quite there, yet. There's the potential for 29 bytes of a 32 byte input to be read into that fixed width field, leaving three characters on the stream. Perhaps they're not space, in which case your whitespace directive will silently fail, and those remaining three characters will be treated as telnum.

You should try to read just one item per call to scanf, if only until you understand the corresponding manual.

No collection should ever require n calls to malloc to store n objects. If you manage to complete this (no doubt self-assigned) task, I suggest making it your next priority to allocate your list as multiple nodes per call to malloc... or better yet, the convenience you get not having to free() every string fscanf returns, you could benefit from the same technique; expect caller to allocate the list, passing you all the storage you need, as well as items to add, remove, etc from the list. All the function does is modify the objects passed in.

```<code>while(getchar() != '\n');
</code>```

Above you recognise that EOF can occur... what do you think getchar() will return when that happens? Not '\n', that's for sure, and it'll keep returning that (not `'\n') value indefinitely, hence an infinite loop. Trying to solve this problem complicates the loop a bit; you need storage for the character, e.g.:

```<code>int c;
while ((c = getchar()) != EOF && c != '\n');
</code>```

The clearer alternative to that is actually to use fread, e.g.

```<code>char c;
while (fread(&c, 1, 1, stdin) && c != '\n');
</code>```

Nonetheless, better yet, is using fscanf, according to how the manual explains (there are many other useful functionalities for you to read about A.S.A.P.). Do you think you can remember these two lines, after typing them ten or fifteen times in a row?

```<code>scanf("%*[^\n]");
getchar();
</code>```

Man... your code should always check malloc return values before they're used. How do we know your malloc calls aren't returning NULL, leading to a question which you haven't asked?

Title: C linked list problems

Body:
I really need your help with my program. I'm a newbie in C and need to create a linked list in my project.

I use xcode on macOS.
My code is here:

typedef struct person
{
    char name[500];
    char telnum[16];
    char wohnort[500];
    struct person *next;

}person;

person *head=NULL;
void einlesen()
{
    person *p;
    char name[30];
    char telnum[16];
    char wohnort[30];
    //char buff1[15], buff2[15];
    int cnt=0;

    FILE *fp=fopen("Data2.txt", "r");
    if(fp==NULL)
    {
        printf("File konnte nicht geoeffnet werden!\n");
        exit(1);
    }
    while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)
    {

        cnt++;

        printf("Datei gefunden!\nDaten:%s, %s, %s\n", name, telnum, wohnort);

        if(head == NULL){
            head = (person*)malloc(sizeof(person));
            strcpy(head->name, name);
            strcpy(head->telnum, telnum);
            strcpy(head->wohnort, wohnort);
            head->next = NULL;
        }
        else{
            p = head;
            while(p->next != NULL)
            {
                p = p->next;
            }

            p->next = (person*)malloc(sizeof(person));
            strcpy(p->next->name,name);
            strcpy(p->next->telnum,telnum);
            strcpy(p->next->wohnort,wohnort);
            p->next->next = NULL;
        }

    }
    printf("Die Daten von %d Personen wurden eingelesen!\n\n", cnt);
    fclose(fp);
}

void addieren()
{   char name[30];
    char telnum[16];
    char wohnort[30];
    person *p = head;

    printf("Bitte den Namen der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", name);
    while(getchar() != '\n');
    printf("\nBitte die Telefunnumer der hinzufuegenden Person eingeben:\n");
    scanf(" %15s", telnum);
    while(getchar() != '\n');
    printf("\nBitte den Wohnort der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", wohnort);
    while(getchar() != '\n');

    if(p==NULL) return;
    while(p->next)
    {
        p=p->next;
    }
    p->next = (person*)malloc(sizeof(person));
    strcpy(p->next->name, name);
    strcpy(p->next->telnum, telnum);
    strcpy(p->next->wohnort, wohnort);
    p->next->next=NULL;
}

and i have this in my main function:

int main()
{
    person *p1=head;

    einlesen();
    addieren();
    while(p1 !=NULL)
    {
        printf("Namen: %s\n", p1->name);
        p1=p1->next;
    }

    return 0;

}

It's already read the data from the file and I wanted to add some new records to it and the print to the screen. This returns 0 and doesn't really print the list on the screen.

Later I need to add more functions to my program, like:
-deletefromlist
-modify element
-search in the linked list
-save to file
-and a menue

Body:
I see no particular question, so I'll start by pointing out some errors, and perhaps when you've added a question (which ends in a question mark) you can ping me for an update.

while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)

Let me just start off by saying I'm a huge advocate of reading the manual before using a function for the first time. In fact, I'm pretty sure it's expected of us, as programmers. Granted, we must learn which manuals to seek, because the internet is a dangerous place and people do occasionally lie. The OpenGroup manuals are good. For example, if you type into Google "Opengroup fscanf", you'll find the manual for fscanf, which will answer many questions I', sure...

The manual states that all whitespace is treated the same, as a directive which attempts to read and discard as much whitespace as possible. Hence, a plain space has the same meaning to \t in a format specifier (at least, in your context)... so if your question is something along the lines of "Why are all whitespaces treated the same?" then the answer is "because that's what the manual says it should do."

The fixed width field you're reading into can fail to translate, in a scenario the manual also describes where-by the first character tested failed to match the criteria ([A-z ], which looks highly suspect, and you'll probably realise by reading the manual that this isn't what you want). That would result in a return value (from scanf) of 0, which, to your code, looks like a successful read.

Here's an idiomatic guideline: Let's first count the number of objects that you want to read into... Here they are, copied verbatim from your code: &name, &telnum, &wohnort... There are three of them.

Now, take that number, three, and compare it to what fscanf returns... If these two numbers match, then you can use all three arguments safely (though as I note below, they may not necessarily contain the values that you expect them to contain).

You also shouldn't use the & (address-of) operator here for name, telnum or wohnort. The address-of operator on a char [10] array would result in a char (*)[10] expression, where-as you most certainly want a plain vanilla char * expression. Hence, the correct thing to do is to let Cs implicit "array expression to pointer expression" conversion do that for you.

Below is probably closer to what you want. My advice regarding the [A-z ] thing is that you list out each of the characters you want to include in those brackets, or use [^...] if you want to list out each of the characters you want to exclude. To be clear, there are no ranges in C format strings, in case that's what your question was about. e.g.:

while(fscanf(fp," %29[qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM ] %s %s", name, telnum, wohnort)==3)

Note that it isn't quite there, yet. There's the potential for 29 bytes of a 32 byte input to be read into that fixed width field, leaving three characters on the stream. Perhaps they're not space, in which case your whitespace directive will silently fail, and those remaining three characters will be treated as telnum.

You should try to read just one item per call to scanf, if only until you understand the corresponding manual.

No collection should ever require n calls to malloc to store n objects. If you manage to complete this (no doubt self-assigned) task, I suggest making it your next priority to allocate your list as multiple nodes per call to malloc... or better yet, the convenience you get not having to free() every string fscanf returns, you could benefit from the same technique; expect caller to allocate the list, passing you all the storage you need, as well as items to add, remove, etc from the list. All the function does is modify the objects passed in.

while(getchar() != '\n');

Above you recognise that EOF can occur... what do you think getchar() will return when that happens? Not '\n', that's for sure, and it'll keep returning that (not `'\n') value indefinitely, hence an infinite loop. Trying to solve this problem complicates the loop a bit; you need storage for the character, e.g.:

int c;
while ((c = getchar()) != EOF && c != '\n');

The clearer alternative to that is actually to use fread, e.g.

char c;
while (fread(&c, 1, 1, stdin) && c != '\n');

Nonetheless, better yet, is using fscanf, according to how the manual explains (there are many other useful functionalities for you to read about A.S.A.P.). Do you think you can remember these two lines, after typing them ten or fifteen times in a row?

scanf("%*[^\n]");
getchar();

Man... your code should always check malloc return values before they're used. How do we know your malloc calls aren't returning NULL, leading to a question which you haven't asked?


答:
You have a typo: getElementsByClassmame, this isn't a valid JS method.

Use .querySelector instead:

```<code>document.querySelector('.nemetale')
</code>```

https://jsfiddle.net/d5dg0uw4/

Title: Button to change color of <td>

Body:
You have a typo: getElementsByClassmame, this isn't a valid JS method.

Use .querySelector instead:

document.querySelector('.nemetale')

https://jsfiddle.net/d5dg0uw4/


问:
how to handle both XmlHttpRequest(AJAX) and regular http requests in one spring mvc method?
currently my solution is

For AJAX:

```<code>@RequestMapping(value = "/verify", method = {RequestMethod.GET},
    headers = "x-requested-with=XMLHttpRequest")
    public
    @ResponseBody userTO
    void verifyForXHR(@RequestParam(required = true) String code,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            UserTO userTO = new SomeService().verifyEmail(code);
            return userTO;
        } catch (ExceptionABC ex) {
            response.setStatus(response.SC_BAD_REQUEST);
            return null;
        } catch (RuntimeException ex) {
              response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
              return null;
        }

    }
</code>```

For regular http requests:

```<code>@RequestMapping(value = "/verify", method = {RequestMethod.GET})
    public ModelAndView verify(@RequestParam(required = true) String code) {
        //get user to
        try {
            ModelAndView mav = new ModelAndView();
            UserTO userTO = new SomeService().verifyEmail code);

            mav.setViewName("somegoodpage");
            mav.addObject("user", userTO);
            return mav;
        } catch (ExceptionABC ex) {
                logger.error(ex, ex);
                ModelAndView mav = new ModelAndView("error page);
                return mav;
            }

        } catch (RuntimeException ex) {
            logger.error(ex.toString(), ex);
            ModelAndView mav = new ModelAndView("another error page");
            return mav;
        }

    }
</code>```

It would be super if I can merge them into one method. Please note they have different return type. The caller for AJAX requests are JavaScript so it needs JSON as http response body media type. For regular http requests, it needs a view(page) to be returned. Any suggestions would be greatly appreciated!

答: To have it all in one method, you can differentiate between the two by taking one extra parameter @RequestHeader(value = "x-requested-with:XMLHttpRequest", required = false) String ajax. Then you can check if (ajax == null) or not and take action accordingly.

Body:
currently my solution is

For AJAX:

@RequestMapping(value = "/verify", method = {RequestMethod.GET},
    headers = "x-requested-with=XMLHttpRequest")
    public
    @ResponseBody userTO
    void verifyForXHR(@RequestParam(required = true) String code,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            UserTO userTO = new SomeService().verifyEmail(code);
            return userTO;
        } catch (ExceptionABC ex) {
            response.setStatus(response.SC_BAD_REQUEST);
            return null;
        } catch (RuntimeException ex) {
              response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
              return null;
        }

    }

For regular http requests:

@RequestMapping(value = "/verify", method = {RequestMethod.GET})
    public ModelAndView verify(@RequestParam(required = true) String code) {
        //get user to
        try {
            ModelAndView mav = new ModelAndView();
            UserTO userTO = new SomeService().verifyEmail code);

            mav.setViewName("somegoodpage");
            mav.addObject("user", userTO);
            return mav;
        } catch (ExceptionABC ex) {
                logger.error(ex, ex);
                ModelAndView mav = new ModelAndView("error page);
                return mav;
            }

        } catch (RuntimeException ex) {
            logger.error(ex.toString(), ex);
            ModelAndView mav = new ModelAndView("another error page");
            return mav;
        }

    }

It would be super if I can merge them into one method. Please note they have different return type. The caller for AJAX requests are JavaScript so it needs JSON as http response body media type. For regular http requests, it needs a view(page) to be returned. Any suggestions would be greatly appreciated!


问:
How to display data required using a database value
I am new to crystal reports and I am trying to get round formulations.
I am trying to display certain data in a report by using a particular value from the database. All the data i need to display is within the value '1' of the database.
I have tried with an if statement, which seems to work but displays true and false instead of the actual data. Can anyone help me with this please?

```<code>if {database.column} = 1 then
    true
else
    false
</code>```

This is where I have got too, just need a little guidance please

答:
Try using the code below:</p>

```<code>if {database.column} = 1 then
    database.column
else
    0
</code>```

Body:
I am new to crystal reports and I am trying to get round formulations.
I am trying to display certain data in a report by using a particular value from the database. All the data i need to display is within the value '1' of the database.
I have tried with an if statement, which seems to work but displays true and false instead of the actual data. Can anyone help me with this please?

if {database.column} = 1 then
    true
else
    false

This is where I have got too, just need a little guidance please

Body:
Try using the code below:

if {database.column} = 1 then
    database.column
else
    0


问:
How can I create a function or a loop over dataframe names in R?
I'm a new programmer and I'm stuck with the creation of a function or loop to avoid repetition of the lines.

Here is part of my code:

```<code># Importing dataframes
R1 <- read.table("C:/Users/Data1.txt", header = TRUE)
R2 <- read.table("C:/Users/Data2.txt", header = TRUE)
R3 <- read.table("C:/Users/Data3.txt", header = TRUE)

# Taking only the colunms that I need from each dataframe
R1_dados <- R1[,c(1,8,11,14,24)]
R2_dados <- R2[,c(1,8,11,14,24)]
R3_dados <- R3[,c(1,8,11,14,24)]

# Adding some colunms
R1_dados$E <- c(0,100,200,300,400,500,600)
R2_dados$E <- c(0,100,200,300,400,500,600)
R3_dados$E <- c(0,100,200,300,400,500,600)

# Doing some math between columns from each dataframe
R1_dados$rETR = R1_dados$fvfm*R1_dados$E
R2_dados$rETR = R2_dados$fvfm*R2_dados$E
R3_dados$rETR = R3_dados$fvfm*R3_dados$E

# and so on...
</code>```

I was wondering if I can create an index of the replicas (R1, R2, and R3)

I'll be grateful if someone helps me. Thanks!

答:
You should loop on a file list.</p>

```<code>fileList <- c("Data1", "Data2", "Data3")
for (file in fileList){
  R <- read.table(paste0("C:/Users/", file, ".csv"))
  R_dados <- R[,c(1,8,11,14,24)]
  R_dados$E <- c(0,100,200,300,400,500,600)
  R_dados$rETR = R_dados$fvfm*R3_dados$E
  write.table(R_dados, file = paste0("C:/Users/", file, "_dados.csv"))
}
</code>```

Body:
I'm a new programmer and I'm stuck with the creation of a function or loop to avoid repetition of the lines.

Here is part of my code:

# Importing dataframes
R1 <- read.table("C:/Users/Data1.txt", header = TRUE)
R2 <- read.table("C:/Users/Data2.txt", header = TRUE)
R3 <- read.table("C:/Users/Data3.txt", header = TRUE)

# Taking only the colunms that I need from each dataframe
R1_dados <- R1[,c(1,8,11,14,24)]
R2_dados <- R2[,c(1,8,11,14,24)]
R3_dados <- R3[,c(1,8,11,14,24)]

# Adding some colunms
R1_dados$E <- c(0,100,200,300,400,500,600)
R2_dados$E <- c(0,100,200,300,400,500,600)
R3_dados$E <- c(0,100,200,300,400,500,600)

# Doing some math between columns from each dataframe
R1_dados$rETR = R1_dados$fvfm*R1_dados$E
R2_dados$rETR = R2_dados$fvfm*R2_dados$E
R3_dados$rETR = R3_dados$fvfm*R3_dados$E

# and so on...

I was wondering if I can create an index of the replicas (R1, R2, and R3)

I'll be grateful if someone helps me. Thanks!

Body:
You should loop on a file list.

fileList <- c("Data1", "Data2", "Data3")
for (file in fileList){
  R <- read.table(paste0("C:/Users/", file, ".csv"))
  R_dados <- R[,c(1,8,11,14,24)]
  R_dados$E <- c(0,100,200,300,400,500,600)
  R_dados$rETR = R_dados$fvfm*R3_dados$E
  write.table(R_dados, file = paste0("C:/Users/", file, "_dados.csv"))
}


问:
How can I delete data from two tables that have a relationship?
i have this database

i want to delete fax in Fax table and records in FaxData that have the same id of fax in Fax table
i created viewmodel view to connect the 2 tables
     using System.Web.Mvc;

```<code>namespace FaxProject.ViewModel
{
public class SendFaxVm
{

    public List<SelectListItem> Employees { set; get; }

    public int[] SelectedEmployees { set; get; }
    public Fax fax { set; get; }
    public int FaxId { set; get; }
    public string CompanyName { set; get; }
    public int Courier_Num { set; get; }
    public Nullable<int> NumberOfPages { get; set; }

    public string CompanyAddress { get; set; }
    public string ReceivingDate { get; set; }
    public string Attachment { get; set; }
    public string Subject { get; set; }

}
}
</code>```

this is the viewmodel

```<code>  public ActionResult Delete(int id,SendFaxVm vm,Fax fax)
    {
        foreach (var userId in vm.SelectedEmployees)
        {
            var faxdatadelete = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
            Db.FaxDatas.Remove(faxdatadelete);

            Db.SaveChanges();
        }

        var deletedfax = Db.Faxes.Single(f => f.Id == id);
        Db.Faxes.Remove(deletedfax);
        Db.SaveChanges();

        return RedirectToAction("FaxForm", "Fax");
    }
</code>```

and this is the action in fax controller .....
and this is the exception that i got when i try to delete (An exception of type 'System.NullReferenceException' occurred in FaxProject.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.)

答:
It should be:</p>

```<code>public ActionResult Delete(int id, SendFaxVm vm, Fax fax)
{
    if (SendFaxVm == null || Fax == null)
    {
        return RedirectToAction("FaxForm", "Fax");
    }

    foreach (var userId in vm.SelectedEmployees)
    {
        var faxdatadelete = Db.FaxDatas.FirstOrDefault(f => f.FaxId == fax.Id);
        if (faxdatadelete != null)
        {
            Db.FaxDatas.Remove(faxdatadelete);
            Db.SaveChanges();
        }
    }

    var deletedfax = Db.Faxes.FirstOrDefault(f => f.Id == id);
    if (deletedfax != null)
    {
        Db.Faxes.Remove(deletedfax);
        Db.SaveChanges();
    }

    return RedirectToAction("FaxForm", "Fax");
}
</code>```

Body:
i have this database

i want to delete fax in Fax table and records in FaxData that have the same id of fax in Fax table
i created viewmodel view to connect the 2 tables
     using System.Web.Mvc;

namespace FaxProject.ViewModel
{
public class SendFaxVm
{

    public List<SelectListItem> Employees { set; get; }

    public int[] SelectedEmployees { set; get; }
    public Fax fax { set; get; }
    public int FaxId { set; get; }
    public string CompanyName { set; get; }
    public int Courier_Num { set; get; }
    public Nullable<int> NumberOfPages { get; set; }

    public string CompanyAddress { get; set; }
    public string ReceivingDate { get; set; }
    public string Attachment { get; set; }
    public string Subject { get; set; }

}
}

this is the viewmodel

  public ActionResult Delete(int id,SendFaxVm vm,Fax fax)
    {
        foreach (var userId in vm.SelectedEmployees)
        {
            var faxdatadelete = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
            Db.FaxDatas.Remove(faxdatadelete);

            Db.SaveChanges();
        }

        var deletedfax = Db.Faxes.Single(f => f.Id == id);
        Db.Faxes.Remove(deletedfax);
        Db.SaveChanges();

        return RedirectToAction("FaxForm", "Fax");
    }

and this is the action in fax controller .....
and this is the exception that i got when i try to delete (An exception of type 'System.NullReferenceException' occurred in FaxProject.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.)

Body:
It should be:

public ActionResult Delete(int id, SendFaxVm vm, Fax fax)
{
    if (SendFaxVm == null || Fax == null)
    {
        return RedirectToAction("FaxForm", "Fax");
    }

    foreach (var userId in vm.SelectedEmployees)
    {
        var faxdatadelete = Db.FaxDatas.FirstOrDefault(f => f.FaxId == fax.Id);
        if (faxdatadelete != null)
        {
            Db.FaxDatas.Remove(faxdatadelete);
            Db.SaveChanges();
        }
    }

    var deletedfax = Db.Faxes.FirstOrDefault(f => f.Id == id);
    if (deletedfax != null)
    {
        Db.Faxes.Remove(deletedfax);
        Db.SaveChanges();
    }

    return RedirectToAction("FaxForm", "Fax");
}


问:
How to build a portable static C library for macOS
I'd like to build a portable static C library that can be linked into macOS binaries regardless of macOS version. The C library does not have any dependencies (i.e. no stdlib, no OS specific calls). The only dependency is the CPU which has to be x86_64.

When extracting the relevant compiler triplet, I get x86_64-apple-darwin16.7.0 for Sierra, and x86_64-apple-darwin17.2.0 for High Sierra. Also, when I build on High Sierra, there is a warning if I use the static library from Sierra (even when I specify --target x86_64-apple-darwin16.7.0 for clang).

How can I build a truly portable static library for macOS? If it is not possible, what is the way to go? One different version per major macOS release that is built from the same release? Some hackery by copying SDKs from outdated Xcode versions? Keep in mind, my library is completely portable and does not depend on macOS or the stdlib in any way.

Does the version part at the end of the compiler triplet matter?

答:
You can just create a static library directly by using macosx libtool

Here's what I just tested out on 3 different versions of Mac OS X (Sierra, High Sierra and Mavrick):

$ ls -al ⏎

```
total 64
drwxr-xr-x  8 masud  staff   272 Dec  5 11:12 .
drwxr-xr-x  7 masud  staff   238 Dec  5 10:35 ..
-rw-r--r--  1 masud  staff   386 Dec  5 11:11 Makefile
-rwxr-xr-x  1 masud  staff  8464 Dec  5 10:38 bar
-rw-r--r--  1 masud  staff    69 Dec  5 11:11 bar.c
-rw-r--r--  1 masud  staff    53 Dec  5 11:10 foo.c
-rw-r--r--  1 masud  staff    84 Dec  5 11:11 foo.h
-rw-r--r--  1 masud  staff    83 Dec  5 11:11 test.c
```

$ cat Makefile⏎

```<code>LIBTOOL=libtool
STATIC=-static
LIBFOO_A=libfoo.a
SRC=foo.c bar.c

OBJ=$(SRC:.c=.o)
LIBFOOCFLAGS=-mmacosx-version-min=10.1

TESTSRC=test.c
TESTCFLAGS=-mmacosx-version-min=10.7

$(LIBFOO_A): $(OBJ)
    $(LIBTOOL) $(STATIC) -o $@ $(OBJ)

%.o: %.c
    $(CC) $(LIBFOOCFLAGS) -c -o $@ $<

test: $(LIBFOO_A) test.c
    $(CC) $(TESTCFLAGS) -o $@ test.c -L. -lfoo

clean:
    $(RM) test $(LIBFOO_A) $(OBJ)
</code>```

$ cat foo.c⏎

```<code>int foo(void) {
    volatile int a = 0;
    return a;
}
</code>```

$ cat foo.h⏎

```<code>#ifndef __FOO_H
#define __FOO_H

extern int foo(void);

#endif
</code>```

$ cat bar.c⏎

```<code>#include "foo.h"

int bar(int k) {
    return k-1;
}
</code>```

In my tests, libfoo.a could be generated on any (of the three) platform(s) and copied to any (of the three) platform(s) and be used to generate test locally.

nm test on all three shows library statically linked into the binary.

Hope this helps.

on macosx libtool

P.S.: macosx libtool is NOT the same as the gnu libtool except in name. Completely different usage and functionality.  the macosx libtool is essentially AR + ranlib + some darwinisms.

Body:
You can just create a static library directly by using macosx libtool

Here's what I just tested out on 3 different versions of Mac OS X (Sierra, High Sierra and Mavrick):

$ ls -al ⏎

total 64
drwxr-xr-x  8 masud  staff   272 Dec  5 11:12 .
drwxr-xr-x  7 masud  staff   238 Dec  5 10:35 ..
-rw-r--r--  1 masud  staff   386 Dec  5 11:11 Makefile
-rwxr-xr-x  1 masud  staff  8464 Dec  5 10:38 bar
-rw-r--r--  1 masud  staff    69 Dec  5 11:11 bar.c
-rw-r--r--  1 masud  staff    53 Dec  5 11:10 foo.c
-rw-r--r--  1 masud  staff    84 Dec  5 11:11 foo.h
-rw-r--r--  1 masud  staff    83 Dec  5 11:11 test.c

$ cat Makefile⏎

LIBTOOL=libtool
STATIC=-static
LIBFOO_A=libfoo.a
SRC=foo.c bar.c

OBJ=$(SRC:.c=.o)
LIBFOOCFLAGS=-mmacosx-version-min=10.1

TESTSRC=test.c
TESTCFLAGS=-mmacosx-version-min=10.7

$(LIBFOO_A): $(OBJ)
    $(LIBTOOL) $(STATIC) -o $@ $(OBJ)

%.o: %.c
    $(CC) $(LIBFOOCFLAGS) -c -o $@ $<

test: $(LIBFOO_A) test.c
    $(CC) $(TESTCFLAGS) -o $@ test.c -L. -lfoo

clean:
    $(RM) test $(LIBFOO_A) $(OBJ)

$ cat foo.c⏎

int foo(void) {
    volatile int a = 0;
    return a;
}

$ cat foo.h⏎

#ifndef __FOO_H
#define __FOO_H

extern int foo(void);

#endif

$ cat bar.c⏎

#include "foo.h"

int bar(int k) {
    return k-1;
}

In my tests, libfoo.a could be generated on any (of the three) platform(s) and copied to any (of the three) platform(s) and be used to generate test locally.

nm test on all three shows library statically linked into the binary.

Hope this helps.

on macosx libtool

P.S.: macosx libtool is NOT the same as the gnu libtool except in name. Completely different usage and functionality.  the macosx libtool is essentially AR + ranlib + some darwinisms.


问:
Get Child Attribute using JQUERY
I am creating a link gallery.

HTML:

```<code><div class="link">
    <header>Test Header</header>
    <a href="http://www.google.com/">Click Here</a>
</div>
</code>```

I want to go to the A element's URL when clicking anywhere in the div.

Javascript with JQUERY 3.2.1:

```<code>$(function() {
    $("div.link").click(function() {
        $url = $this.children("a").attr("href");
        alert($url);
    });
});
</code>```

It doesn't alert the URL

I have also tried:

```<code>$(function() {
    $("div.link").click(function() {
        $url = $this.find("a:first-child").attr("href");
        alert($url);
    });
});
</code>```

It returns a collection instead of a single element so I tried the following:

```<code>$function() {
    $("div.link").click(function() {
        $url = $this.find("a");
        alert($url[0].attr("href"));
    });
});
</code>```

Neither approach is working.  I have confirmed the click selector is functioning by testing it with a simple alert("hello");

EDIT: I was using $this instead of $(this).

答:
If you check your browser's console, you'll have an error saying $this is not defined. It should be $(this), in order to turn this (the raw HTML element clicked on) into a jQuery object on which you can the run jQuery methods such as .find() and .attr().

Additionally, this version will actually cause the navigation action rather than just alerting the URL:

```<code>$("div.link").click(function() {
    $(this).find("a").click();
});
</code>```

Title: Get Child Attribute using JQUERY

Body:
I am creating a link gallery.

HTML:

    Test Header
    Click Here

I want to go to the A element's URL when clicking anywhere in the div.

Javascript with JQUERY 3.2.1:

$(function() {
    $("div.link").click(function() {
        $url = $this.children("a").attr("href");
        alert($url);
    });
});

It doesn't alert the URL

I have also tried:

$(function() {
    $("div.link").click(function() {
        $url = $this.find("a:first-child").attr("href");
        alert($url);
    });
});

It returns a collection instead of a single element so I tried the following:

$function() {
    $("div.link").click(function() {
        $url = $this.find("a");
        alert($url[0].attr("href"));
    });
});

Neither approach is working.  I have confirmed the click selector is functioning by testing it with a simple alert("hello");

EDIT: I was using $this instead of $(this).

Body:
If you check your browser's console, you'll have an error saying $this is not defined. It should be $(this), in order to turn this (the raw HTML element clicked on) into a jQuery object on which you can the run jQuery methods such as .find() and .attr().

Additionally, this version will actually cause the navigation action rather than just alerting the URL:

$("div.link").click(function() {
    $(this).find("a").click();
});


问:
How do I edit a WPF button at runtime

So I was using Expression Blend to design my button. I created a new button, edited the template of the button by removing everything within it. Then I added a grid into it and named it "grid". Inside the grid i added a textblock and called it "textBlock". Then i saved the template under Applications.

This is the content in the app.xaml file.

```<code><Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="grid" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="90">
                        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Margin="5,5,0,0" Height="25" Width="75" FontSize="17.333"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsDefaulted" Value="true"/>
                        <Trigger Property="IsMouseOver" Value="true"/>
                        <Trigger Property="IsPressed" Value="true"/>
                        <Trigger Property="IsEnabled" Value="false"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Basically what I am intending to do is to create a button at runtime, apply this style to the button, go to the template of the button, and change the text property of the textblock in the template of the button.

So for starters, instead of creating a button at runtime, i created one at compile time and named it "customButton". Then I tried to edit the text property of the button's templates' textblock but ran into exceptions.

```<code>TextBlock tb = this.customButton.Template.FindName("textBlock", customButton) as TextBlock;
tb.Text = "ASDDDQWEQWEQWE";
</code>```

Please advise thanks!

答:
Create a Button Template, like the one you have, and add controls for each of your items:

```<code><ControlTemplate TargetType="{x:Type Button}">
                <StackPanel>
                    <Label Content="{Binding CompanyName}" />
                    <Image Source="{Binding Image}" />
                    <Label Content="{Binding StockChange}" />
                </StackPanel>
</ControlTemplate>
</code>```

Or you can just add it to the button content:

```<code><Button>
    <Button.Content>
        <StackPanel>
            <Label Content="{Binding CompanyName}" />
            <Image Source="{Binding Image}" />
            <Label Content="{Binding StockChange}" />
        </StackPanel>
    </Button.Content>
</Button
</code>```

Create an class to hold the data from your API:

```<code>public class CompanyInfo
{
    public string CompanyName;
    public ImageSource Image;
    public string StockChange;
}
</code>```

Create a ObservableCollection<CompanyInfo> in code-behind or viewmodel to hold the CompanyInfo objects created from your API data:

```<code>public ObservableCollection<CompanyInfo> CompanyInfoList = new ObservableCollection<CompanyInfo>();
</code>```

Create an ItemsControl to create buttons from your list of data:

```<code><ItemsControl ItemsSource="{Binding Path=CompanyInfoList}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>

            //Button with Bindings Goes Here

        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>
</code>```

And Bobs your uncle. I advise researching some of these things to gain a better understanding of how it all works.

Title: How do I edit a WPF button at runtime

Body:
So I was using Expression Blend to design my button. I created a new button, edited the template of the button by removing everything within it. Then I added a grid into it and named it "grid". Inside the grid i added a textblock and called it "textBlock". Then i saved the template under Applications.

This is the content in the app.xaml file.

Basically what I am intending to do is to create a button at runtime, apply this style to the button, go to the template of the button, and change the text property of the textblock in the template of the button.

So for starters, instead of creating a button at runtime, i created one at compile time and named it "customButton". Then I tried to edit the text property of the button's templates' textblock but ran into exceptions.

TextBlock tb = this.customButton.Template.FindName("textBlock", customButton) as TextBlock;
tb.Text = "ASDDDQWEQWEQWE";

Please advise thanks!

Body:
Create a Button Template, like the one you have, and add controls for each of your items:

<ControlTemplate TargetType="{x:Type Button}">
                <StackPanel>
                    <Label Content="{Binding CompanyName}" />
                    <Image Source="{Binding Image}" />
                    <Label Content="{Binding StockChange}" />
                </StackPanel>
</ControlTemplate>

Or you can just add it to the button content:

<Button>
    <Button.Content>
        <StackPanel>
            <Label Content="{Binding CompanyName}" />
            <Image Source="{Binding Image}" />
            <Label Content="{Binding StockChange}" />
        </StackPanel>
    </Button.Content>
</Button

Create an class to hold the data from your API:

public class CompanyInfo
{
    public string CompanyName;
    public ImageSource Image;
    public string StockChange;
}

Create a ObservableCollection<CompanyInfo> in code-behind or viewmodel to hold the CompanyInfo objects created from your API data:

public ObservableCollection<CompanyInfo> CompanyInfoList = new ObservableCollection<CompanyInfo>();

Create an ItemsControl to create buttons from your list of data:

<ItemsControl ItemsSource="{Binding Path=CompanyInfoList}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>

            //Button with Bindings Goes Here

        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

And Bobs your uncle. I advise researching some of these things to gain a better understanding of how it all works.


问:
Can not cast context into activity Xamarin
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

```<code> public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }
</code>```

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

```<code>ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
</code>```

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

答:
I have just found the solution.

I had to take the context with

var context = Xamarin.Forms.Forms.Context;

instead of

var context = Android.App.Application.Context;

After that, cast works nicely

Thanks everybody

Body:
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

 public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you


问:
I need to decrypt a file efficiently

I am trying to decrypt an encrypted file with unknown key - the only thing I know about it is that the key is an integer x, 0 <= x < 1010 (i.e. a maximum of 10 decimal digits).

```<code>public static String enc(String msg, long key) {
    String ans = "";
    Random rand = new Random(key);
    for (int i = 0; i < msg.length(); i = i + 1) {
        char c = msg.charAt(i);
        int s = c;
        int rd = rand.nextInt() % (256 * 256);
        int s2 = s ^ rd;
        char c2 = (char) (s2);
        ans += c2;
    }
    return ans;
}

private static String tryToDecode(String string) {
    String returnedString = "";
    long key;
    String msg = reader(string);
    for (long i = 0; i <= 999999999; i++) {
        System.out.println("decoding message with key + " + i);

        key = i;
        System.out.println("decoding with key: " + i + "\n" + enc(msg, key));

    }
    return returnedString;
}
</code>```

I expect to find the plain text

The program works very slowly, is there any way to make it more efficient?

答:
You can use Parallel Array Operations added in JAVA 8 if you are using Java 8 to achive this.

The best fit for you would be to use Spliterator

```<code>    public void spliterate() {
    System.out.println("\nSpliterate:");
    int[] src = getData();
    Spliterator<Integer> spliterator = Arrays.spliterator(src);
    spliterator.forEachRemaining( n -> action(n) );
}

public void action(int value) {
    System.out.println("value:"+value);
    // Perform some real work on this data here...
}
</code>```

I am still not clear about your situation. Here some great tutorials and articles to figure out which parallel array operations of java 8 is going to help you ?

http://www.drdobbs.com/jvm/parallel-array-operations-in-java-8/240166287

https://blog.rapid7.com/2015/10/28/java-8-introduction-to-parallelism-and-spliterator/

Title: I need to decrypt a file efficiently

Body:
I am trying to decrypt an encrypted file with unknown key - the only thing I know about it is that the key is an integer x, 0 <= x < 1010 (i.e. a maximum of 10 decimal digits).

public static String enc(String msg, long key) {
    String ans = "";
    Random rand = new Random(key);
    for (int i = 0; i < msg.length(); i = i + 1) {
        char c = msg.charAt(i);
        int s = c;
        int rd = rand.nextInt() % (256 * 256);
        int s2 = s ^ rd;
        char c2 = (char) (s2);
        ans += c2;
    }
    return ans;
}

private static String tryToDecode(String string) {
    String returnedString = "";
    long key;
    String msg = reader(string);
    for (long i = 0; i <= 999999999; i++) {
        System.out.println("decoding message with key + " + i);

        key = i;
        System.out.println("decoding with key: " + i + "\n" + enc(msg, key));

    }
    return returnedString;
}

I expect to find the plain text

The program works very slowly, is there any way to make it more efficient?

Body:
You can use Parallel Array Operations added in JAVA 8 if you are using Java 8 to achive this.

The best fit for you would be to use Spliterator

    public void spliterate() {
    System.out.println("\nSpliterate:");
    int[] src = getData();
    Spliterator<Integer> spliterator = Arrays.spliterator(src);
    spliterator.forEachRemaining( n -> action(n) );
}

public void action(int value) {
    System.out.println("value:"+value);
    // Perform some real work on this data here...
}

I am still not clear about your situation. Here some great tutorials and articles to figure out which parallel array operations of java 8 is going to help you ?

http://www.drdobbs.com/jvm/parallel-array-operations-in-java-8/240166287

https://blog.rapid7.com/2015/10/28/java-8-introduction-to-parallelism-and-spliterator/


问:
Why does my XPath not select based on text()?
I have a page in firefox (no frame) which contains the following part of html code:

```<code>...
<div class="col-sm-6 align-right">
    <a href="/efelg/download_zip" class="alert-link">
        Download all results in .zip format
     </a>
</div>
...
</code>```

which I want to select with a selenium XPATH expression. In order to test my XPATH expression, I installed an add-on for firefox called 'TryXpath' in order to check my expression. However, the expression seems to be incorrect, as no element is selected. Here is the expression:

```<code>//a[text()= "Download all results in .zip format"]
</code>```

but what is wrong with that expression? I found it in different SO answers - but for me this does not seem to work. Why do I get 0 hits? Why is the expression wrong find the html element I posted above (no frame, element is visible and clickable...)

答:
The reason your XPath isn't selecting the shown a element is due to the leading and trail white space surrounding your targeted text.  While you could use contains() as the currently upvoted and selected answer does, be aware that it could also match when the targeted string is a substring of what's found in the HTML in an a element -- this may or may not be desirable.

Consider instead using normalized-space() and testing via equality:

```<code>//a[normalize-space()='Download all results in .zip format']
</code>```

This will check that the (space-normalized) string value of a equals the given text.

See also

Testing text() nodes vs string values in XPath

Body:
I have a page in firefox (no frame) which contains the following part of html code:

...

        Download all results in .zip format

...

which I want to select with a selenium XPATH expression. In order to test my XPATH expression, I installed an add-on for firefox called 'TryXpath' in order to check my expression. However, the expression seems to be incorrect, as no element is selected. Here is the expression:

//a[text()= "Download all results in .zip format"]

but what is wrong with that expression? I found it in different SO answers - but for me this does not seem to work. Why do I get 0 hits? Why is the expression wrong find the html element I posted above (no frame, element is visible and clickable...)

Body:
The reason your XPath isn't selecting the shown a element is due to the leading and trail white space surrounding your targeted text.  While you could use contains() as the currently upvoted and selected answer does, be aware that it could also match when the targeted string is a substring of what's found in the HTML in an a element -- this may or may not be desirable.

Consider instead using normalized-space() and testing via equality:

//a[normalize-space()='Download all results in .zip format']

This will check that the (space-normalized) string value of a equals the given text.

See also

Testing text() nodes vs string values in XPath


问:
jquery ajax post and get in single page
I am trying to post some data and get those data. On page load i am showing the data. it works. but once i post the data, it is posted in db but not showing in the page. after loading the page only it shows.

i need to show the data once it is posted in the same page without page reload.

here is my code:

```<code><script>
$(document).ready(function() {
    $.ajax({
              type: "GET",
              url: "employees.php",
              success: function(data) {
                    $("#result").html(data);
              }
    });

    $("#create").click(function(e) {
        e.preventDefault();
        var name = $("#name").val();
        var age = $("#age").val();
        var gender = $("#gender").val();
        var salary = $("#salary").val();
        $.ajax({
            url: "create_employees.php",
            type: "POST",
            data:
                {
                    name:name,
                    age:age,
                    gender:gender,
                    salary:salary
                }
        }).success(function (response){
            console.log(response);

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

```<code><form>
    Name  : <input type="text" name="name" id="name"><br />
    Age   : <input type="age" name="age" id="age"><br />
    Gender: <input type="radio" name="gender" id="gender" value="male" checked>Male
            <input type="radio" name="gender" id="gender" value="female">Female<br />``
    Salary: <input type="text" name="salary" id="salary"><br />
    <button id="create">Create</button>
</form>
<div id="result"></div>
</code>```

答:
Because you're not showing the data anywhere on the page.  Take a look at your AJAX success handler:

```<code>.success(function (response){
    console.log(response);
})
</code>```

It does exactly one thing... log the response to the console.  Nothing else.

What do you want it to do?  What is response and how will you update the page with it?  Well, that's up to you really.

Is response HTML data?  You can append it as the contents of an element:

```<code>$('#someElement').append(response);
</code>```

Is response JSON data?  You can use values from it to set some HTML values:

```<code>$('#anElement').text(response.someValue);
</code>```

And so on.  The point is, if you want to display the data on the page then you need to write the logic to do exactly that.  The system has no way of automatically doing it for you.

Title: jquery ajax post and get in single page

Body:
Because you're not showing the data anywhere on the page.  Take a look at your AJAX success handler:

.success(function (response){
    console.log(response);
})

It does exactly one thing... log the response to the console.  Nothing else.

What do you want it to do?  What is response and how will you update the page with it?  Well, that's up to you really.

Is response HTML data?  You can append it as the contents of an element:

$('#someElement').append(response);

Is response JSON data?  You can use values from it to set some HTML values:

$('#anElement').text(response.someValue);

And so on.  The point is, if you want to display the data on the page then you need to write the logic to do exactly that.  The system has no way of automatically doing it for you.