text:
Q: cakephp 2.x pivot table I have a table as follows
Tablename :  tb_daily_call_reports
+------------+-----------+
| username   |  date     |
+------------+-----------+
| Peter      |  5/5/2014 |
+------------+-----------+
| Steve      |  5/5/2014 |
+------------+-----------+
| Peter      |  5/5/2014 |
+------------+-----------+
| Peter      |  5/5/2014 |
+------------+-----------+
| Peter      |  5/6/2014 |
+------------+-----------+
| Steve      |  5/6/2014 |
+------------+-----------+
| Peter      |  5/6/2014 |
+------------+-----------+
| James      |  5/7/2014 |
+------------+-----------+
| Steve      |  5/7/2014 |
+------------+-----------+
| James      |  5/8/2014 |
+------------+-----------+
| Peter      |  5/8/2014 |
+------------+-----------+
| Steve      |  5/8/2014 |
+------------+-----------+
| James      |  5/8/2014 |
+------------+-----------+
| James      |  5/8/2014 |
+------------+-----------+

What I would like to do is count the users in particular day and display the output as follows
+-----------+--------+---------+---------+
|           | Peter  | Steve   |  James  |
+-----------+--------+---------+---------+
| 5/5/2014  |   3    |   1     |    0    |
+-----------+--------+---------+---------+
| 5/6/2014  |   2    |   1     |    0    |
+-----------+--------+---------+---------+
| 5/7/2014  |   0    |   1     |    1    |
+-----------+--------+---------+---------+
| 5/8/2014  |   1    |   1     |    3    |
+-----------+--------+---------+---------+

Using SQL query I get the required result (for clarity username = user_detail_id)
SELECT date,
count(IF (user_detail_id = 'Peter', date, NULL)) AS 'Peter',
count(IF (user_detail_id = 'Steve', date, NULL)) AS 'Steve',
count(IF (user_detail_id = 'James', date, NULL)) AS 'James',
FROM tb_daily_call_reports
GROUP BY  date;

I need to implement this using CakePHP 2.x.
Thank you!

A: I suppose you are in your DailyCallReportsController
// First I search for all the distinct usernames that I have in my table

$names = $this->DailyCallReport->find(
    'all',
    array(
        'fields' => array('DISTINCT DailyCallReport.user_detail_id'),
        'recursive' => -1
    )
);

// Then for every username I create a virtual field for my Model

$fields = array('date');

foreach($names as $record)
{
    $user_detail_id  = $record['DailyCallReport']['user_detail_id '];
    $this->DailyCallReport->virtualFields['user_'.$user_detail_id] = "COUNT(IF (user_detail_id = $user_detail_id, date, NULL))";
    $fields[] = 'user_'.$user_detail_id;
}

// Finally I do the query

$pivot = $this->DailyCallReport->find(
    'all',
    array(
        'fields' => $fields,
        'recursive' => -1,
        'group' => array('date')
    )
);


text:
Q: How to build a script which can Get Content periodically from internet and save it to every new csv file using PowerShell? I am a beginner to PowerShell and thinking of developing a scraping tool for a dynamic webpage using PowerShell.
IDEA:
I tried 'Invoke-WebRequest' for scraping a free scraping site 'https://quotes.toscrape.com/'
After Scraping, ('For Loop, (Get-content | Format-Table) and Export-CSV' commands will be used) which will create a new .csv file in new folder and save the content into that file.
Difficulty 1: Tried to scrape 'https://quotes.toscrape.com/' using 'Invoke-WebRequest', but I did not find any strings of Quotes. To me it looks like it just returned the Formatting code
Output :
 StatusCode        : 200
StatusDescription : OK
Content           : <!DOCTYPE html>

                        <meta charset="UTF-8">
                        <title>Quotes to Scrape</title>
                        <link rel="stylesheet" href="/static/bootstrap.min.css">
                        <link rel="stylesheet" href="/static/m...
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    Vary: Accept-Encoding
                    Strict-Transport-Security: max-age=15724800; includeSubDomains
                    Content-Length: 11053
                    Content-Type: text/html; charset=utf-8
                    Date: Sat...
Forms             : {}
Headers           : {[Connection, keep-alive], [Vary, Accept-Encoding], [Strict-Transport-Security, max-age=15724800; includeSubDomains], [Content-Length,
                    11053]...}
Images            : {}
InputFields       : {}
Links             : {@{innerHTML=Quotes to Scrape; innerText=Quotes to Scrape; outerHTML=Quotes to Scrape;
                    outerText=Quotes to Scrape; tagName=A; style=TEXT-DECORATION: none; href=/}, @{innerHTML=Login; innerText=Login; outerHTML=Login; outerText=Login; tagName=A; href=/login}, @{innerHTML=(about); innerText=(about); outerHTML=(about); outerText=(about); tagName=A; href=/author/Albert-Einstein}, @{innerHTML=change;
                    innerText=change; outerHTML=change; outerText=change; tagName=A; class=tag;
                    href=/tag/change/page/1/}...}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 11053

Difficulty 2:
Full code Working:
#1. Creating an array of Folders using For Loop
for ($i = 1; $i -lt 6; $i++){
    $folders = New-Item -Path "C:\Users\Henry\PowerShellscripts\Project8\May 1$i" -ItemType Directory
    #2. Using For Each Loop to create QuotestoStore.csv inside them
    foreach($sample in $folders) {
        Add-Content -Path "$sample\QuotestoStore.csv" -Value Invoke-WebRequest 'https://quotes.toscrape.com/'
        Write-Host "$sample saved."
    }
}

Error Messages:
Add-Content : A positional parameter cannot be found that accepts argument
'https://quotes.toscrape.com/'.
At line:6 char:9
+         Add-Content -Path "$sample\QuotestoStore.csv" -Value Invoke-W ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-Content], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.AddConten
   tCommand

**Doubt 1: As we see in (Difficulty 1) the Web Formatting code is returned instead of the values or the Text in the webpage, So Which Syntax should I use to get values of quotes from webpage 'https://quotes.toscrape.com/'  ??
Doubt 2: (Add-Content -Path "$sample\QuotestoStore.csv" -Value Invoke-WebRequest 'https://quotes.toscrape.com/')
Can I include (Invoke-WebRequest 'https://quotes.toscrape.com/) command in -Value Parameter??... If not how to create a function and insert that here, to export the content to csv.??
Doubt 3: Can we add a time variable ($stop = '12:52:30') and create the following Code: ??**
    [datetime] $stop = '12:52:30'

Do{
    for ($i = 1; $i -lt 6; $i++){
        $folders = New-Item -Path "C:\Users\Henry\PowerShellscripts\Project8\May 1$i" -ItemType Directory
        #2. Using For Each Loop to create QuotestoStore.csv inside them
        foreach($sample in $folders) {
            Add-Content -Path "$sample\QuotestoStore.csv" -Value Invoke-WebRequest 'https://quotes.toscrape.com/'
            Write-Host "$sample saved."
        }
    }
}Until((Get-Date) -ge $stop)

Please Guide me !!
Thank you!!

A: It of course all depends on what you would like to capture from the quotes on that page, but I could imaging doing something like this (daily ?)
# create the target directory including the date like 'May 22'
$destination = 'C:\Users\Henry\PowerShellscripts\Project8\{0:MMM dd}'-f (Get-Date)
$null        = New-Item -Path $destination -ItemType Directory -Force
$outFile     = Join-Path -Path $Destination -ChildPath 'QuotestoStore.csv'

$url = 'https://quotes.toscrape.com'
$req =  Invoke-WebRequest -Uri $url -Method Get

if ($req.StatusCode -ne 200) {
    Write-Warning "Error: Website returned statuscode $($req.StatusCode)"
}
else {
    $req.ParsedHtml.getElementsByClassName('quote') | ForEach-Object {
        $relativeLink = $_.getElementsByTagName('span')[1].getElementsByTagName('a')[0].href -replace 'about:/'
        [PsCustomObject]@{
            Quote  = $_.getElementsByClassName('text')[0].innerText -replace '[""]'                       # quotes; remove the curly quotes
            Author = $_.getElementsByClassName('author')[0].innerText                                     # name of the author
            About  = '{0}/{1}' -f $url, $relativeLink                                                     # link to author page
            Tags   = $_.getElementsByClassName('tags')[0].getElementsByClassName('keywords')[0].content   # tag categories
            #or: Tags   = ($quotes[0].getElementsByClassName('tags')[0].getElementsByTagName('a') | ForEach-Object { $_.innerText }) -join ','
        }
    } | Export-Csv -Path $outFile -UseCulture -NoTypeInformation
}

Result would be a csv file:
"Quote";"Author";"About";"Tags"
"The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.";"Albert Einstein";"https://quotes.toscrape.com/author/Albert-Einstein";"change,deep-thoughts,thinking,world"
"It is our choices, Harry, that show what we truly are, far more than our abilities.";"J.K. Rowling";"https://quotes.toscrape.com/author/J-K-Rowling";"abilities,choices"
"There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.";"Albert Einstein";"https://quotes.toscrape.com/author/Albert-Einstein";"inspirational,life,live,miracle,miracles"
"The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.";"Jane Austen";"https://quotes.toscrape.com/author/Jane-Austen";"aliteracy,books,classic,humor"
"Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.";"Marilyn Monroe";"https://quotes.toscrape.com/author/Marilyn-Monroe";"be-yourself,inspirational"
"Try not to become a man of success. Rather become a man of value.";"Albert Einstein";"https://quotes.toscrape.com/author/Albert-Einstein";"adulthood,success,value"
"It is better to be hated for what you are than to be loved for what you are not.";"Andr? Gide";"https://quotes.toscrape.com/author/Andre-Gide";"life,love"
"I have not failed. I've just found 10,000 ways that won't work.";"Thomas A. Edison";"https://quotes.toscrape.com/author/Thomas-A-Edison";"edison,failure,inspirational,paraphrased"
"A woman is like a tea bag; you never know how strong it is until it's in hot water.";"Eleanor Roosevelt";"https://quotes.toscrape.com/author/Eleanor-Roosevelt";"misattributed-eleanor-roosevelt"
"A day without sunshine is like, you know, night.";"Steve Martin";"https://quotes.toscrape.com/author/Steve-Martin";"humor,obvious,simile"

Some explanation as per your comment:

*

*Why the -Force switch on the New-Item cmdlet ?
Without -Force, the cmdlet creates a new folder and returns a DirectoryInfo object of that new folder.
However, if a folder with that name already existed, you wil receive an exception: New-Item : An item with the specified name <path\to\the\folder> already exists..
For good measure then you should first check if the folder exists or not with Test-Path, OR add the -Force switch, because then New-Item either creates the folder, or returns the DirectoryInfo object of the already existing folder without exceptions being thrown.
Since I'm not interested in that returned DirectoryInfo object, I'm throwing that away by using $null = New-Item ..

*Why StatusCode -ne 200 ?
A webrequest always returns a StatusCode telling you if the request was successful or not. There are a lot of them, see here. StatusCode 200 means 'OK', so then you can proceed with the rest of the code. If not, the answer displays a warning.

*Why the -UseCulture switch on Export-Csv ?
Many users tend to double-click a CSV file and expect their installed version of Excel to open it nicely with all fields in different columns.
However, there are differences in the machine's locales (cultures) in the world. Without -UseCulture, Export-Csv will use the comma (,) as delimiter, but if you are in a country like me (The Netherlands), the machines default list separator is the semi-colon (;) as you can see in the example output. So in my case, if I don't specify the semi-colon as being the delimiter to use, Excel will make a mess of the file when double-clicking it. You can do that either by using parameter -Delimiter ';' if you know what Excel will understand, OR let the -UseCulture switch figure out what the current locale's ListSeparator is and use that.
(It does that by using the character returned from [cultureinfo]::CurrentCulture.TextInfo.ListSeparator)

A: Are you trying to get result as shown below then,

User below code
$url = "https://quotes.toscrape.com/"

$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession  -UseBasicParsing

$webrequest | Export-Csv "C:\Test.csv"

And if you want to schedule this process then  you can use windows scheduler in powershell(Register-ScheduledTask).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shorter macron over letter i I am trying to typeset song lyrics in Hindi, where I want a bar over an "a" and an "i". I found \={} and \macron{} which both produce a nice bar over an "a", but the bar over an "i" (without the dot) is too long for my taste, because the bars appear connected when an "i" follows an "a" as in S\={a}\={\i} S\macron{a}\macron{\i}:

Is there a way I can make the bar over an "i" shorter?

A: You can use \vbox{\halign{}} construction for this special case:
\def\macroni{\leavevmode\vbox{\offinterlineskip\ialign{\hfil##\hfil\cr
   \vrule height.03em width.25em\cr\noalign{\kern.13em}\i\cr}}}
\let\macronori=\=
\def\=#1{\ifx\i#1\macroni\else\macronori{#1}\fi}

S\=a\={\i}

A: Rather than shorten the length of the macron bar, I'd consider inserting a very thin "kern" (non-discardable whitespace) ahead of the \={\i} part. In the example below, I've chosen a kern of 0.5pt; feel free to adjust the width of the kern to suit you needs. Note that the kern is needed only if \={\i} is preceded by another macron-endowed character.

\documentclass{article}
\newcommand\imacron{\kern0.5pt\={\i}}
\begin{document}
S\={a}\imacron\ vs.\ S\={a}\={\i}
\end{document}


text:
Q: Как корректно отсортировать массив со строками из чисел и букв Есть массив со строками из числовых значений и обычных строк, например:
[
  "1",
  "11",
  "111",
  "Product",
  "2",
  "22",
  "App"
]

Как отсортировать этот массив там, чтобы строки, которые можно привести к числам, сортировались как числа ,а не "по алфавиту", а за ними шли отсортированные "по алфавиту" строки?

A: Одним проходом можно разделить массив на числа и строки, отдельно их отсортировать, потом склеить. Такой подход показался наиболее простым, хотя подозреваю, что можно придумать какую-то хитрую конструкцию с одним sort или сортировать циклом вручную.

let arr = [
  "1",
  "11",
  "111",
  "Product",
  "1Product",
  "0Product",
  "2",
  "22",
  "App"
];

let numbers = [];
let strings = [];

arr.forEach(e => (isNaN(e) ? strings : numbers).push(e) );

numbers = numbers.sort((a,b) => Number(a) - Number(b));
strings = strings.sort();

arr = numbers.concat( strings );

console.log( arr );

A:      [
       "1",
       "Product",
       "11",
       "2",
       "App",
       "22",
       "111",
     ]. sort (( a , b , c = a - b )=> c == c ? c : a > b ? 1 : -1 );


text:
Q: DNS Setup for mail to two different servers I have a stage.domainX.com and domainX.com. How do I adjust the MX records accordingly to where all mail sent to stage.domainX.com goes to one server (IP1 66.xx.xx.xx) and all other mail sent to domainX.com goes to another server (IP2 67.xx.xx.xx)?
info@stage.domainX.com -> IP1
info@domainX.com -> IP2

A: Make sure you have DNS records for the mail servers, for example:
mail1.domainX.com.         IN    A     66.xx.xx.xx
mail2.domainX.com.         IN    A     67.xx.xx.xx

Then create an MX record for each domain:
stage.domainX.com.         IN    MX    10 mail1.domainX.com.
domainX.com.               IN    MX    10 mail2.domainX.com.

A: The correct way of doing it would be the delegating stage.domainX.com
Refer to the documentation to delegate stage.domainX.com
http://www.zytrax.com/books/dns/ch9/delegate.html


text:
Q: Algorithm for cutting rod to maximize profit I am trying to solve the standard rod-cutting problem through dynamic programming. As found here and here, the recurrence relations seems to be:
prices = [1..n]
array[1..n]

array[1] = prices[1]

for i in (2..n)
{
    array[i] = INT_MIN
    for j in (1..i-1)
    {
        array[i] = max(array[i],prices[j]+array[i-j])
    }
}

And array[n] returns the value for n, which is our answer. My question lies in the line
array[i] = max(array[i],prices[j]+array[i-j])

Shouldn't it be
array[i] = max(array[i],array[j]+array[i-j])

Imagine we are trying to find max value for length 8. Now, for 4 we find that the value we obtain by cutting one single unit of length 4 is less than say obtained by cutting lengths of 3 and 1, i.e for n = 4, prices[4] is not optimal. But since we are building the result array bottom up, array[4] is optimal. So won't array[4]+array[4] be the max value for n = 8, compared to prices[4]+array[4]? My resulting solution looks something like this:
prices = [1..n]
array[1..n]

for i in (1..n)
    array[i] = prices[i] //prices[i] is the minimum value we can obtain by cutting it fully

for i in (2..n)
{
    for j in (1..i-1)
    {
        array[i] = max(array[i],array[j]+array[i-j]) // find out all possible (j,i-j) pairs, and compare with array[i]
    }
}

If this is not correct, please tell me where am I erring logically.

A: array[i] = max(array[i],prices[j]+array[i-j]) looks right to me.
In that algorithm, j represents the length of rod of your initial cut. We start off with a rod of length i and cut off j. Then, we need to know how much we can get for a rod of i - j because you just cut off j length and you're left with i - j. But we know this value is at least as high as price[i-j] because we have the option of selling the rod as a whole or by cutting it to increase its value.
Example:
We have a rod of length 4. Assuming array[] already contains optimal values for 1,2,3, then we:

cut off a piece of length 1, then check how much we can get for a rod of length 3
cut off a piece of length 2, then check how much we can get
  for a rod of length 2
cut off a piece of length 3, then check how much we can get for a rod of length 1

And pick the maximum.
If we used array[i] = max(array[i],array[j]+array[i-j])
array[k] contains the maximum value for a rod of length k if we cut it into pieces. So these values would be unexpectedly high compared to if we used price[k].
Also the current step in the recursion only cares about making one cut, and checking the leftover's max value, not both sides max values (that will be taken care of when you find that the value of a large cut may not be ideal)


text:
Q: Handling UIButtons iOS I've been watching the iOS lectures(by Paul Hegerty) from Winter 2013 and I can't seem to wrap my head around why this second line of code is necessary in the Matchisimo program. If I comment it out, the program crashes, but if I leave it in, it works fine.
[cardButton setTitle:card.contents forState:UIControlStateSelected];

[cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

Fails at this line:
@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([CardGameAppDelegate class]));
}

Error given if the second line is commented out:
'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 47 beyond bounds [0 .. 46]'

Card contents:
@property (strong, nonatomic) NSString *contents;

Update UI:
- (void)updateUI
{
    for (UIButton *cardButton in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];

        [cardButton setTitle:card.contents forState:UIControlStateSelected];

        [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

        cardButton.selected = card.isFaceUp;
        cardButton.enabled = !card.isUnPlayable;
    }
}

A: Commenting this line [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled]; does not cause a crash for any reason.
This is the line [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]]; causing a crash related to an index out of bounds. Basically you have more cardButtons than self.game has cards.
You can wrap it with this to prevent a crash but should look for the deeper underlying problem for why an extra button is created.
int buttonIndex = [self.cardButtons indexOfObject:cardButton];
if (self.game.count > buttonIndex) {
    Card *card = [self.game cardAtIndex:buttonIndex];

    [cardButton setTitle:card.contents forState:UIControlStateSelected];

    [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

    cardButton.selected = card.isFaceUp;
    cardButton.enabled = !card.isUnPlayable;
}


text:
Q: Fluid full width grid in container What is a simple, preferrably css-only, solution to achieve the following:
Have a grid of divs with fluid widths that always matches the with of the container, without having some space on one side due to the margin of the divs.
All boxes should be in one container.
Here is what i have: https://jsfiddle.net/5g0uwxtx/

#container{
width:100%;}
.box{
width: 32%;
height: 0;
padding-bottom: 32%;
float:left;
margin:0 1% 1% 0;
background-color:#CCC;}

I want each row of boxes to stretch exactly to the right side, without left over space.
Thanks!

A: There are a number of ways, but one of the more commonly seen is using a row based layout with first-child or last-child to control the margins, e.g.
http://codepen.io/anon/pen/MajyaG

#container{

}

.box{
  width: 32.5%;
  height: 0;
  padding-bottom: 32%;
  float:left;
  margin:0 1% 1% 0;
  background-color:#CCC;
}

.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

.row .box:last-child{
  margin-right: 0;
}


text:
Q: Sum over real photon polarizations. The minus sign Ok for real photons there is the formula when summing over the polarizations:
$$ \sum_{\lambda=\pm}\epsilon^{*\mu}_\lambda\epsilon^\nu_\lambda = -\eta^{\mu\nu}$$
But if I have a matrix element of the form:
$$\epsilon^{*\mu}M_\mu\qquad \epsilon^\mu\bar{M}_\mu$$
So when I take the absoulte squared of that I have:
$$|M|^2 = \epsilon^{*\mu}M_\mu \epsilon^\nu\bar{M}_\nu= -M_\mu\eta^{\mu\nu}M_\nu = -M \bar{M}$$
But know the absolute squared is negative. So I know I have a heavy mistake somewhere here. Can someone help me understand?
Thanks a lot.

A: $$-M_\mu\eta^{\mu\nu}M_\nu=-M_0^2+M_1^2+M_2^2+M_3^2$$
Since due to Ward identity $M_0=M_3$ (choosing $x^3$ as the direction of motion), the above result is positive.


text:
Q: C++ Timer implementation I'm trying to implement a "timer" function in C++ for the program to do something after some seconds.
However, I've got unexpected results.
short e, sum;
clock_t start;
double duration=0;

for (e=0; e<4; e++) {
    start = clock();
    while (duration < 1) {

        duration = (clock() - start)/(double)CLOCKS_PER_SEC;
    }
    cout << duration;
    duration = 0;
    sum += e;
    /* Calculate EPOCH error */
    cout << e;
}
cout << "\n" << e<< "\n";

The results I expect are:

*

*console output every second, followed by e (0,1,2,3)

*at the end of the execution I expect sum to be 0+1+2+3 = 6,

Results obtained:

*

*console output followed by e, all together when execution finishes

*sum = 6

What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,

A: Your problem is that the output stream isn't flushed during your loop. Actually writing pieces of text to the console is somewhat expensive. Therefore the input is buffered and only written to the console when a flush occurs. Flushing the stream can be accomplished by streaming std::flush:
    cout << e<<std::flush;

std::endl will also flush the stream in addition to adding a newline (writing \n might also do it, but that's not guaranteed).
As a sidenote: you might want to consider adding some sort of seperators between your numbers to make the output readable.


text:
Q: Can the quantum harmonic oscillator be solved by power series methods without going for asymptotic analysis? Although this is a question pertaining to Physics, since this is related to the mathematical treatment of a differential equation, I believe it is well suited for this community.
While deriving the wave function for harmonic oscillator potential using Schrodinger's equation, we obtain the following equation through rearrangement of constants and nondimensionalization of the variables.
$$\frac{d^2\psi}{du^2}+(\epsilon-u^2)\psi=0 \tag1$$
And then we use the technique of asymptotic analysis.
This is achieved by checking the behaviour of $\psi$ at large $u$ and guessing the form of the solution as $$\psi \approx \exp(-u^2) g(u)$$
And then we obtain Hermite's differential equation for $g(u)$ which can solved by power series solution.

My Question: Why can't we avoid Asymptotic Analysis and directly go for a Series Solution?
  Why can't we just directly take $$\psi(u)=\sum_\limits{n=0}^{\infty} a_n u^n \tag2$$

I have checked everywhere in the internet and also in all standard books on quantum mechanics. What I have observed is that they directly go for the asymptotic analysis without stating any reason. They simply say that the asymptotic analysis will help in simplifying the calculations. However they do not mention anything about a direct solution by power series method. They do not make any comments on the possible of a direct series solution; neither why we may be able to go for such solutions nor why we can't go for such a method and have to adopt something called asymptotic analysis.
I tried solving Schrödinger's Equation using such a power series as in $(2)$.
What I got was:
 $$2a_2+\epsilon a_0+(6a_3+\epsilon a_1)u+\sum_\limits{n=0}^{\infty} \left[(n+4)(n+3)a_{n+4}+\epsilon a_{n+2}-a_n\right]u^{n+2}=0$$
These gives 2 constants and $1$ recursion.
$$(n+4)(n+3)a_{n+4}+\epsilon a_{n+2}-a_n=0$$
I know that it is difficult to obtain any nice desired result from this recursive relation.
But is this correct? Is this process feasible here? I checked for singularities and found none.
In case this is correct, is it so that both asymptotic analysis and my procedure are allowed but the asymptotic analysis method is most favoured since in that case we get closed form results which can be used to derive other useful results?
Or is this series solution not feasible due to some reason more general?

A: Your solution $\psi$ as wave function should be bounded, even go to zero at infinity. It should at least be in $L^2(\Bbb R)$, for the equation to make sense you will need a Sobolov space $H^1$ or better. That is not given for polynomial solutions, and also most power series solutions will diverge at infinity, trigonometric and similar functions are the exceptions to that rule.
Thus it makes sense to get the solution as the product of a factor that captures this asymptotic behavior and a slower growing factor that can be computed via power series, or in this case can be chosen as polynomial so that the convergence considerations occur in the linear combinations of the basis solutions.

You will find that in setting $\psi(u)=\exp(s(u))g(u)$ you get
\begin{align}
\psi''&=(e^s)''g+2(e^s)'g'+e^sg''\\
&=e^s\Bigl[(s'^2+s'')g+2s'g'+g\Bigr]\\
&=e^s(u^2-E)g
\end{align}
Assuming $s'$ is growing to infinity, that is, $s$ is superlinear, the terms with $s'^2$ and $u^2$ are the largest on both sides. Setting them equal (this is a design decision, there is one functional relation with $s$ and $g$ free) to cancel each other in the equation results in $s'=\pm u$, $s=\pm u^2/2$ where the plus sign gets excluded because of unbounded growth. $\psi(u)=\exp(-u^2/2)g(u)$ has the remaining equation
$$
0=(E-1)g-2ug'(u)+g''(u)
$$
or in power series coefficients
$$
0=(E-1)a_n-2na_n+(n+1)(n+1)a_{n+1}\implies a_{n+2}=\frac{2n+1-E}{(n+2)(n+1)}
$$
To prevent a solution growing like $e^{u^2/2}$ you want either a polynomial solution or that $\frac{a_{n+2}}{a_n}=o(\frac1n)$. The latter is impossible. For a polynomial solution you need $E=2N-1$ to get $a_n=0$ for $n>N$.


text:
Q: Convert aggregate function from Excel to Google Sheets I'm working on a excel that pulls out consecutive capital letters from a cell. It's basically trying to find states abbreviations from any type strings and I got a list of state abbreviations. This is my formula in excel
=MID(A1,AGGREGATE(15,6,FIND(States," "&A1&" "),1),2)

States:
={" AL "," AK "," AZ "," AR "," CA "," CO "," CT "," DE "," FL "," GA "," HI "," ID "," IL "," IN "," IA "," KS "," KY "," LA "," ME "," MD "," MA "," MI "," MN "," MS "," MO "," MT "," NE "," NV "," NH "," NJ "," NM "," NY "," NC "," ND "," OH "," OK "," OR "," PA "," RI "," SC "," SD "," TN "," TX "," UT "," VT "," VA "," WA "," WV "," WI "," WY "}

However, I'm trying to do this in google sheets, does anyone know a conversion for this aggregate function in google sheets?


text:
Q: Confused about how java synchronization works I have this example code based on a sample I found on the web to illustrate how to use wait() and notify(). Let me preface the code sample with the following statement a Java textbook makes about wait and notify.

A thread can't invoke a wait or notify method on an object unless it
  owns that's object's lock

Now take a look at this code and the output:
public class ThreadTester
{
    public class Message {
        private String msg;
        public Message(String str){ this.msg=str;}
        public String getMsg() { return msg; }
        public void setMsg(String str) { this.msg=str;}
    }

    public class Waiter implements Runnable{
        private Message msg;
        public Waiter(Message m){
            this.msg = m;
        }
        public void run() {
            String name = Thread.currentThread().getName();
            synchronized (msg) {
                try{
                    System.out.println(name + " acquired lock to msg object. waiting to get notified");
                    msg.wait();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(name + " waiter done at time: " + System.currentTimeMillis());
            }
            System.out.println(name + " waiter giving up msg object lock");
        }
    }

    public class Notifier implements Runnable {
        private Message msg;
        public Notifier(Message msg) {
            this.msg = msg;
        }
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println(name + " started");
            try {
                Thread.sleep(5000);
                synchronized (msg) {
                    String localMesg = name + " acquired lock to msg object. Notifier work done.";
                    System.out.println(localMesg);
                    msg.setMsg(localMesg);
                    msg.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    void runtest() {
        Message msg = new Message("process it");
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1,"waiter1").start();

        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();

        Notifier notifier = new Notifier(msg);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }

    public static void main(String [] args) {
        new ThreadTester().runtest();
    }
}

Here is the output:
waiter1 acquired lock to msg object. waiting to get notified
waiter2 acquired lock to msg object. waiting to get notified
All the threads are started
notifier started
notifier acquired lock to msg object. Notifier work done.
waiter1 waiter done at time: 1419745413721
waiter1 waiter giving up msg object lock

Now the question is, how can waiter2or notifier threads acquire the msg object's lock when waiter1 thread is still holding it? That seems to directly contradict the Java textbook statement I cite above. What am I missing?
Thanks for any help.

A: In the pattern
synchronized (msg) {
  msg.wait();
}

the lock on msg is indeed taken by the synchronized statement. But the msg.wait() call temporarily releases the lock and waits for a notification. A later msg.notify() or msg.notifyAll() can satisfy that wait. When the wait ends, the lock on msg is taken again. In the example the Notifier thread does msg.notify(), which means that one of the two Waiter threads can have its msg.wait() satisfied. That doesn't happen immediately, because the msg.notify() is inside a synchronized (msg) block so the Notifier thread is holding the lock on msg. As soon as that block exits, though, whichever thread's msg.wait() got the notification will take back the lock on msg and proceed.
This pattern is fairly fragile. The Notifier thread starts by doing a 5 second sleep, to make sure that the two Waiter threads have each reached their msg.wait(). Without the sleep, it would be possible for Notifier to do msg.notify() before either Waiter thread had done msg.wait(), and the msg.notify() would have had no effect. Because of issues like this, it is usually better to use synchronization classes such as Semaphore from the java.util.concurrent package, rather than using synchronized and wait/notify.

A: It wouldn't make sense to hold the lock while waiting. If you held the lock while waiting, you'd never be able to notify it.
According to §17.2.1 (Wait) of the JLS:
Thread t is added to the wait set of object m, and performs n unlock actions on m.
So, that means whilst the thread is waiting upon notification, the lock is released so notifiers can acquire the lock and drain the wait set.


text:
Q: MacOSX Console Application to slow or speedup speech without losing quality I have a .mp3 file that contains just voice and I would like to adjust the speed (slower or faster) while maintaining the same clarity. No chipmunks! Then write out the modified file to disk. In order to do this, I am trying to use the AVAudioEngine Framework but am a complete N00B to the framework. All the examples, I have found, are geared to modifying music or recording voice then playing it audibly. I just want to convert to a different speed and have it spit out the modified file. This was all I could figure out so far, I documented my confusion in the comments of the code.
import Foundation
import AVFoundation
import AVKit

print("Change Voice Speed")

let engine = AVAudioEngine()
let speedControl = AVAudioUnitVarispeed()
let originalFile = URL(fileURLWithPath: "/Users/User/Desktop/speech.mp3")

do {
   // What do I do with the input file ?
   let file = try AVAudioFile(forReading: originalFile)
} catch let error as NSError {
    print("There's an error: \(error)")
}

speedControl.rate += 0.1
engine.attach(speedControl)
// Do I need to attach a AVAudioRecorder and record here ?

print("Write New File")

let outputFile = URL(fileURLWithPath: "/Users/User/Desktop/modifiedSpeech.mp3")

// Don't know what settings to put for a .mp3 file are. Also not
// sure if this actually writes the file to disk

do {
   try AVAudioFile(forWriting: outputFile, settings: <#T##[String : Any]#>)
} catch let error as NSError {
    print("There's an error: \(error)")
}

A: Here is proof-of-concept code that speeds up a stereo M4A file and saves it as a WAVE file. There is minimal error handling and no attempt at handling different channel layouts, but hopefully it should get you started:
let engine = AVAudioEngine()

// Use AVAudioUnitTimePitch to avoid pitch shifts
let timePitch = AVAudioUnitTimePitch()
let player = AVAudioPlayerNode()

engine.attach(timePitch)
engine.attach(player)

engine.connect(player, to:timePitch, format: nil)
engine.connect(timePitch, to:engine.mainMixerNode, format: nil)

// Speed up the file 1.5x
timePitch.rate = 1.5

// Run the engine in manual rendering mode using chunks of 512 frames
let renderSize: AVAudioFrameCount = 512

let renderFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 44100.0, channels: 2, interleaved: true)!
let renderBuffer = AVAudioPCMBuffer(pcmFormat: renderFormat, frameCapacity: renderSize)!

try! engine.enableManualRenderingMode(.offline, format: renderFormat, maximumFrameCount: renderBuffer.frameCapacity)

try! engine.start()
player.play()

// The render format is also the output format
let output = try! AVAudioFile(forWriting: URL(fileURLWithPath: "/tmp/foo.wav"), settings: renderFormat.settings, commonFormat: renderFormat.commonFormat, interleaved: renderFormat.isInterleaved)
let file = try! AVAudioFile(forReading: URL(fileURLWithPath: "/tmp/test.m4a"))

// Read using a buffer sized to produce `renderSize` frames of output
let readSize = AVAudioFrameCount(Float(renderSize) * timePitch.rate)
let readBuffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: readSize)!

// Process the file
while true {
    do {
        // Processing is finished if all frames have been read
        if file.framePosition == file.length {
            break
        }

        try file.read(into: readBuffer)
        player.scheduleBuffer(readBuffer, completionHandler: nil)

        let result = try engine.renderOffline(renderBuffer.frameCapacity, to: renderBuffer)

        // Try to avoid adding silence
        let expectedFrames = AVAudioFrameCount(Float(readBuffer.frameLength) / timePitch.rate)
        if expectedFrames < renderBuffer.frameLength {
            renderBuffer.frameLength = expectedFrames
        }

        // Write the adjusted-rate audio
        try output.write(from: renderBuffer)
        if result != .success {
            break
        }
    }
    catch {
        break
    }
}

player.stop()
engine.stop()


text:
Q: How do I create and implement a free ssl certificate that does not raise a warning in a browser but simply ensures safe communication? That ensures safe communication being symbolized in the address bar.
I have an apache virtual server. I followed some tutorials but there is always this browser notification that it has to accept a certificate. And even after accepting the certificate, the page won't load. The php page itself is flawless, that's no source of error.
Share what one needs to know to create one's own certificates one can actually use, that means that raise no "accept certificate" or at least work after the certificate has been installed. I wouldn't write this here if the tutorials I came across so far weren't flawed.

A: As mentioned by Ken White in the comments, for commercial usage or deployments, a privately issues certificate will never be a safe certificate.
But, if you wish to use it for testing purposes, then you can try installing the "Private CA's and Roots" of your Private Certificate in the corresponding browsers. You should refer to browser help on how to do this.

A: You can generate your certificate and then get it signed for free by StartCom as a Class 1 verified certificate.  With a class 1 verified certificate, you don't get the "green" symbol in the http address bar and the certification is minimal (i.e., your domain name and personal email) but it does get rid of the browser security warning.  The application process is much leaner than for "upper class" certifications.  It looks like you are looking for something like that.


text:
Q: Calling server-side function from HTML on click (Classic ASP) I am trying to use my if else statement inside my Function Save()  but I cannot make it works? After click on the img button I want to verify if mycheckBox_A is checked. By the way I am using classic ASP
    <img src="blah" onclick="<%Save()%>"/>

    <%
    Function Save()
      If mycheckBox_A.checked Then
         'mycheckBox_A is checked
      Else
         'mycheckBox_B is checked
      End If
   End Function
    %>

A: The onclick attribute is not for calling server-side functions. You can assign JavaScript to this one, but not VB function. Think if you really need server-side code here that's possible that all you need in this exact place could be done with JavaScript.
EDIT:
If you need to do something on the server, you have to use AJAX to send only data you want to the server or submit the form with submit button or JavaScript call to submit() method. After submitting date you have to process it in your server-side function. Check this short tutorial on processing submitted with both POST and GET methods.

A: According to how to call a ASP function in the onclick event:

ASP functions execute only on the server side, while the onclick event
  executes only on the client side. You are trying to mix the two in an
  impossible way.
The problem is that the function calculate() does not exist on the
  client-side. The browser cannot see it.
You will need to use JavaScript (or another client-side technology) if
  you want to have this type of functionality.

This also applies to your Save() function.

A: You can't use onclick like this. Your only option is to have the button be either a submit button, or a link, then handle it on postback (if you need to do it server-side) or to write it in javascript if it can be done client-side.
Using postback to handle server logic is quite simple and basically how it works in modern ASP. You could have the submit button be in a form which has an integer, showing what you want to do, then handle this at the top of the page. That way, you can postback to the same page, handling different kinds of logic depending on what button was pressed, etc.
Should be noted that this makes for pretty ugly code, but then again, it's classic ASP.NET, it will look ugly no matter what.

A: No need to use any client script here at all
<%
'Have you POST to this page?
If Len(Request.Form) > 0 Then Call Save()

Sub Save()
  Dim a_check, i_item, i_items
  a_check = Split(Request.Form("checkbox") & "", ",")
  If IsArray(a_check) Then
    i_items = UBound(a_check, 1)
    For i_item = 0 To i_items
      'Could store this and output it later on but is just a quick example
      Response.Write a_check(i_item) & " is checked"
    Next
  End If
End Sub
%>

<html>
  <head>
  </head>
  <body>
    <!-- make the page POST to itself -->
    <form method="POST" action="">
      <! -- your other fields etc

      <input type="checkbox" name="checkbox" value="A" />
      <input type="checkbox" name="checkbox" value="B" />

      <input type="submit" value="Save" />
    </form>
  </body>
</html>

Quick example nothing special untested.

A: You can use JQuery post method and pass your variables to classic asp page.


text:
Q: How to include specific content of 1 jsp page to another jsp page I have 2 jsp pages HeaderTemplate.Jsp and mainMenu.jsp.In header Template.jsp i have one table inside body of html and in mainMenu before body I have to include that table content How i will do that please help me

A: You can use the below tag to include your jsp
<jsp:include page="..." />

A: there are different ways you can include jsps
1) <%@ include file="filename" %> is jsp directive syntax (static include).

Then the source JSP page is converted into a java servlet class. The
  included file can be a static resource or a JSP page. Generally JSP
  include directive is used to include header banners and footers.
The JSP compilation procedure is that, the source JSP page gets
  compiled only if that page has changed. If there is a change in the
  included JSP file, the source JSP file will not be compiled and
  therefore the modification will not get reflected in the output.

2) <jsp:include page="relativeURL" /> is a dynamic include, since you want to include jsp, you need to use <jsp:include>, since it works with dynamic content

The jsp:include action element is like a function call. At runtime,
  the included file will be 'executed' and the result content will be
  included with the soure JSP page. When the included JSP page is
  called, both the request and response objects are passed as parameters

3) you can use templates framework like tiles, freemaker etc. which manages your templates and include jsps defined in your custom template.
for more about tiles
http://tiles.apache.org/framework/tutorial/
if you have many jsps and one or more layout design then template frameworks will be more flexible


text:
Q: How to change color of a Tkinter treeview's row based on condition with python? I'm trying to change row colors of my program. I've already seen many tutorials and visited so many more websites but none of what the say works. This is my code, I don't understand where is the problem. The program runs without errors by the way. Thank you guys in advanced!
def base_datos(self):
    self.tabla = ttk.Treeview(self, column=('Nombre', 'Apellidos', 'Correo', 'Número', 'Estado'),
                              selectmode='browse')

    scroll = ttk.Scrollbar(self, orient='vertical', command=self.tabla.yview)
    scroll.place(relx=0.968, rely=0.304, height=326)
    self.tabla.configure(yscrollcommand=scroll.set)

    self.tabla.column('#0', anchor='c')
    self.tabla.column('#1', anchor='c')
    self.tabla.column('#2', anchor='c')
    self.tabla.column('#3', anchor='c')
    self.tabla.column('#4', anchor='c')
    self.tabla.column('#5', anchor='c')

    self.tabla.heading('#0', text='ID')
    self.tabla.heading('#1', text='Nombre')
    self.tabla.heading('#2', text='Apellidos')
    self.tabla.heading('#3', text='Correo')
    self.tabla.heading('#4', text='Número')
    self.tabla.heading('#5', text='Estado')

    self.tabla.tag_configure('sub', background='#6FE87F')
    self.tabla.tag_configure('no-sub', background='#D45E5E')

    self.lista_usuarios = Usuario.mostrar_db()
    self.lista_usuarios.reverse()

    for u in self.lista_usuarios:
        if self.sub_caducada(u[5]):
            my_tag = 'no-sub'
        else:
            my_tag = 'sub'
        self.tabla.insert('', 'end', text=u[0], values=(u[1], u[2], u[3], u[4], u[5]), tags=(my_tag,))

    self.tabla.place(relx=0.02, rely=0.3, width=1345, height=330)


text:
Q: How to configure codehaus.mojo jaxws-maven-plugin:wsimport to access ssl-protected WSDL Using Spring Initializer adding only one dependency "Spring Web Service", I created a spring boot maven project as SOAP Web Service Client. I try to use mojohaus/jaxb2-maven-plugin to generate client artifacts from WSDL which is ssl protected. Below is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <wsdlUrls>
                        <wsdlUrl>https://sample.com/MyService?WSDL</wsdlUrl>
                    </wsdlUrls>
                    <packageName>com.example.consumingwebservice.wsdl</packageName>
                    <sourceDestDir>src/main/java</sourceDestDir>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

I got below error when I run mvn clean package:
parsing WSDL...
[ERROR] PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.
After I add
<vmArgs>
    <vmArg>-Djavax.net.ssl.trustStore=path/to/truststore/trust.jks</vmArg>
</vmArgs>

to the configuration section of jaxws-maven-plugin, it seems to me the jaxws-maven-plugin:wsimport finds the truststore but a different error occurs:
parsing WSDL...
[WARNING] schema_reference: Failed to read schema document 'MyService?xsd=1', because 'https' access is not allowed due to restriction set by the accessExternalSchema property.
line 4 of https://sample.com/MyService?WSDL#types?schema1
MyService_schema1.xsd is in the same folder as .wsdl is. It is imported to WSDL.
<definitions xmlns:wsu= ...
<types>
<xsd:schema>
<xsd:import namespace="xxx" schemaLocation="https://sample.com:443/I94WS/I94DocQuery?xsd=1"/>
</xsd:schema>
...

Dose anyone know how to configure the jaxb2-maven-plugin to let its wsimport to access ssl-protected WSDL, or bypass/disable the ssl check?


text:
Q: Implementing bootstrap select into an existing project I'm working with a massive code base here and trying to shoe horn in bootstrap-select to render in a nice fancy drop down. https://developer.snapappointments.com/bootstrap-select/
We have bootstrap 3.0.0 and jquery 1.12.4 and from what I understand for bootstrap-select I need at least bootstrap 3.3.7 and I'm not quite sure how to go about updating bootstrap. We've got a public folder housing the current bootstrap js and css files.
I've found that adding
 <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">

Gives me the desired look for the drop downs but breaks the rest of the styling on the page. Honestly kind of lost for a direction here.

A: For the newest version of bootstrap use:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

For version 3.37 specifically, I believe you can just change the number in the link from 4.3.1 to your desired version.
Hope this helps!
You may also want to try this (with your version number) in the terminal
gem install bootstrap -v 4.3.1

A: After such a simple fix my brain hurts. I should have read the getting started page better... By adding the 2 lines below the styling is displaying correctly now.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/css/bootstrap-select.min.css">

<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/js/bootstrap-select.min.js"></script>


text:
Q: How do I get a variable from a text input in tkinter? I have tried to get a variable from a text input by doing this:
username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var).place(x = 110, y = 100)
username = username_var.get()

However when I try to acess the variable in a function it does not do anything.
My two functions are:
def ifSubmit():
    writeToFile(service)
    writeToFile(username)

def writeToFile(input_variable):
    with open("password&usernames.txt", "a") as input:
        input.writelines(input_variable)

But when I open the text file, nothing appears. I have also tested with:
writeToFile('hello')

In this case I do get hello in my text file and so I suspect that it is the variables that is the probelm not the writeToFile() function.
So am I retrieving the text being inputed correctly?
Full code:
import string
import random
from tkinter import *

mypasslist = []

with open("password&usernames.txt", "r") as input:
    for line in input:
        items = line.split()
        mypasslist.append([item for item in items[0:]])

def generatePassword():
    characters = string.ascii_letters + string.punctuation  + string.digits
    password =  "".join(random.choice(characters) for x in range(random.randint(8, 16)))
    return password

def writeToFile(input_variable):
    with open("password&usernames.txt", "a") as input:
        input.writelines(input_variable)

top = Tk()
top.geometry("1920x1080")

def ifSubmit():
    global a
    a = generatePassword()
    label1 = Label(top, text='Your password is: %s' % a, font=("Arial", 11)).place(x = 40, y = 170)
    label1 = Label(top, justify='left', text='Your password and username has been saved, you can access them below.').place(x = 40, y = 227)
    copy_button = Button(top, text = 'Copy', command=copyText).place(x=40, y=195)

    writeToFile(service)
    writeToFile(username)
    writeToFile(str(a))

def copyText():
    top.clipboard_clear()
    top.clipboard_append(a)
    top.update()

# the label for user_name
Service = Label(top, text = "Service").place(x = 40, y = 60)
user_name = Label(top, text = "Username").place(x = 40, y = 100)

submit_button = Button(top, text = "Submit", command=ifSubmit).place(x = 40, y = 130)

service_var = StringVar()
Service_input_area = Entry(top, width = 30, textvariable=service_var)
Service_input_area.place(x = 110, y = 60)
service = service_var.get()

username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var)
username = username_var.get()
user_name_input_area.place(x = 110, y = 100)

top.mainloop()

A: A few things stick out:
Let's say you're creating a label widget:
label = Label(top, text="This is a label").place(x=40, y=40)

This is incorrect. label will be bound to whatever the place method returned, because you're chaining the Label instantiation and the place method. The place method always returns None, so label will be None. You need to split this up into two separate statements - one to instantiate and bind the widget, the other to place it:
label = Label(top, text="This is a label")
label.place(x=40, y=40)

You need to do this for every widget in your script, regardless of whether it's a label, button, etc.
Also, in a few places, you do something like this:
var = StringVar()
entry = Entry(..., textvariable=var)
user_input = var.get()

Which is also incorrect. You create an entry widget, and then immediately read from it using var.get. Since you just created the widget, its contents will be empty, so in this case user_input will be empty. You also never change user_input, or read from the entry widget again at a later point, so what you end up writing to the file will just be an empty string. You need to call var.get once the user has actually had a chance to write something. A button callback would be a good place to do this.

A: This answer has already has pointed out most of the mistakes.
I also see a few more things that you are doing wrong specifically under isSubmit() function. Here you are creating 2 labels and a button that would be created whenever the submit button is pressed. you either need to destroy the previous label and buttons or create a label and button only once and use place() and place_forget() to show and hide them. Also, try to avoid using python inbuilt class and function names to name your variables.
Here is your corrected code:
import string
import random
from tkinter import *

mypasslist = []

with open(r"file.txt", "r") as inp:
    for line in inp:
        items = line.split()
        mypasslist.append([item for item in items[0:]])

def generatePassword():
    characters = string.ascii_letters + string.punctuation  + string.digits
    password =  "".join(random.choice(characters) for x in range(random.randint(8, 16)))
    return password

def writeToFile(input_variable):
    with open(r"file.txt", "a") as inp:
        inp.writelines(input_variable)

top = Tk()
top.geometry("1920x1080")

def ifSubmit():

    passwd = generatePassword()
    label1.config(text='Your password is: %s' % passwd)
    label1.place(x = 40, y = 170)

    label2.config(text='Your password and username has been saved, you can access them below.')
    label2.place(x = 40, y = 227)

    copy_button = Button(top, text = 'Copy', command=copyText).place(x=40, y=195)

    writeToFile(service_var.get()+', ')
    writeToFile(username_var.get()+', ')
    writeToFile(passwd+'\n')

def copyText():
    top.clipboard_clear()
    top.clipboard_append(passwd)
    top.update()

# the label for user_name
Label(top, text = "Service").place(x = 40, y = 60)
Label(top, text = "Username").place(x = 40, y = 100)

submit_button = Button(top, text = "Submit", command=ifSubmit).place(x = 40, y = 130)

service_var = StringVar()
Service_input_area = Entry(top, width = 30, textvariable=service_var)
Service_input_area.place(x = 110, y = 60)

username_var = StringVar()
user_name_input_area = Entry(top, width = 30, textvariable=username_var)
user_name_input_area.place(x = 110, y = 100)

# label 1
label1 = Label(top, font=("Arial", 11))
label2 = Label(top, justify='left')

copy_button = Button(top, text = 'Copy', command=copyText)

top.mainloop()


text:
Q: Cursor function is causing variable to not pass to frontend So I am trying to use infinite scroll in react and according to mongoose docs I should use .cursor() to avoid overloading memory. However, I keep getting the following error.
The following is my code for the backend and the latter will be for the frontend. P.S. it works without the whole cursor function.
exports.getCountries = async (req, res) => {
  const { _page } = req.query;
  console.log(_page);
  // var countries = [];
  const beginIndex = Number(_page) * 6 - 6;
  var countriesList;
  try {
    const countries = await Country.find().skip(beginIndex).limit(6).cursor();

    countries.next(function (error, doc) {
      countriesList = doc;
    });

    return res.status(200).json([countriesList]);
  } catch (error) {
    return console.log('error during get countries', error);
  }
};

frontend:
const HomeScroll = () => {
  const classes = useStyles();
  const {
    fetchNextPage, //function
    hasNextPage, // boolean
    isFetchingNextPage, // boolean
    data,
    status,
    error,
  } = useInfiniteQuery(
    '/country',
    ({ pageParam = 1 }) => getPostsPage(pageParam),
    {
      getNextPageParam: (lastPage, allPages) => {
        return lastPage.length ? allPages.length + 1 : undefined;
      },
    }
  );

  const intObserver = useRef();
  const lastPostRef = useCallback(
    (country) => {
      if (isFetchingNextPage) return;

      if (intObserver.current) intObserver.current.disconnect();

      intObserver.current = new IntersectionObserver((countries) => {
        if (countries[0].isIntersecting && hasNextPage) {
          console.log('We are near the last post!');
          fetchNextPage();
        }
      });

      if (country) intObserver.current.observe(country);
    },
    [isFetchingNextPage, fetchNextPage, hasNextPage]
  );

  if (status === 'error')
    return
Error: {error.message}
;

  const content = data?.pages.map((pg) => {
    return pg.map((country, i) => {
      if (pg.length === i + 1) {
        return (
          <CountryListCard
            ref={lastPostRef}
            key={country.id}
            country={country}
          />
        );
      }
      return <CountryListCard key={country.id} country={country} />;
    });
  });

  return (
    <>
      <Box sx={{ flexGrow: 1 }}>
        <Grid
          container
          spacing={4}
          className={classes.gridContainer}
          justify='center'
        >
          <Grid item xs={12} sm={6} md={4}>
            <Item>
              {content}
              {/* <Review ref={lastPostRef} key={country._id} country={country} review={review}/> */}
            </Item>
          </Grid>
        </Grid>
      </Box>

      {isFetchingNextPage &&
Loading More Posts...
}

        Back to Top

    </>
  );
};

export default HomeScroll;

Thanks for any help!
I tried changing from array to Object and vice versa, I tried use a for loop as shown in the mongoose docs as well. Nothing seems to work and even though the doc variable is showing the full array I need. It doesn't show up on the frontend.


text:
Q: how to delete an item from a listBox in WP8 i have a list box view in windows phone that i want to delete an item from it upon a specified event .... how can i accomplish that
this is my XAML code
 <ListBox x:Name="lstData2"
    ItemsSource="{Binding DataCollection2, Source={StaticResource PinsCollection}}" Grid.ColumnSpan="3" Foreground="#FF1D53D0" Height="583" VerticalAlignment="Bottom">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Tap="StackPanel_Tap">
                <Image Margin="8"
                    VerticalAlignment="Top"
                    Source="{Binding ImageUri}"
                    Width="100"
                    Height="100" />
                <StackPanel Height="93" Width="259" >
                    <TextBlock Margin="8"
                        Width="250"

                        TextWrapping="Wrap"
                        VerticalAlignment="Top"
                        HorizontalAlignment="Left"
                        Foreground="#FF1D53D0"
                        Text="{Binding Pinnedname}"  Height="33" RenderTransformOrigin="0.5,0.5" FontFamily="Segoe WP SemiLight" FontSize="24" FontWeight="Bold" />
                    <TextBlock Width="155"
                        Margin="8,0,8,8"
                        VerticalAlignment="Top"
                        HorizontalAlignment="Left"
                        Text="{Binding Status}" Foreground="#FF1D53D0" FontFamily="Segoe WP SemiLight" />
                    <toolkit:ContextMenuService.ContextMenu>
                        <toolkit:ContextMenu>
                            <toolkit:MenuItem Header="Remove Pin" Click="RemovePin_Click" Tag="{Binding pinId}"/>

                        </toolkit:ContextMenu>
                    </toolkit:ContextMenuService.ContextMenu>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: You are using binding to show your data (DataCollection2) in a list view. Your list view is updated when your data is modified. To delete an item in the ListView, you should remove the corresponding item in the DataCollection2 and the list view will be automatically updated. Make sure that the DataCollection2 is an ObservableCollection instance.


text:
Q: Adam optimizer - ValueError: tf.function-decorated function tried to create variables on non-first call I am using tensorflow 2.3
The code below
import  tensorflow as tf

y_N= tf.Variable([1., 2., 3.],name="dd")

@tf.function
def loss():
    return -tf.reduce_mean(input_tensor=tf.reduce_sum(input_tensor=tf.math.log(y_N), axis=0))

@tf.function
def run():
    tf.keras.optimizers.Adam(0.5).minimize(loss, var_list=[y_N])

run()

gives exception
ValueError: tf.function-decorated function tried to create variables on non-first call.

Problem looks like tf.keras.optimizers.Adam(0.5).minimize(loss, var_list=[y_N]) creates new variable on > first call, while using @tf.function. If must wrap it under @tf.function, how should I modify it? (in real case run() is a much bigger function)

A: I think it's probably not about the optimizer. Because of using function decorator, I think we need to enable the eager execution of tf.functions as follows. Source
import  tensorflow as tf
tf.config.run_functions_eagerly(True)

y_N= tf.Variable([1., 2., 3.],name="dd")

@tf.function
def loss():
    return -tf.reduce_mean(
        input_tensor=tf.reduce_sum(
            input_tensor=tf.math.log(y_N), axis=0
        )
    )

@tf.function
def run():
    tf.keras.optimizers.Adam(0.5).minimize(loss, var_list=[y_N])

run()
print(y_N)

<tf.Variable 'dd:0' shape=(3,) dtype=float32,
numpy=array([1.5000134, 2.5000117, 3.5000103], dtype=float32)>

Update
The above code would run on eager mode with the cost of performance. To run it on graph mode, first, create instance of optimizers.Adam class and use class method afterwards as follows:
y_N = tf.Variable([1., 2., 3.],name="dd")
opt = tf.keras.optimizers.Adam(0.5)

@tf.function
def loss():
    return -tf.reduce_mean(
        input_tensor=tf.reduce_sum(
            input_tensor=tf.math.log(y_N), axis=0
        )
    )

@tf.function
def run():
    opt.minimize(loss, var_list=[y_N])

run()
print(y_N)

<tf.Variable 'dd:0' shape=(3,) dtype=float32,
numpy=array([1.4999985, 2.499997 , 3.4999952], dtype=float32)>

Also you can check this for similar details.

A: I'm afraid I won't be able to provide you all the explanations you might be looking for, as the documentation for @tf.function is somewhat complex, but in my experience building neural nets with Tensorflow, only the subparts of the "running" process must be decorated with @tf.function, and this part must be within with tf.GradientTape() as tape:. Your code works if I implement it that way:
import tensorflow as tf

y_N= tf.Variable([1., 2., 3.], name="dd")

@tf.function
def loss():
    return -tf.reduce_mean(input_tensor=tf.reduce_sum(
                           input_tensor=tf.math.log(y_N), axis=0))

def run():
    with tf.GradientTape() as tape:
        tf.keras.optimizers.Adam(0.5).minimize(loss, var_list=[y_N])

run()

print(y_N)

<tf.Variable 'dd:0' shape=(3,) dtype=float32, numpy=array([1.4999985, 2.499997 ,
    3.4999952], dtype=float32)>

A: I found out that  after calling minimize function, it will create an iter variable, by calling self.iterations once.
(This happens in tensorflow/python/keras/optimizer_v2/optimizer_v2.py)
Subsequent call of the self.iterations will not create a new variable -
as iter has already been created.
Therefore, by calling to make it work, we need to create the optimizer once outside, and pass it in to @tf.function. It will still create variables in minimize function, but it will only do it once since we don't repeatedly create the Adam model.
import  tensorflow as tf

y_N= tf.Variable([1., 2., 3.],name="dd")

@tf.function
def loss():
    return -tf.reduce_mean(input_tensor=tf.reduce_sum(input_tensor=tf.math.log(y_N), axis=0))

@tf.function
def run(adam):
    adam.minimize(loss, var_list=[y_N])

adam=tf.keras.optimizers.Adam(0.5)

run(adam)


text:
Q: Bring a control to front I have a user control that uses a textbox and a list box. List box isn't visible, it only becomes visible when user starts typing or click in text box.
I have added the user control to a group box which is on the form.
Now when the listox becomes visible, it stays inside the group box, and can't see the full height. I wan't it float on top so that i can see the full height.
I have looked around, implemented some solutions but nothing worked for me.
Constructor for the user control
namespace YarCustomControl
{
    public partial class YarCustom : TextBox
    {
        public YarCustom()
        {
            InitializeComponent();

            _code = "";
            _id = -1;

            //list box handling
            listBox = new ListBox();
            listBox.Visible = false;
            listBox.Font = this.Font;
            listBox.Location = this.Location;
            listBox.BorderStyle = BorderStyle.Fixed3D;
            listBox.Resize += new EventHandler(listBox_Resize);
            //listBox.SelectedValueChanged += new EventHandler(listBox_SelectedValueChanged);
            listBox.KeyDown += new KeyEventHandler(listBox_KeyDown);
            listBox.Click += new EventHandler(listBox_Click);

            //test => no affect on listbox
            this.Controls.Add(listBox);

            listBox.Visible = false;

        }
}
}

and the following method makes the listbox visible. Both SetchildIndex (commented and not commented) throw an error
private void makeListBoxVisible()
        {
            Form parentForm = (this.FindForm() as Form);

            //parentForm.Controls.SetChildIndex(listBox, 0);
            this.Controls.SetChildIndex(listBox, 0);
            listBox.Visible = true;
            listBox.BringToFront();
        }

What is the best approach for handling something like this?
My environment is VS2010 and WinForms.

A:
Now when the listox becomes visible, it stays inside the group box,
  and can't see the full height. I wan't it float on top so that i can
  see the full height.

Simply put it directly on the Form.


text:
Q: singly linked list head and tail method? I'm relatively new to c programming language, and was playing around to get familiar with it, but I'm not sure how to actually implement a linked list with the following structs and data I'm trying to do(below). Basically the goal is to add an item from a singly linked list with a head and tail.
Update: I tried to do write some code in my add function, haven't sorted it but is that how it would look like?
CODE SOURCE
typedef struct {
    char car_model[32],car_name[32];

} CarObjects;

typedef struct myNode{

    struct myNode* next;
    CarObjects* data;

} MyList;

//initialize list
void declareList(MyList* someList){
    someList->next = NULL;
}

void insertElementByTitle(MyList* someList, CarObjects* someCar){

    //first case adding to an empty list.
    if(someList == NULL){
        someList = malloc(sizeof(MyList));
        someList->data = someCar;
        someList->next = NULL;
    }
//END OF first case adding to an empty list.

//make thee list's head and tail node, point to the first element since its an empty list
    someList->head = someList;
    someList->tail = someList->head;

    while(someList->next != NULL)
       someList = someList->next;

    someList->next = malloc(sizeof(MyList));
    someList = someList->next;
    someList->data = newBook;
    someList->next = NULL;

}

int main(){

   MyList* listHead= NULL;
   MyList* listTail= NULL;

   //Somehow add an element to the list

   return 0;
}

A: At first properly define your structure.
typedef struct car{
char car_model[32],car_name[32];
};

typedef struct myList{
myList * next;
car * carObject;
};

Now, you are trying to insert as the Insertion Sort technique.
void insertElementByTitle(MyList* someList, CarObjects* someCar){
\\I assume someList is pointing the head of the linked list
\\One more assumption that, the Linked List is already sorted and need to inset
\\someCar in the correct position.
MyList *secondPointer = someList->next;
while(secondPointer != null)
{
     if(ifCarIsInBetweenSomeListAndSecondPointer(someList,secondPointer,someCar))
     {
      someList->next = newNode(someCar);
      someList->next->next=secondPointer;
      break;
     }
  someList = secondPointer; secondPointer = secondPointer->next;
}
if(secondPointer == null)
{
     someList->next = newNode(someCar);
}
}

Now, you need two function
myNode* newNode(car * someCar);
bool ifCarIsInBetweenSomeListAndSecondPointer(myNode *someList,myNode *secondPointer,car *someCar);

myNode* newNode(car * someCar){
myNode * t =(struct myNode*)malloc(sizeof(struct myNode));
t->carObject = someCar;
t->next= null;
return t;
}

bool ifCarIsInBetweenSomeListAndSecondPointer(myNode *someList,myNode *secondPointer,car *someCar){
if( (strcmp(someList->carObject->car_name,someCar->carObject)<0) &&(strcmp(someCar->carObject,secondPointer->carObject->car_name)<0))
          return true;
return false;
}

Refer online reference such as geeksforgeeks-linked list, to get better understanding.


text:
Q: Computer restarts when I don't turn off the monitors before clicking shutdown (No system error) For quite a while now my Computer keeps restarting when I shut it down. The only way it doesn`t turn on again is to either click the shut down button and then extremly fast turn off the monitor, or run a command that shuts down the PC in some seconds and before it starts turn off the monitors.
When I turn the Monitors on again after it the PC is shut down, it doesn`t restart.
I have Windows 10 and a reinstall of a new version didn't help.
I guess it`s in something in the BIOS but I can't find it out.

A: According to your description, the problem is probably not with Windows.
It may possibly be some installed application, which you can verify by booting in
Safe mode to disable all third-party applications and drivers.
For the BIOS, you may boot into the BIOS and reset it (losing all settings,
so don't do it if you have encrypted the disk).
You may also search for a new BIOS from the website of the manufacturer
of your motherboard, but be very careful since an error in the installation
may brick the computer.
Otherwise, this may be a hardware error, maybe related to the power supply,
and is better handled by a professional.


text:
Q: Codeigniter Smiley Not Showing Up In Preview Area I have created a area where user can type in some text and also add smiley into the text area. smiley helper
How ever when I click on my preview button it does not show the generated smiley.

Question how to make sure on the preview are if has any smiles on
  question will show up in preview properly. I use preg_replace_callback on my preview function on controller. and also .replace on script Update I found this on user guide but not sure where to add it on code

Generate the smiles here.
<?php

class Question extends CI_Controller {

    public $data = array();

    public function __construct() {
        parent::__construct();
        $this->load->helper('smiley');
    }

    public function create() {

        $this->load->library('table');

        $image_array = get_clickable_smileys(base_url('assets/img/smiley'), 'question');

        $col_array = $this->table->make_columns($image_array, 8);

        $data['smileys'] = $this->table->generate($col_array);

        $this->form_validation->set_rules('title', 'title', 'trim|required');
        $this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');

        if ($this->form_validation->run() == true) {

        }

        $data['page'] = 'question/create';

        $this->load->view($this->config->item('config_template') . '/template/template_view', $data);
    }

    public function preview() {
        $data = array('success' => false, 'question' => '', 'tag' => '');

        if ($_POST) {
            $string = $this->input->post('question');

        $match = array(
            '<' => '<',
            '>' => '>',
        );

        $new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
        return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
        }, $string);

            $data['question'] =  $new_data;
            $data['success'] = true;
        }

        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($data));
    }

}

Script On View

A: Got it working
I had to use $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
public function preview() {
    $data = array('success' => false, 'question' => '', 'tag' => '');

    if ($_POST) {
        $string = $this->input->post('question');

        $match = array(
            '<' => '<',
            '>' => '>',
        );

        $new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
        return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
        }, $string);

        $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
        $data['success'] = true;
    }

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($data));
}


text:
Q: how to set a timeout for download in C# I am writing an application that downloads web contents.The problem is, when download starts, the whole app freezes until it download is completed. Is there a way to set a timeout which stops the process after sometime?

A: If you don't want the whole program to freeze, then you can complete the download on a BackgroundWorker, but if you simply want to run a process for a given amount of time and then stop it, you can use Process.WaitForExit, and set the timeout to 2 minutes.
After 2 minutes, if it returns false, then you can use Process.Kill to terminate it.
Process process = Process.Start("myDownloadApp.exe");

//wait 2 minutes
if (!process.WaitForExit(120000))
{
    process.Kill();
}

A: Task.Factory.StartNew allows you to run a function in a seperate thread. That means you can run your function in the background without affecting the main thread. Might be an option...
You could use it with System.Timers.Timer which allows you to run a process after a set time. You set that to 2 minutes and kill the process if it's still running. More info here: https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8


text:
Q: how passing web url string to function I have a problem passing a string to a function that is an web address in order  to open that particular direction through a webview.
-(IBAction)toWeb:(NSString*)web_direction {
    UIViewController *webViewController = [[[UIViewController alloc] init] autorelease];

    UIWebView *uiWebView = [[[UIWebView alloc] initWithFrame: CGRectMake(0,0,320,480)] autorelease];

     [uiWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:web_direction]]];

    [webViewController.view addSubview: uiWebView];
    webViewController.title = @"web bar";
    [self.navigationController pushViewController:webViewController animated:YES];

}

I want to call that function via   MKannotation using:
NSString *direction = @"http://www.google.com";
[btnDetails addTarget:self action:@selector(toWeb:direction) forControlEvents:UIControlEventTouchUpInside];

But the app crashes. Any idea about that?

A: You can't pass parameters in that manner with @selector().  @selector() is only meant to reference a selector to invoke in response to something, in this case a target on a button.
If you want to invoke different urls based on the button pressed, here's a suggestion on how to approach it (for this sample I use three different buttons to show you how you can conditionally use different urls based on the button pressed):
This goes where you are setting the targets:
btnDetailsForGoogle.tag = 1;
[btnDetailsForGoogle addTarget:self action:@selector(toWeb:) forControlEvents:UIControlEventTouchUpInside];
btnDetailsForYahoo.tag = 2;
[btnDetailsForYahoo addTarget:self action:@selector(toWeb:) forControlEvents:UIControlEventTouchUpInside];
btnDetailsForBing.tag = 3;
[btnDetailsForBing addTarget:self action:@selector(toWeb:) forControlEvents:UIControlEventTouchUpInside];

And here's the updated IBAction method
-(IBAction)toWeb:(id)sender {
    NSString *web_direction = @"";
    if (((UIButton *)sender).tag == 1)  web_direction = @"www.google.com";
    if (((UIButton *)sender).tag == 2)  web_direction = @"www.yahoo.com";
    if (((UIButton *)sender).tag == 3)  web_direction = @"www.bing.com";
    UIViewController *webViewController = [[[UIViewController alloc] init] autorelease];

    UIWebView *uiWebView = [[[UIWebView alloc] initWithFrame: CGRectMake(0,0,320,480)] autorelease];

     [uiWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:web_direction]]];

    [webViewController.view addSubview: uiWebView];
    webViewController.title = @"web bar";
    [self.navigationController pushViewController:webViewController animated:YES];

}

A: A selector is the name of the method; it doesn't include parameters.  You would need to use...
[btnDetails addTarget:self action:@selector(toWeb:) forControlEvents:UIControlEventTouchUpInside];

...and find another way to get the URL string.  The parameter that toWeb: gets is the button (usually called "sender").


text:
Q: If else Jquery for IP number I'm trying to test to see if my IP number matches with the one specified. I'm new to Javascript, and not sue what's wrong with my code.

$(document).ready(function() {
  $.getJSON("http://jsonip.com/?callback=?", function(data) {
    console.log(data);
    var userIP = (data.ip);
    var myIP = 172.16.254.1;

    if (userIP == myIP) {
      $("body").html("
IP Login Success!
");
    } else {
      $("body").html("
Invalid IP!
");
    }
  });
});

How can I make it see if the IP matches the users?

A: Try:
var myIP = "172.16.254.1";

You are assigning a literal string to myIP.


text:
Q: discord.py | check for 2 or more messages I tried to program a discord bot that checks several messages one after the other.
So if someone writes "Hello", the bot should write "Hello there" and check whether the following message "How are you?" is.
    @client.event
async def on_message(message):
    if 'hi' in message.content:
        await message.channel.send('Hello there.')
        if 'How are you?' in message.content:
            await message.channel.send('I am fine.')

But the bot ignores the second command. Why?

A: When writing it like that, it checks if there is a How are you in the message where there was a hi. To make your bot respond and then wait for a response use wait_for
It would look like this:
@client.event
async def on_message(message):
    if 'hi' in message.content:
        await message.channel.send('Hello there.')
        await bot.wait_for("How are you", check=check)

What this is doing, is if a message has hi in it, the bot responds, and then waits for a message with How are you

A: The second message you send will again passes as message to on_message() function.
try this
async def on_message(message):
    if 'hi' in message.content:
        await message.channel.send('Hello there.')
    if 'How are you?' in message.content:
        await message.channel.send('I am fine.')

A: To complete this article and to help others I am posting the correct and finished code in here.
@client.event
async def on_message(message):
    if message.content.startswith('Hi'):
        channel = message.channel
        await channel.send('Hello!')

        def check(message1):
            return message1.content == 'How are you?' and message1.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send("I am fine.".format(msg))

I hope this article helps some other people! Have a great day!


text:
Q: Advantages of redirecting to a login page versus having a drop down menu login form with javascript I've noticed that a lot of big sites, namely gmail, require you to redirect to a specific login page where others will have a drop down menu to login. What are the advantages/disadvantages of both?
Thanks a lot

A: The primary advantage of having a logon mechanism integrated into the page is it provides the ability to logon and/or create a user account without losing the context of what the user is doing.
For example, on StackOverflow a user can enter a new question or answer without being logged on.  Upon clicking the "Submit" button, they are prompted if they want to create an account or use an existing account.  This can be done without losing the information by redirecting to another page.
Another example could be on a recipe website.  A user might find a recipe they like, and click on the "Add To Favorites" button.  If they're not already logged on, a popup box could allow them to create an account or logon with an existing account.  When done, the recipe would then be added to their favorites within their newly created account.  The alternative would be a logon link that goes to a different page, forcing the user to then find the recipe they were interested in again once they were logged on.  This severely disrupts user flow and could potentially cost a lot of users.
A separate logon page has the advantage of being easier to implement.  Pages that have "secure" information can simply redirect to the logon page, rather than having to worry about rendering UI without the context of a valid session.
Overall, it's a choice that has to be made depending on the context of your website, after a careful study of user habits, and tested on a realistic sampling of your user base.  I think this decision is definitely not arbitrary, nor should it be taken lightly.

A: From a user-interface perspective, it depends on how much functionality you want to provide to users who are not logged in.  If, like gmail, the answer is 'none', you have nothing to show non-logged-in users except the login form.  If you're a store website, you don't want to require that someone log in just to browse, but you do want to make it easy to log in from anywhere - so you put a login mechanism on each page.
Also, if you have a dedicated login page you can use it for more than just the one app.  Google's authentication system is significantly wider than just gmail.


text: Q: Convert Angular Webpage in AMP (Accelerated mobile Pages) I have progressive web app in angular8. Is it possible to convert any created component into AMP? Searched a lot but nowhere related concept is documented well. Please help.


text:
Q: gps doesn't provide my longitude and latitude accurately Android? I am usin location service for getting latitude and longitude of my location.While running my program it will give me wrong latitude and longitude.How can i get my current location details accurately? Is there any settings in mobile /device ?
String locationProvider = LocationManager.GPS_PROVIDER;
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER )) {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        Log.w(TAG,"CurrentLocProvider :"+locationProvider);

        location=locationManager.getLastKnownLocation(locationProvider);
        Log.i(TAG,"Location :"+location);
        if(location!=null){
            Log.i(TAG,"Location Lat :"+location.getLatitude());
            latitude = Double.toString(location.getLatitude());
            longitude = Double.toString(location.getLongitude());

            txtView.append("\nLatitude : "+latitude+"\n Longitude : "+longitude);
        }

After some time
public void onLocationChanged(Location location) {
Log.i(TAG,"Lat :"+location.getLatitude();
Log.i(TAG,"Long :"+location.getLongitude();

}

Also giving me wrong location.Some times USA,In another device china.In Different device it is giving different results?
How can i get the currect result?
Thanks,
aare.

A: Hm, it is very unlikely (but possible) to give you wrong coordinates - if the device GPS is not working properly.
BTW - the method getLastKnownLocation may return completely wrong data, as described in another stackoverflow question:
this location can be "out-of-date", since the method returns the location when the GPS was used the last time.
Give a look at onStatusChanged, also. You may output the status changes of the GPS to get a better vision of what's going on.

A: You should also check if network location provider is enabled (users can have this disabled in settings):
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

Or even better: use LocationManager.PASSIVE_PROVIDER.


text:
Q: Instagram pictures to Google Maps in a radius of 1km around you I'm wondering if it's possible to get Instagram photo's to Google Maps working with API's. So far I got Google Maps working and it's showing my current location, along with a radius of 1km around me.
The thing I want to do is show a certain amount of Instagram pictures in that radius around me, taken by everybody.
But so far, I got no idea where or how to start, and if it's even possible.
The code for my google maps is:
    </script>

A: You have to use the media/search API to get photos around a location (lat/lng) and distance:
https://api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&distance=1000&access_token=ACCESS-TOKEN

Here is an implementation of getting instagram photos around any radius on google maps:
http://www.gramfeed.com/instagram/map


text:
Q: Formula Help - alternative of using nested if in formula due to size limitation Can anyone kindly help me with with following salesforce formula I have been trying to write.
Formula is getting fairly complex and large due to number of conditions. Basically there are 4 status fields, for budget, schedule, scope and participation. budget and schedule status are already formula fields while scope and participation being picklists. Now there are 2 more fields (picklists) budget status override and schedule status override. If override fields has values they take priority in calculating overall status. I have been trying to write overall status formula but this is just crossing formula compilation limit of 15k bytes.
This is what I have written.
IF(
    OR(
        ISPICKVAL(Project_Schedule_Override__c,"Red"),
        ISPICKVAL(Project_Budget_Override__c,"Red")
    ),
    "Red",
    IF(
        AND(
            ISBLANK(TEXT(Project_Schedule_Override__c)),
            NOT(ISBLANK(TEXT(Project_Budget_Override__c))),
            OR(
                ISPICKVAL( ProjectScope_Status__c ,"Yellow"),
                ISPICKVAL( Participation_Status__c ,"Yellow"),
                ISPICKVAL( Project_Budget_Override__c,"Yellow"),
                Project_Schedule_Status__c = "Yellow"
            )
        ),
        "Yellow",
        IF(
            AND(
                ISBLANK(TEXT(Project_Budget_Override__c)),
                NOT(ISBLANK(TEXT(Project_Schedule_Override__c))),
                OR(
                    ISPICKVAL(ProjectScope_Status__c , "Yellow"),
                    ISPICKVAL( Participation_Status__c ,"Yellow"),
                    Project_Budget_Status__c = "Yellow",
                    ISPICKVAL(Project_Schedule_Override__c,"Yellow")
                )
            ),
            "Yellow",
            IF(
                AND(
                    ISBLANK(TEXT(Project_Schedule_Override__c)),
                    ISBLANK(TEXT(Project_Budget_Override__c)),
                    OR(
                        ISPICKVAL( ProjectScope_Status__c ,"Red"),
                        ISPICKVAL( Participation_Status__c ,"Red"),
                        Project_Budget_Status__c = "Red",
                        Project_Schedule_Status__c = "Red"
                    )
                ),
                "Red",
                IF(
                    AND(
                        ISBLANK(TEXT(Project_Schedule_Override__c)),
                        ISBLANK(TEXT(Project_Budget_Override__c)),
                        OR(
                            ISPICKVAL( ProjectScope_Status__c ,"Yellow"),
                            ISPICKVAL( Participation_Status__c ,"Yellow"),
                            Project_Budget_Status__c = "Yellow",
                            Project_Schedule_Status__c = "Yellow"
                        )
                    ),
                    "Yellow",
                    "Green"
                )
            )
        )
    )
)

A: Often with this sort of situation, the proper course of action is more of a paradigm shift; rather than fixing or improving this formula, it might be more prudent to ask if a Formula Field is the right tool for the job. It could make more sense to instead use a writable field and populate it from your domain layer. Domain layer here meaning your database hooks, which can be:

*

*Before Save Flow

*Apex Trigger (before events)

*Workflow Field Update

*Process Builder

Options 3 and 4 are pretty firmly recommended against at this point as those tools are on their way out. Option 2 is likely overkill, as it will give you a slight performance gain, but cost more in potential maintenance. In a complex org, that might be worthwhile, but in most, option 1 would be the best way to go about field updates from a domain layer.
Once you make the above paradigm shift, it allows you to break out the logic into smaller increments, and compile size of a formula will no longer be a limiting constraint.

A: There is dirty approach; Introduce dummy fields and create formula around the same. For example,
Project_Schedule_Override__c  --> Prj_Sch_Ov__c; the field is simple formula field  like TEXT(Project_Schedule_Override__c)
On the consolidate formula field use the abstract fields without the the PICKLIST, TEXT  functions. This may help.


text:
Q: If R is a PID, is it true that $R/\ker \phi$ is also a PID? I came across this solution that seeks to prove that any submodule of a cyclic module is cyclic.
Proof:
Let $M$ be a cyclic module, so that $\phi:R \rightarrow M$ is a surjection under $\phi(r)=r \cdot m$ for some fixed $m$ . Therefore $M$ is isomorphic to $R/ \ker \phi$, i.e. a quotient of $R$ by some ideal. Further, any submodule of $M$ is isomorphic to an ideal of $R/ \ker \phi$. Since $R/ \ker \phi$ is a PID also, any submodule of it is generated by one element. Hence any submodule $N \subset M$ is cyclic.
My question is:
How to prove that $R/\ker \phi$ is also a PID?

A: As pointed out in the comments, $R/I$ may not be a domain, however:
Let $I$ be any ideal of the principal ideal domain $R$.  Let $\mathscr J$ be an ideal of $R/I$, let $\pi:R \to R/I$ be the canonical projection, viz. $\pi(r) = r + I$ for $r \in R$, and let $J = \pi^{-1} (\mathscr J)$.  Then I claim that $J$ is an ideal of $R$ and $I \subset J$.  The second assertion is pretty obvious:  any $s \in I$ maps to $\bar 0 = 0 + I = I$ in $R/I$, and since $\bar 0 \in \mathscr J$, the set $\pi^{-1}(\bar 0) \subset J$ contains $s$; thus $I \subset J$.  As for the first, it is easy to see that $J$ is an ideal of $R$, straight from the definitons:  if $a, b \in J$, then $\pi(a - b) = \pi(a) - \pi(b) \in \mathscr J$ since $\pi(a), \pi(b) \in \mathscr J$;  thus $a - b \in \pi^{-1}(\mathscr J) = J$; if $r \in R$, then $\pi(ra) = \pi(r) \pi(a) \in \mathscr J$, an ideal of $R/I$; this implies of course that $ra \in J$.  Bearing these facts in mind we note that $J = (j)$ for some $j \in R$ since $R$ is a PID.  Then any $l \in J = \pi^{-1}(\mathscr J)$ is of the form $pj$ for some $p \in R$.  Thus $\pi(l) = \pi(pj) = \pi(p) \pi(j) = \bar p \bar j$; this shows that $\mathscr J = (\bar j) = (j + I)$; it follows that $R/I$ is a principal ideal ring, though not in general a domain. QED.

A: Hint: let $I$ be an ideal in $R/\ker(\phi)$. What can you say about its preimage $J=\pi^{-1}(I)$ under the canonical projection $\pi:R\to R/\ker(\phi)$?

 It's an ideal, hence $J=aR$ for some $a\in R$ since $R$ is a PID, and $\pi(a)$ is a generator of $I$.


text:
Q: Fixed menu with title div disappearing on scrolling I wish to combine the scripts of this template (I'm revising)
https://codepen.io/lydiawawa/pen/gEPpwX
to carry the effect from this example:
https://codepen.io/jamesbarnett/pen/JwFuy
The javascript I need to revise is as of the following:
/* JavaScript from: http://jqueryfordesigners.com/fixed-
   floating-elements/ */

$(function () {
var sidebar = $('.sidebar');
var top = sidebar.offset().top - parseFloat(sidebar.css('margin-top'));

$(window).scroll(function (event) {
  var y = $(this).scrollTop();
  if (y >= top) {
    sidebar.addClass('fixed');
  } else {
    sidebar.removeClass('fixed');
  }
});
});

Could anyone help me to revise the script to achieve the effects?
Thank you!

A: You've already set the position of nav as fixed by default which won't give you the desired result. You should set its position as static by default, and change the value after the document has reached a certain point by scrolling.
As I mentioned earlier, that script in the actual OP is doing the right job. The only thing I've done is to copy/paste that script to your example ( and some tiny CSS changes ).
check out this revised version at codePen


text:
Q: .Net MVC 3 403.14 error I'm creating an asp.net MVC3 demo application. I have attached the application with this thread. I'm facing a HTTP Error 403.14 - Forbidden issue when trying to run the application. The issue occurs only in a specific scenario. i.e. in the RegisterRoutes method in the global.asax
has only the below code then the issue occurs.
 routes.MapRoute(
                "Process1", // Route name
                "Process/List" // URL with parameters
            );

If we have the above code with default route the application works fine without any issues. The issue occurs when i have this particular code alone in the register routes method.
I tried the solutions given in this link but it did not work.
I assume the issue with that code. If yes then please let me know what causes the issue. I use windows 8.1 & the iis is 8.5.
The code can be found here

A: You have removed the default route and defined the following route:
routes.MapRoute(
    "Process1", // Route name
    "Process/List" // URL with parameters
);

In this declaration it is not clear which controller and which action should be
executed. You should explicitly state them:
routes.MapRoute(
    "Process1", // Route name
    "Process/List", // URL with parameters
    new { controller = "MyController", action = "MyAction" }
);

and then make sure that you are making the request to the proper url that you have defined:
http://localhost:1619/Process/List

because you don't have any route configured that is capable of handling the http://localhost:1619/ request that you seem to have made in your screenshot.
Of course having such route is completely constraining. The only controller action you could ever have in your MVC application is the one defined as such in the route config. This is fine in a SPA application where you have a single entry point serving the SPA and a separate ASP.NET Web API but in a real ASP.NET MVC application with multiple controllers and actions it is not going to work. So you probably want to keep the default route in this case and do not experiment in this area.

A: You must have a default root in your global.asax file to make it work. add one default and then you can add this route.