text:
Q: keep express app running on Linux cloud server I am pretty new to node/express. In the past I've used Django and apache. Recently I developed an express app and it works great when I manually run it and test it. I've done research on how to keep a node app with mongo db up and running after logging out of the linux server and there seems to be a lot of different answers. Is there a single ideal agreed upon way of doing it?

A: You can use tools like pm2 to keep node process running


text:
Q: If integrals are the same over every measurable set, then two functions are equal a.e. Let $(\Omega,\mathscr{F},P)$ be a probability space and $f,g(\Omega,\mathscr{F})\rightarrow [0,\infty]$ be measurable functions.
If $\int_E f dP=\int_E g dP$ for every $E$, how do I prove that $f=g$ $P$-a.e.?
If $f,g$ do not assume the value $\infty$, this is obvious by considering $\int_E f-gdP =0$. However, if this is not the case, since $f-g$ may not be defined, usual argument cannot be applied.

A: Let $q,t$ be nonnegative rationals such that $t<q$.
Note that $$qP(f>q,g\leq t)=\int q\chi_{f>q,g\leq t} dP \leq \int f \chi_{f>q,g\leq t}= \int g \chi_{f>q,g\leq t} \leq \int t\chi_{f>q,g\leq t} = tP(f>q,g\leq t)$$.
Hence, it must be $P(f>q,g\leq t)=0$. (Note that finiteness of $P$ is used here)
This means that $P(f>g)=0$, and analogously we have $P(g>f)=0$. Hence, $P(f=g)=1$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: is CocoaPods "pod install" working How can I check if "pod install" command of CocoaPods is actually downloading pods or not?
It seems doing nothing, it's about 10 minutes it's status is :
Analysing Dependencies

A: pod --verbose install  appears the be the command that will show you more.
This is a list of the options for the pod command
Options:

    --silent     Show nothing
    --version    Show the version of CocoaPods
    --no-color   Show output without color
    --verbose    Show more debugging information
    --help       Show help banner of specified command

A: It is a verbose command so it tells you each time it's doing something, download Bolts, installing Bolts, etc...
Have you made sure your cocoa pods install is up to date.
gem update cocoapods

from the commend line.
If that doesn't work... what's in your Podfile?

A:
How can I check if "pod install" command of CocoaPods is actually downloading pods or not

Use the Activity Monitor to check whether the Terminal is receiving data.
But when it show Analysing Dependencies, it actually do nothing about downloading. All you can do is waiting.


text: Q: What is a best practice for the design of an ASP.NET Core Web API Hello I'm building a RESTful API for the backend of a web application and have a quick question about design best practices. Is it bad practice to have more than one model associated with a controller? For instance, I have a model that represents the table I'm querying in my database and then another model (Created through linq queries such as joins, selects, etc.) that I'm using which is the one that I want to serve to the client. Therefore, if I follow this method I will always have one model that represents the table I am querying from and then another model that is the object that I actually want to expose through the API, is this a bad idea? Is there a better way to organize this? Any suggestions or assistance is greatly appreciated.


text:
Q: jQuery UI + ASP.NET: Make Modal Popup Load After AJAX is Ready I was hoping for a little help. I am currently using some of the jQueryUI widgets in an ASP.Net Web App. I have successfully got everything working. Basically, I have a GridView on a page which contains some hidden fields in each row containing data. I also have a dialog div containing an update panel and a few Labels.
When a user clicks on an Image Button on the GridView, the jQuery is fired to show the jQueryUI dialog and code behind is used to fill the labels from the selected GridView row. Unfortunately, the AJAX communication takes quite a bit longer to update versus showing the dialog div.
The same question actually applies to the loading of an ASP page into a jQuery popup window also as I will need to eventually do this.
So my questions are:

*

*How can I make jQuery wait to execute until after the partial postback has returned with the AJAX information for the popup?

*Is the above method the right way to go?

*Is there a better way?

*Is there a way to speed up AJAX
communications to make it more
instantaneous?

Thanks in advance for your input.

A: without knowing exactly what you're doing (code wise), the best I can understand is that you want to trigger some behavior after the ajax call has completed, which is actually supported like so:
$.ajax({
  url: 'myurl.aspx',
  success: function(data) {
    //everything you want to happen after the ajax completes.
    //this can either be code, or a call to another function that loads your div
  }
});


text:
Q: How to delete data from list with check condition i have one list this list i have bind from webservices in webservice i have a one parameter in each list item the parameter is status . so i want  to check if status is 0 delete this particular item
here my code
List<boko_data_json> thedata = Newtonsoft.Json.JsonConvert.DeserializeObject<List<boko_data_json>>(json);
listname.ItemsSource = list.data;
foreach (var item in thedata)
{
   if(item.status == "0") {
       //How to DELETE THIS storage data from thedata List
   }
}

A: You can use List<T>.RemoveAll:
List<boko_data_json> thedata = Newtonsoft.Json.JsonConvert.DeserializeObject<List<boko_data_json>>(json);
theData.RemoveAll(n => n.status == "0");


text:
Q: SortBy in Ember.js not working on newly created Items I applied a sortBy on date(time) attribute like this,
cars = @store.all('car')
cars.filter (car) =>
   if car.get('name') == undefined
      @store.find('car', car.get('id')).then ->
      console.log('record found')
   else
      cars

cars.sortBy('messageAt','name').reverse()

It does work when I reload the page, but as soon as I get a new message in Ember data, it does appear in messages but at the bottom, which means sorting does not work.

A: I got the same error. As far as I understood the problem is in messageAt attribute which has date type. And sorting by date is a little buggy in new versions of emberData. I fixed it by adding new property with integer type which is being sorted perfectly. Here's the code
lastMessageTime: DS.attr('date'),
lastMessageTimeInMilliseconds: function () {
    var lastMessageTime = this.get('lastMessageTime');

    if (typeof lastMessageTime === 'string') {
      return (new Date(lastMessageTime)).getTime();
    } else {
      return lastMessageTime.getTime();
    }

}.property('lastMessageTime'),


text:
Q: Test for "at least 6 non-space characters" stopped a perfectly good edit from being done I tried to edit "SourceIndex#each is deprecated". How to rectify? to clean up the block of messages which were all folded together. So I indented each one by four characters to make it into a nice code block. But when I tried to save the edit I got the following error message:
Oops! Your edit couldn't be submitted because: Edits must be at least 6 non-space
characters; is there something else to improve in this post?

This edit of all spaces would have improved the post had I been allowed to make it. I think that edits like this that cleanup code should be allowed even if all blanks. Maybe if someone edits something and introduces a code block like this, it should get a free pass around this particular check?

A: Well, you could use the <pre> tag or the > markup for some of that log. That itself would take you above the threshold and do a clean job.
But I agree, some legit changes can definitely be with space characters only.
As written in comment on another answer:

"If we impart meaning to space characters, then we can't refuse an edit just because it contains only space characters."

A: There were at least six grammatical and formatting errors elsewhere in the text. If you'd fixed those you would have easily met the non-trivial-edit threshold.
update: Oh, and the title needed cleaning too.


text:
Q: Run Query as Community User We are using angular to display UI and Salesforce is being used to maintain database. We have a REST API class created which has the urlMapping. This class is used to find the records.
The API have few queries which have the where clause such that the data should display by filtering from logged in User's details.
We are using 'Customer Community Login' Custom profile and need to check the data by logging as Community User.
The issue is, I need to check if the queries are running smoothly and displaying the relevant data when logged in as Community User. How can I run the query as with logged in as Community User?

A: You have two options:

*

*Create a visualforce page which displays response.

*Easier- Use Salesforce Session Id of Community user for authentication, and test using any rest based tools like postman.


text:
Q: Convergence of the integral of step functions This is a question about the proof of Lemma A in §16 of the book Functional Analysis by F. Riesz and B. Sz.-Nagy.

Lemma A: For every sequence of step functions $\{\varphi_n\}$ which decreases to zero almost everywhere, the sequence of values of their integrals also tends to zero.

The proof starts, by covering the set $E_0$ of all discontinuities of the sequence, which is of measure zero, with a system of intervals $\Sigma_0$ of total length less than $\varepsilon$. Then it continues:

For the remaining points $\varphi_n(x) \to 0$.

Here is the question: how do we conclude that the points where the series does not converge are covered by $\Sigma_0$?
It is possible finish the proof by adding the points, where the sequence does not converge to $E_0$, but I assume the authors have a reason not to do so.
On the other hand, I think I have a counterexample: let the discontinuities of the step function $\varphi_n$ be at the points $x_{nk} = k2^{-n}$ for $k=1,\dots,2^{-n}-1$. Let the sequence be convergent except at the point $\xi=1/3$, for instance:
\begin{gather}
\phi_n(x) = \begin{cases}
 1 & x\in \bigl(\tfrac{k}{2^{n}},\tfrac{k+1}{2^{n}}\bigr]
\text{ where $k$ is such that } \tfrac{k}{2^{n}}<\tfrac13<\tfrac{k+1}{2^{n}}
\\
0 & \text{elsewhere}
\end{cases}
\end{gather}
Choose for $\Sigma_0$ the intervals $I_{nk} = (x_{nk}-\delta_{nk}, x_{nk}+\delta_{nk})$, where
\begin{gather}
\delta_{nk} = \min\left\{\varepsilon2^{-n}2^{-k}, \left|x_{nk}-\tfrac13\right|\right\}.
\end{gather}
Since for all indices $\delta_{nk}>0$, this set covers all discontinuities of the sequence, has total length less than $\varepsilon$, and does not cover the point $\xi$. Or am I wrong here?


text:
Q: How can I wait to the close of the uninstall panel in windows 7 from batch file? I have simple batch file :
@echo off
call "c:\windows\system32\appwiz.cpl"
echo "Done"

On Windows XP, this batch launche the uninstall panel of windows, and block the execution until the use close the panel.
The same batch on Windows 7 doesn't blocks anymore, the echo is displayed immediatly.
How can I make the script blocks again on 7 ?
Thanks.


text:
Q: How is the "Memory usage" value computed that is shown when I login to Ubuntu 11.10? When I login to my Ubuntu 11.10 box, several values are displayed by default. For example:
Welcome to Ubuntu 11.10 (GNU/Linux 3.0.0-17-virtual x86_64)

 * Documentation:  https://help.ubuntu.com/

  System information as of Thu Apr  5 20:35:07 UTC 2012

  System load:  0.01              Processes:           56
  Usage of /:   15.5% of 7.87GB   Users logged in:     0
  Memory usage: 26%               IP address for eth0: XX.XXX.XX.XXX
  Swap usage:   0%

  Graph this data and manage this system at https://landscape.canonical.com/
Get cloud support with Ubuntu Advantage Cloud Guest
  http://www.ubuntu.com/business/services/cloud

I would like to know how the "Memory usage" value is calculated, so I can write a shell script to collect this and graph it over time.
Thanks!

A: When you login motd runs all of the files in /etc/update-motd.d. The output you're looking for comes from 50-landscape-sysinfo which is a symlink to /usr/share/landscape/landscape-sysinfo.wrapper.
This is just a short script though:
#!/bin/sh
cores=$(grep -c ^processor /proc/cpuinfo 2>/dev/null)
[ "$cores" -eq "0" ] && cores=1
threshold="${cores:-1}.0"
if [ $(echo "`cut -f1 -d ' ' /proc/loadavg` < $threshold" | bc) -eq 1 ]; then
    echo
    echo -n "  System information as of "
    /bin/date
    echo
    /usr/bin/landscape-sysinfo
else
    echo
    echo " System information disabled due to load higher than $threshold"
fi

Which indicates it comes from landscape-sysinfo. That output is just STDOUT for that utility. Landscape is all part of a Canonical system monitoring service. Find more information here:

*

*http://www.canonical.com/enterprise-services/ubuntu-advantage/landscape
If this isn't good enough Nagious is a more advanced but free networking monitoring tool that can monitor any number of machines. Cacti is a graphing web-frontend to RRDtool which is individual monitoring for a system.


text:
Q: Cannot access element in Javascript array I'm trying to do Inventory checking with using ajax post method and return with some array value. My response is okay, but I cannot access the array value of my response. I'm using response[0] and response[1]["OptionKey"] but it doesn't show anything.
response
[6,{"OptionKey":"215,221,224"}]

javascript
function InventoryChecking(LineOptionData) {
    var ItemID = $("#tiItemID").val();
    var OptVal = LineOptionData;

    $.ajax({
        type: 'POST',
        enctype: 'multipart/form-data',
        url: '<?= site_url() ?>item/InventoryChecking',
        data: "ItemID=" + ItemID + "&OptVal=" + OptVal + "&From=" + From,
        success: function (response) {
            console.log(response);
            if (From === "mytray") {
                $("#ItemBalance").text(response[0]);
            } else {
                $("#ItemBalance").text(response);
            }
            qty = $("#quantity").val();

            if (From === "mytray" && response[0] - qty === -qty && BaseLineOptionData === response[1]["OptionKey"]) {
                $("#btnAddToTray").attr("disabled", false);
            } else if ((response - qty) < 0) {
                // if( (response-qty)<0 ) {
                if (response <= 0) {
                    $("#ItemBalance").text(0); //Show 0 instead of negative
                }
                if (ItemStockCheck == 0) {
                    $("#btnAddToTray").attr("disabled", true);
                } else {
                    $("#btnAddToTray").attr("disabled", false);
                }
            } else {
                $("#btnAddToTray").attr("disabled", false);
            }
        }
    });
}

PHP to respond
if ($From === "mytray") {
   $array = [$reserved,$CombineOptID];
   echo json_encode($array);
}

A: Based on jwatts1980 comment, my response is in string. To fix this I need to change my response to Javascript object.
var obj = JSON.parse(response);


text:
Q: How to display different contents types(twitter, imges, blog etc.) in Viewslide show in Drupal? I am trying to display different content types on Drupal as views slideshow, including twitter, images, and blogs. Currently they are all saved in a field (unlimited value fields). I am going to extract these values to nodes as views only accepts node type values. I am wondering what is the best way to do it? I am new to drupal and can think of following ideas:
1. Use one node type, and create a display mode for this node type with customized codes
2. A separate node type for different content types, and each node type with some display mode
3. A minipanel for each node type,is it possible to display it in view slideshow?
4. some code to get data directly from fields, and export to views?
5. Or I use Colorbox and completely forget about View Slideshow?
Please help. Thanks.

A: You must set all the content types you want to pull in the query in the "edit" form of the view. It is not possible using only the one-step setup, you must choose "continue & edit" and then add different content types to your slideshow view.


text:
Q: Components of the vector product consider a parallelogram $ABCD$ with $A(3,-2,-1)$, $B(2,1,3)$ and $C(0,4,1)$
find the coordinates of $D$ and calculate the area of this parallelogram

A: a parallelogram can be divided into two triangles of equal area by a diagonal,that is if you find area of triangle ABC and then multiply it by two, you will get area of parallelogram.
area of triangle is half of product of two sides and angle between them, in your case area of triangle is 1/2{(AB)(BC)sin*} where * is the angle between A and B, and you know that (AB)(BC)sin* = ABxBC(cross product), twice of area of this triangle is area of your parallelogram,hence area of parallelogram becomes(ABxBC).solve ABxBC and get the answer.

A: $$\vec{OD}=\vec{OA}+\vec{AB}+\vec{AC}.$$
For the area, you know (I hope) that the altitude is given by $$Alt=\left\|\vec{AB}-\frac{\left<\vec{AB},\vec{AC}\right>}{\|\vec{AC}\|^2}\right\|.$$
I let you conclude.

A: $$\quad{\text{Area=}}\overrightarrow{AB}\times \overrightarrow{BC}$$
$$\overrightarrow{AB}+\overrightarrow{BC}+\overrightarrow{DC}+\overrightarrow{AD}=0$$

A: Find the vectors C-B = (0-2 ; 4-1 ; 1-3) =(-2 ; 3 ; -2) and  A-B = (3-2 ; -2 -1 ; -1 -3)= (1 ; -3 ; -4)
Now you can do the cross product between C-B  and A-B and the results is the area of the parallelogram  (because the parrallelogram is two triangles. The area of a triangle is 0.5 for the product of two sides for the sin of the angle between those two sides that is the cross product). I remember you that you must find the magnitude of the vector getted from the cross product for find the area.  In this way you do not need to calculate the coordinate D


text:
Q: Pass parameter to javascript function in Go template I have the following in my Go's template.
<button type="submit" class="validate_button" onclick="validate({{.Quiz.ID}})">Validate</button>

This is not working and I am getting this Javascript error :
"Property assignment expected."

This works perfectly of course :
<button type="submit" class="validate_button" onclick="validate(1234)">Validate</button>

Whats the right syntax here?

Note :

I am using VS Code. The same is telling me there is an error but I can compile just fine. The thing is once I ran the app there is no "button" on the page. It simply disappears. It works correctly when I hardcode a value though.
Note 2 :
This is the ouput of executing my template :
2020/02/13 09:52:49 template: execute.html:38:79: executing "execute.html" at <.Quiz.ID>: can't evaluate field Quiz in type models.Question

This is my template :
<!doctype html>

    <meta charset="utf-8">
    <title>Linux Quiz</title>
    <meta name="description" content="Linux Quiz">
    <meta name="author" content="Matias Barrios">
    <link rel="stylesheet" href="static/executeQuizz/style.css">
    <link rel="stylesheet" href="static/style.css">
    <link rel="stylesheet" href="static/bootstrap/css/bootstrap.css">

        Home

Logout : {{ .User.Name }}

        Contact
        About

 {{ .Quiz.ID }}

 {{ .Quiz.Description }}

   {{range $q := .Quiz.Questions}}

{{ $q.Question }}

        {{ $mode := $q.Mode }} {{ if eq $mode "single" }}
            {{range $o := $q.Options}}
            <input type="radio" id="{{ $q.ID }}" name="{{ $q.ID }}" value="{{$o}}">
            {{$o}}

            {{end}}
        {{ end}}

        <button type="submit" class="validate_button" onclick="validate({{.Quiz.ID}})">Validate</button>

   {{ end }}

And this is the execution of the template :
func executeQuizzHanlder(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/execute" && r.Method != "GET" {
        errorHandler(w, r, http.StatusNotFound)
        return
    }
    claims := getClaims(w, r)
    u := models.User{
        Name: claims.Username,
    }
    keys, ok := r.URL.Query()["quizz"]
    if !ok || len(keys) < 1 || len(keys[0]) < 1 {
        errorHandler(w, r, http.StatusNotFound)
        return
    }
    quizz, err := quizzes.GetQuizzByID(keys[0])
    if err != nil {
        errorHandler(w, r, http.StatusNotFound)
        return
    }
    quizz.ID = keys[0]
    envelope := models.ExecuteQuizzEnvelope{
        User: u,
        Quiz: quizz,
    }

    err = views.ViewExecuteQuizz.Execute(w, &envelope)
    log.Println(err.Error())
}

And this is my models :
package models

// Question :
type Question struct {
    ID       string   `json:"id"`
    Mode     string   `json:"mode"`
    Question string   `json:"question"`
    Options  []string `json:"options"`
    Answers  []string `json:"answers"`
}

// Quiz :
type Quiz struct {
    ID          string     `json:"id"`
    Description string     `json:"description"`
    Author      string     `json:"author"`
    Questions   []Question `json:"questions"`
    Completed   bool       `json:"-"`
}

// ExecuteQuizzEnvelope :
type ExecuteQuizzEnvelope struct {
    User User
    Quiz Quiz
}

A: Thanks to everybody for replying. As @mkopriva stated, within a range the . is set to the iteration element. I initially thought that this syntax...
{{range $o := $q.Options}}

would avoid that since I am naming my iteration variable o, but I was wrong in my assumption.
So that was the problem in this case.


text:
Q: Testing for contents of an NSArray without risking range error I'm foolishly saying:
if ([imageCache objectAtIndex:index]) {

Problem is, on my first time through this, I haven't put ANYTHING in my NSMutableArray *imageCache, and this croaks with a range error.
How can I ask an NSMutableArray whether it has anything for a particular index?

A: The NSArray cluster class cannot store nil. So I think it is sufficient to simply check the bounds:
NSUInteger index = xyz;
if (index < [imageCache count]) {
    id myObject = [imageCache objectAtIndex:index];
}

A: What I find really useful is having a safeObjectAtIndex: method. This will do the check for you and will return nil if the index is out of range.
Just create a new category on NSArray and include the following methods:
- (id)safeObjectAtIndex:(NSUInteger)index;
{
    return ([self arrayContainsIndex:index] ? [self objectAtIndex:index] : nil);
}

- (BOOL)arrayContainsIndex:(NSUInteger)index;
{
    return NSLocationInRange(index, NSMakeRange(0, [self count]));
}

A: if (index < [imageCache count])
   ...

A: This code answers your question.  Unlike the accepted answer, this code handles passing in a negative index value.
if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
    // Index does not exist
} else {
    // Index exists
}

A: [imageCache count] will return the number of items in your array. Take it from there :-)

A: Check the number of items in the array first with [imageCache count].  Don't try to ask for anything with an index greater than that result.


text:
Q: Can't run CTX_DDL.CREATE_STOPLIST through EXECUTE IMMEDIATE Code below works properly:
BEGIN
    CTX_DDL.CREATE_STOPLIST('MY_STOPLIST', 'BASIC_STOPLIST');
END;
/

However, when trying to run it through EXECUTE IMMEDIATE:
BEGIN
    EXECUTE IMMEDIATE 'CTX_DDL.CREATE_STOPLIST(''MY_STOPLIST'', ''BASIC_STOPLIST'');';
END;
/

I get the error
ORA-00900: invalid SQL statement
ORA-06512: at line 2
00900. 00000 -  "invalid SQL statement"
*Cause:
*Action:

FIXED (thanks @William Robertson):
BEGIN
    EXECUTE IMMEDIATE 'BEGIN CTX_DDL.CREATE_STOPLIST(''MY_STOPLIST'', ''BASIC_STOPLIST''); END;';
END;
/

NOTE: I really need to run it using EXECUTE IMMEDIATE.


text:
Q: Progress bar with indeterminate mode on a button click doesn't work I am using netbeans and this is the button click function. I want the progress bar to run as soon as I click on the button. The mode will be indeterminate because I am calling a class WriteToFile and it does the work for minutes in background and doesn't return any value.
private void createFileButtonActionPerformed(java.awt.event.ActionEvent evt)
{
    String str = (String) selectTypeComboBox.getSelectedItem();
    createFileButton.setEnabled(false);// Prevent more button presses
    String filepaths = fileChooserWindow.getSelectedFile().getAbsolutePath();
    String selectType =(String) selectTypeComboBox.getSelectedItem();
    WriteToFile writeOBJ;
    writeOBJ = new WriteToFile(filepaths,start,selectType);
    try
    {
        writeOBJ.selectType();
    }
    catch (SQLException | IOException  | RuntimeException ex)
    {
        System.exit(0);
    }
}

A: Got this to work:
    jProgressBar1.setVisible(true);
    jProgressBar1.setIndeterminate(true);
    Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
    executor.execute(new Runnable(){
        @Override
        public void run(){
       String str = (String) selectTypeComboBox.getSelectedItem();
       createFileButton.setEnabled(false);// Prevent more button presses
       String filepaths = fileChooserWindow.getSelectedFile().getAbsolutePath();
       String selectType =(String) selectTypeComboBox.getSelectedItem();
       WriteToFile writeOBJ;
       writeOBJ = new WriteToFile(filepaths,start,selectType);
      try
      {
       writeOBJ.selectType();
      }
      catch (SQLException | IOException  | RuntimeException ex)
      {
       System.exit(0);
      }
     jProgressBar1.setVisible(false);
   }


text:
Q: MEMS microphone for insect sound recording I am working on a project to record the sound of insects in stored grains and I am initially using a MEMS I2S breakout microphone from Adafruit but it look like the sound recording is not good or accurate enough. The main consideration for the microphone device is being low cost and sturdy but also better accuracy. Your suggestions are greatly appreciated.
Sincerely,
A PhD student on insect acoustic sensor


text:
Q: Unable to read the files from shared folder I am trying to access files from the shared folder(ftp location)  in Asp.net application. It is working fine  from visual studio. When i deploy same in IIS 7 , i am getting the following error
"Logon failure: the user has not been granted the requested logon type at this computer."
Stack Trace:

[IOException: Logon failure: the user has not been granted the
  requested logon type at this computer. ]
  System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  +9723522    System.IO.FileSystemEnumerableIterator1.CommonInit() +245    System.IO.FileSystemEnumerableIterator1..ctor(String path, String
  originalUserPath, String searchPattern, SearchOption searchOption,
  SearchResultHandler`1 resultHandler) +556
  System.IO.DirectoryInfo.InternalGetFiles(String searchPattern,
  SearchOption searchOption) +64    System.IO.DirectoryInfo.GetFiles()
  +14

......
My application pool is running in NETWORKSERVICE mode
To which user in IIS i need to give the permission for accessing this folder? is it IUSER or NT AUTHORITY\NETWORK SERVICE ? How can i identify the current running user in IIS?

A: The reason the connection is refused it most likely a Group Policy which disallows access to that service by the user running the IIS service.
I would not want to give any of those system users permission to access a network resource. Other computers could potentially connect as well.
Instead - make your program authenticate with a guest account or another account which you create and give the appropriate permissions.
I would say that it would be a more secure approach.

A: You may be trying to log on interactively to a computer you can only access over a network, or vice versa.
Change your logon location. Try to log on either locally (interactively) or remotely (over the network), as appropriate. You may want to ask the person who administers computer security to change the security database so you can log on either locally or remotely.

A: To debug - look at Environment.UserName at the moment of exception. It will be either user that initiated request OR anonymous user.
To fix: if local files - granting permissions may be ok. If remote and using user's impersonated account - need to impersonate with another account that have permissions on remote machine as you can't use already impersonating account to access remote resource ("NTLM one hop").
Note: make sure you review security requirements when allowing access to files.


text:
Q: deleting even nodes from a doubly link list c++ I'm trying to delete the nodes that are even in a doubly linked list by recursion. The problem is that it deletes the nodes but still show garbage in the deleted nodes space.
This is the output:
Here is the original list: 2 -> 2 -> 23 -> 2 -> 78 -> 5 -> 2
This list contains 7 number of items
The Number of even numbers is: 5
The number of even nodes removed was: 5
The resulting list is... 23 -> 5
***************After the even numbers are removed I get this back, Are you getting the same problem?***************************************
Now backwards: 5 -> 27303024 -> 27302960 -> 23 -> 27302928 -> 0
This list contains 2 number of items
The sum of all data is: 28
int removeEven(node*& head) {
    // double pointer to use the address of pointer head
    node ** deleteNode = &head;
    //if is the end of the list stop
    if(head==NULL)
        return 0;
    //if is even
    if((*deleteNode) -> data %2==0)
    {
        node * helper = *deleteNode;
        *deleteNode = helper -> next;
        delete helper;

        return 1+ removeEven(helper -> next);
    }
    //but if is an odd number
    else if ((*deleteNode) -> data %2)
    {
        //traverse to the next node
        deleteNode = &(*deleteNode)->next;
        //calls itself so that we can start againg to check in the new node.
        return removeEven(head -> next);
    }
}

I was told that changing the function like this will help but Im getting a lot of errors please help

//Remove even numbers
node* recfunremoveEven(node *head,node *prevnode, int* count) //helper function for remove even nodes
{
    if(head==NULL)
        return NULL;
    if(head->data %2 == 0) //data is even
    {
        *count+=1;
        free(head);
        node* next = recfunremoveEven(head->next,head,&count); //recursive call
        if(prevnode)
        {
            prevnode->next = next;
            next->previous = prevnode;
        }
        return next;
    }
    return recfunremoveEven(head->next,&count);
}

int removeEven(node*& head)
{
    int count=0;
    recfunremoveEven(head,&count);
    return count;
}

When compiling I get the following errors:

g++ -g -std=c++11 -o proftest dlist.h dlist.cpp main.cpp supplied.o
dlist.cpp: In function 'node* recfunremoveEven(node*, node*, int*)':
dlist.cpp:30:53: error: cannot convert 'int**' to 'int*' for argument
  '3' to 'node* recfunremoveEven(node*, node*, int*)' node* next =
  recfunremoveEven(head->next,head,&count); //recursive call ^
dlist.cpp:38:42: error: cannot convert 'int**' to 'node*' for argument
  '2' to 'node* recfunremoveEven(node*, node*, int*)' return
  recfunremoveEven(head->next,&count); ^
dlist.cpp: In function 'int removeEven(node*&)': dlist.cpp:45:29:
  error: cannot convert 'int*' to 'node*' for argument '2' to 'node*
  recfunremoveEven(node*, node*, int*)' recfunremoveEven(head,&count);

This is the .h file in case someone need to see it
//doubly linked list
#include <iostream>
#include <cstring>
#include <cctype>
#include <cstdlib>

struct node
{
    int data;
    node * previous;
    node * next;
};

/* These functions are already written and can be called to test out your code */
void build(node * & head);  //supplied
void display(node * head);  //supplied
void destroy(node * &head); //supplied
//Recursively compute and return the number of nodes that contain even number
//in the doubly linked list
int countEven(node *head);
//Recursively remove all the nodes that contain even number in the doubly linked list
//and return the number of nodes removed
int removeEven(node*& head);

A: After free(head), you're not allowed to dereference head, but you do.
You've also added some &s where you shouldn't (when recursing) and you left out a parameter on a couple of function calls.
But I think you're overcomplicating matters by passing around the "previous" node.
There are three cases to handle:

*

*The list is empty,

*The first node is odd,

*The first node is even.

The first case is trivial.
The second and third are very similar:

*

*Remove the even nodes recursively from the rest of the list.

*Adjust the previous pointer of the result of that removal.

*If head is even, delete it and increment the count.

*Return either head (if it's odd) or the result of the recursion (if head was even).

I believe this should do it (beware - untested):
node* removeEvenWorker(node* head, int* count)
{
    // Case 1
    if (head == nullptr)
    {
        *count = 0;
        return head;
    }

    // Recurse
    node* rest = removeEvenWorker(head->next, count);

    // Cases 2 & 3: Set up the first node.
    if (head->data % 2 != 0)
    {
        // Keep 'head'; link the recursive result to it.
        if (rest != nullptr)
        {
            rest->previous = head;
        }
        head->next = rest;
        return head;
    }
    else
    {
        // Discard 'head'
        if (rest != nullptr)
        {
            rest->previous = nullptr;
        }
        free(head);
        *count += 1;
        return rest;
    }

}

And calling it:
int removeEven(node*& head)
{
    int count = 0;
    head = removeEvenWorker(head, &count);
    return count;
}


text:
Q: google.api.client get null from file I'm trying to get some data from an existing file in google drive. The search correctly returns me some metadata, but when I try to get the date of the last modification of the file, I get null. I do not understand
This is a part of my code:
FileList result = null;
        try {
            result = mService.files().list()
                    .setQ("name = file.db and trashed = false")
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
 Log.d("Sync_drive", result);
 List<com.google.api.services.drive.model.File> files;
  if (result != null) {
  for (com.google.api.services.drive.model.File fileD : files) {
 dateModified = String.valueOf(fileD.getModifiedTime().getValue());
 gdid = fileD.getId();
 Log.d("Sync_drive", "id: " + gdid);
 }

result:
Sync_drive: {"files":[{"id":"1jX2w7F0Pjx28ug0lvjEIp4Kje6fw5JyF","kind":"drive#file","mimeType":"application/octet-stream","name":"file.db"}],"incompleteSearch":false,"kind":"drive#fileList"}

and
Process:  PID: 27987
                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'long com.google.api.client.util.DateTime.getValue()' on a null object reference

A: you first need to connect to google client:
here is an example :
protected synchronized void buildGoogleApiClient() {
        if (checkPlayServices()) {
                    .requestServerAuthCode(BuildConfig.GOOGLE_WEB_CLIENT_ID)
                    .requestEmail()
                    .build();
            // Build a GoogleApiClient with access to the Google Sign-In API and the
            // options specified by gso.
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(/*Api for google Drive*/)
                    .enableAutoManage(this, this)
                    .build();
            mGoogleApiClient.connect();

        }
    }

you also have to implement callback functions in the same activity:
, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
once client is connected ,you can get data from file


text:
Q: select2 set value to selected or placeholder I'm using select2, to create a dropdown menu with options 1-6
$('#main-search-dropdown').select2({
     placeholder: "Select a number"
});

The thing is, I have an API that handles what's being selected and submitted, then refresh the the page data. The dropdown also reloads, but in the code, the number is still selected, though, the dropdown box text is still the placeholder, not the value that's selected.
Any idea how I get this to display the selected text instead?

A: Try reinitializing the drop-down
$('#main-search-dropdown').select2();

A: Try trigger change
$('#main-search-dropdown').val(null).trigger('change');

Refer the documentation of select2:
select2


text:
Q: Extract separte values from url query string parameter I've gotten soooo lost on the approach. I'm using a tag manager to fire a custom script that extracts the full query string from a url...bare in mind, I deploy analytics tracking and am not a developer at all.
This works already to get the query string parameters
var queryString = decodeURIComponent(location.search.split("&").join(":")).substring(1);
return queryString;
Started to see urls with
"?utm_source=google&utm_medium=organic&utm_campaign=local&utm_content=editorial" coming through...
Would anyone be able to help me build on the code from above to extract only 1 value?
sorry for reaching out if it's been done, our implementation is bad for analytics so until we use proper campaign tracking, separating these are what I have to figure out :( #havemercy
thanks x300, seriously

A: Google will provide many solutions for this, but here's another quick ES5 example:
function getQueryParams() {
    var queryStringItems = decodeURIComponent(location.search).substring(1).split('&');
    var queryParams = {};
    for (var i = 0; i < queryStringItems.length; i++) {
        var component = queryStringItems[i];
        var keyValue = component.split('=');
        queryParams[keyValue[0]] = keyValue[1];
    }
    return queryParams;
}

Usage for printing the value for query parameter myQueryParam to the console would be the following:
var queryParams = getQueryParams();
console.log(queryParam['myQueryParam']);


text:
Q: ListView not returning selected item after filtering to previous activity I have a ListView populated by a String array. The user searches through edittext and it filters from the list, but when I click on one of the list items after filtering, the selected item is not returned but something else entirely. This was why it was going wrong:
Filter code:
et.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {

            adapter.getFilter().filter(cs);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }

List item click code:
lv.setOnItemClickListener(new OnItemClickListener() {

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

            String s = array[position];
            intent.putExtra(s);
            setResult(RESULT_OK, intent);
            finish();

        }
    });

Then I would read the string through OnActivityResult. The problem is that when the list is filtered, the list items are reduced. On selecting one of the items returns the position number of the reduced list, not the array. That's why the returned string is actually the string according to the array not according to the reduced list. How can I overcome this ?

A: problem is simple when you filtered the list and click on item you won't get the filtered item clicked because in lv.setOnItemClickListener(new OnItemClickListener() {...} you are passing position of original list not the filtered list.
Workaround is instead of getting from main list try getting it like this :
String a = array[parent.getItemAtPosition(position)];
or
String a = array[adapter.getItem(position)];
or
String a = array[(String) parent.getAdapter().getItem(position)];


text:
Q: Difference between flutter camera and flutter image_picker XFiles base64 encoding When i take a picture from the CameraController in camera package, and i take the same picture with the same image but with image_picker, and i encode every picture to base64 code, both codes are completely different. 3/4 (800) of their characteres are different. But, when i take two different pictures to the same object with just image_picker, and i compare the base64 codes of erveyone, they are almost the same, just with 6-7 different characteres. I tested visually showing the image files generated by image_picture and camera and they are basically the same.
That's a problem to me, because tesseract package recognize the images from image_picker, but not the images from camera, so, i need to know what is the root of the problem and if that have any solution.


text:
Q: How to get Maximum date from Django Model Query? Hello I have a Student model in Django which has following fields Id, Status, Marks, End Date.
When I am doing following query-
records = list(Students.objects.filter(status__in=["Active"])
    .values('id', 'marks', 'end_date')

Then this is the value that I am getting -
[{'id':'450', 'marks':'30', 'end_date':datetime.datetime(2021, 2, 3, 0, 0, tzinfo=<UTC>)},
 {'id':'450', 'marks':'60', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)},
 {'id':'450', 'marks':'80', 'end_date':None},
 {'id':'452', 'marks':'51', 'end_date':datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<UTC>)},
 {'id':'452', 'marks':'27', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}]

Now, my requirement is to get sum of all marks and max date for same Ids. For exa for above result set the output that I want is this -
[{'id':'450', 'marks':'170', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)},
 {'id':'452', 'marks':'78', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}]

I have tried the following code to get this output -
records = list(Students.objects.filter(status__in=["Active"])
    .values('id', 'end_date')
    .annotate(marks=Coalesce(Sum('marks'), 0),
            ))

Above code is giving me sum value but I am not able to get Max date. I tried adding end_date=Coalesce(Max('end_date__date'), 0) into annotate function but this is throwing this error -
AttributeError: 'str' object has no attribute 'tzinfo'

Anyone have idea how to get the Max date using annotate method or is there any other way of doing it?
Thanks in Advance :-)


text:
Q: Using the Google+ API with xCode/iOS (ARC) I want access to my Google+-Timeline for an iOS-App.
Following the Google-Documentation I imported the libGTlTouchStaticLib.a and library's header files.
After trying to build the project the following warning/error occured:
ld: warning: ignoring file ..../libGTLTouchStaticLib.a, file was built for archive which is not the architecture being linked (i386)

How do I build the Lib for xCode 4.3.2 architecture?

A: what does the command: file libGTLTouchStaticLib.a return? It sounds like it's compiled for ARM (the device) and you are running it in the simulator (i386). YOu might also want to try it on a device.


text:
Q: Xlib: extension "GLX" missing on display ":0". and OpenGL GLX extension not supported by display ':0' I am trying to use OpenGL on my Ubuntu 12.04 LTS.
I installed OpenGL with the following commands:
sudo apt-get install g++ cmake
sudo apt-get install freeglut3 freeglut3-dev
sudo apt-get install binutils-gold

I wrote a simple example in C++ and compiled it with g++ -lGL -lglut main.cpp -o test and then I tested it using ./test. A window opened but it was black and I didn't show anything.
So, I installed my nvidia driver using the following commands:
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install nvidia-current
sudo apt-get install nvidia-settings
sudo reboot

And now when I try to run again the program it gives me the 2 errors:
Xlib:  extension "GLX" missing on display ":0".
freeglut (./test): OpenGL GLX extension not supported by display ':0'

What could be the problem?
Also, here is the output of the lspci | grep VGA command:
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)
01:00.0 VGA compatible controller: NVIDIA Corporation GF108M [GeForce GT 525M] (rev a1)


text:
Q: mv: failed to preserve ownership I have two computers, both running Ubuntu (Ubuntu Server 10.04LTS on one, Ubuntu Desktop 10.10 on the other). I setup a Samba share on the Desktop. On the Server, I mounted the Samba share to /mnt/fileserver. This is the share:
[files]
    path = /home/fileserver/files
    guest ok = yes
    writeable = yes
    create mask = 0777
    directory mask = 0777

I have a script on the Server to backup my local web development files and put them on the Desktop. They are bzipped and then put into the Samba mount. When I try to move them into the Samba mount with the mv command, I get

mv: failed to preserve ownership for 'file': Permission denied

This is what my script looks like:
_DIR=$(date +%m-%d-%Y)

mkdir /mnt/fileserver/webserver_backups/$_DIR

tar vfcpj /tmp/www.tar.bz2 /var/www 2>> /var/log/backup.txt

mv /tmp/www.tar.bz2 /mnt/fileserver/webserver_backups/$_DIR/www.tar.bz2

All the files still seem to make it over okay, but I'm curious why I get this error.

A: Disregard the error.
Linux and Windows set file permissions in a radically different manner. The files get transferred just fine, but since the permission styles are incompatible, the permissions you originally had on the files don't transfer. Eg, what user owned the file, was it executable, could everyone read it or not..
Transferred files thus inherit the samba share's mount settings. If you mounted using Susan's credentials, she now owns the file.

A: I had this same error, but the file moved anyway. After the error check the source and destination to see if the file move was a success. I spent ages looking for a solution to the error not realizing I didn't have to resolve anything.


text:
Q: Retrieve SubString Auto Hot Key I have a list of strings I am trying to loop through within AutoHotkey, but within each loop I need to split each value into separate button presses:
 List := ["1111","1222","1498"]
 for key, value in List
      Send, SubStr(val,1,1)
      Send, SubStr(val,2,1)
      Send, SubStr(val,3,1)
      Send, SubStr(val,4,1)

The send isn't working and I suspect it is because my Send, SubStr code isn't written correctly. I would appreciate any advice/expertise thank you :)

A: I haven't tested this, but I'm guessing it might be because of legacy syntax. You should use expressions instead.
List := ["1111","1222","1498"]
for key, val in List
     Send % SubStr(val,1,1)
     Send % SubStr(val,2,1)
     Send % SubStr(val,3,1)
     Send % SubStr(val,4,1)

A: check for loop parse csv in autohotkey help


text:
Q: What Linux distros make upgrades easy? I am currently running Fedora 16 on my laptop, which is like 3 years EOL-ed. The reason that's the case is because it is not easy to upgrade to the current version in Fedora (at least v16) and it requires a complete reinstall.  So everything on it it old and doesn't work too well and I am just too lazy to move my data on an external medium and rebuild the OS. Ideally, I would like to upgrade by running a simple yum/apt-get command.
So my lesson learned from this experience is that I would like my next Linux distro to be idiotically easy to bring up-to-date, not because I am incompetent to deal with Linux but simply because I am lazy and want to remain so.  I also believe that, in this day and age, OSs should be very easily upgraded.
What Linux distros make upgrades easy to conform to this agenda?  I specifically do not want to have to move the data or the file system to a separate medium before performing the upgrade.
I also would like the distro to support KDE, which is my preferred interface.

A: I would recommend going with a rolling distribution. Meaning that there are no upgrades to higher version, you always have the newest version. Arch Linux is the one of the most popular rolling distros.
Obviously Arch is not the way to go if you insist on it being easy to use, as it requires considerably more effort to setup up the system. However Antergos and Manjaro which are both derivatives of Arch are easy to use. They are targeted towards the beginner and offer the same rolling release model. So there is no need to upgrade the distribution ever, just install updates and your operating system and software is up-to-date.
I just saw that you added the requirement KDE. Arch and both Antergos and Manjaro offer the most popular Desktop Environments (KDE, XFCE, GNOME, etc). Antergos even lets choose it during the installation process.

A: Debian is probably one of the easiest to upgrade - even across major releases.
From the Debian FAQ, Chapter 9, Keeping your Debian system up-to-date there is this statement,

A Debian goal is to provide a consistent upgrade path and a secure upgrade process. We always do our best to make upgrading to new releases a smooth procedure.

Opinion: I have just upgraded a number of systems from release 7 ("wheezy") to release 8 ("jessie"). For the most part it just worked. One had previously been upgraded from release 6 ("squeeze"). This is one of the major reasons I prefer to use Debian.
More information in answers to the Question Will Debian Wheezy (stable) automatically upgrade to Jessie once Jessie becomes the stable release
Update: since you have amended your Question to indicate a preference for KDE, you might like to review KDE's software in Debian and these Live install images

A: Most current distros have had easy upgrade capability for several years now. You might not be out of luck if you want to try upgrading your current distro. Have a look at this document:
https://fedoraproject.org/wiki/Upgrading_from_EOL_Fedora_using_yum#Fedora_16_-.3E_Fedora_17

A: I use OpenSuse and upgraded from version 11.3 (from 2009?) to version 13.1 (2014) with no problem at all. Burn CD, run CD, done in a couple of hours. Well... almost... there might have been the need to upgrade some applications, I do not remember now, but that is not really the OS' fault.
Yet, there are probably quite a few of them, as others say. A couple of places to look for them may be distrowatch.com and linux.com - Distributions.


text:
Q: Creating Dynamic Select Query in SqlAlchemy I have researched this topic and have decided just to ask here since I can't seem to find anything. I'll explain below:
Context: Flask Application with a form the client fills out and posts to the server. The form inputs are used to create a query and return data.
I am using SQLalchemy currently to construct the query from scratch. At this point, I have successfully connected to my existing Redshift database and can query properly but I cannot figure out how to dynamically construct a simple Select x, y, z statement based on the user's form inputs.
The main problem being that Query() can't take in a python list of columns. It seems you must specify each column like table.c.column1 which doesn't work well with a dynamic query since I don't know what columns I want until the user submits the form.
My 2 ideas so far:

*

*Loop through all column names and use Query.add_columns(table.c['colname'])

*Use select([col1, col2, ...]) instead of Query()

*Use load_columns() to load only specific columns in a table to query. Unfortunately seems to only work with model objects and not reflected tables unless I am mistaken

Both of these seem backwards to me as they do not really accomplish my goal effectively.

A: SQLAlchemy is quite flexible, so both 1 and 2 get the job done. If you've no need for ORM functionality, then perhaps #2 is more natural. If the user were to pass a list of column names such as
columns = request.args.getlist('columns')

you could then create your select() quite easily with a bunch of column() constructs:
stmt = select([column(c) for c in columns]).\
    select_from(some_table)

or if you have the table at hand, like you hint in the question:
stmt = select([table.c[c] for c in columns])

and then all that is left is to execute your statement:
results = db.session.execute(stmt).fetchall()


text:
Q: gdata youtube api 302 'The document has moved' I'm trying to get YouTube feeds with the python gdata library.
Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get:
RequestError: {'status': 302, 'body': '<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE>\n
302 Moved
\nThe document has moved\nhere.\r\n\r\n', 'reason': 'Redirect received, but redirects_remaining <= 0'}

302 to 'google.com'???
I've even tried to do something from the google online tutorials and I get the same error. What's going on?

A: Solved.
You need to add ssl=False to the YouTubeService object. Don't see nothing about it in the docs though.
yt = gdata.youtube.service.YouTubeService()
yt.ssl = False


text:
Q: Are HBITMAPs assigned via SetMenuItemInfo automatically deleted on DestroyMenu()? Using CreatePopupMenu() to create HMENU, adding text items to it via AppendMenu(), then loading an icon, using GetIconInfo() to get the bitmap, assigning that bitmap to the HMENU via SetMenuItemInfo().   Now I presume I need to keep that HBITMAP from GetIconInfo() valid so I can't delete it at this time.
The question is does DestroyMenu() delete the HBITMAP assigned to it, or do I need to loop through the menu and DeleteObject() for each item that has an assigned HBITMAP?  If I do have to do that, do I have to remove it via setting HBITMAP in the HMENU to NULL prior to DeleteObject() or the fact that after the loop I'll be calling DestroyMenu() enough?
TIA!!


text:
Q: How to pass parameters in Flutter ListView i want to pass list of title and description in my list view, i can pass in list view builder, but i don't how to pass in list view.
i want to pass entries array in ListView. without typing each entry i want to show everything in array on cards.
 Widget build(BuildContext context) {
 final List<String> entries= <String> ['Entry one','Entry Two','Entry Three','Entry one','Entry Two','Entry Three','Entry one','Entry Two','Entry Three','Entry one','Entry Two','Entry Three'];

    return Scaffold(
      appBar: AppBar(
        title: Text('title'),
      ),

      body: ListView(

  children: const <Widget>[
  Card(
      child: ListTile(
        leading: FlutterLogo(size: 40.0),
        title: Text('all entries one by one'),
        subtitle: Text(
          'subtitle'
        ),
        trailing: Icon(Icons.favorite),
        isThreeLine: true,
      ),
    ),
  ],
)
    );

  }

A: You can use ListView.builder() for this. Here is an example.
class TestPage extends StatelessWidget {
  final List<String> entries = <String>[
    'Entry one',
    'Entry Two',
    'Entry Three',
    'Entry one',
    'Entry Two',
    'Entry Three',
    'Entry one',
    'Entry Two',
    'Entry Three',
    'Entry one',
    'Entry Two',
    'Entry Three'
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('title'),
      ),
      body: Container(
        height: 500,
        child: ListView.builder(
          itemCount: entries.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: ListTile(
                leading: FlutterLogo(size: 40.0),
                title: Text(entries[index]),
                subtitle: Text('subtitle'),
                trailing: Icon(Icons.favorite),
                isThreeLine: true,
              ),
            );
          },
        ),
      ),
    );
  }
}

A: If you already have array of title and description using the ListView.builder() is the best option here. First make a class for your title and description:
class Info{
  String title;
  String description;
  Info(this.title, this.description);
}

Now create an array of this info class List<Info> _myInfo and populate it with your data. Now you can create your list view like this:
ListView.builder(
  itemCount: _myInfo.length,
  builder: (context, index) {
    return _createCard(index);
  }
);

Now you can separate your card creation here like this:
Widget _createCard(int index){
  return Card(
    child: ListTile(
      leading: FlutterLogo(size: 40.0),
      //here your title will be create from array for each new item
      title: Text(_myInfo[index].title),
      subtitle: Text(
        'subtitle'
      ),
      trailing: Icon(Icons.favorite),
      isThreeLine: true,
    ),
  ),
}

Code might contain syntax error feel free to ask if you face any problem


text:
Q: Having issue while running docker-compose up -d version: '3.0'
services:
db:
image: mysql
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: 1234
MYSQL_USER: wordpress
MYSQL_PASSWORD: 12345
wordpress1:
depends_on:
-db
image: wordpress:latest
restart: always
ports:
-"8080:80"
environment:
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_HOST: db:3306
volumes:
db_data:
Error as below-
ERROR: yaml.scanner.ScannerError: while scanning a simple key
in "./docker-compose.yml", line 21, column 3
could not find expected ':'
in "./docker-compose.yml", line 23, column 3
Can anyone please help me to resolve this issue? I am trying to resolve since past 1 hour but getting into errors one by one

A: The problem is probably in the definition of the wordpress1 service.
You need to add a space after the dash:
wordpress1:
  depends_on:
    - db

So instead of -db you need to have - db.
Edit:
The complete docker-compose.yml should probably look like this:
version: '3.0'

services:
  db:
    image: mysql
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 1234
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: 12345

  wordpress1:
    depends_on:
    - db
    image: wordpress:latest
    restart: always
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_HOST: db:3306

volumes:
  db_data:

A: From docker documentation, the exact code you want to run:
https://docs.docker.com/compose/wordpress/


text:
Q: Sharepoint 2010 "Failed to render field Created_x0020_Date, use default value instead" Our company recently upgraded from Sharepoint 2007 to 2010 and with the upgrade it managed to break a filter on one of our sites.
The site is mostly just a dressed up document library with a custom view and has a date filter (by year, month). After the upgrade it randomly generates an error of "Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator." along with a correleation ID. The logs generated on the sharepoint server state "Failed to render field Created_x0020_Date, use default value instead".
The problem does not appear to be with the query or with the returned results until it actually tries to display the web part. Somehow the created date is not getting set? The strange thing is it works intermittently. The web part loads correctly maybe 5% of the time.
Any ideas what could have changed from 2007 to 2010?

A: Was the "Created_x0020_Date" column a calculated column?  Was it modified in any way (such as the current date XSL hack)?
I've seen that sporadic error before and for my problem it was a time-out issue with a poor performing web part pulling from 3 different lists. We increased list throttling, and caching but it didn't help.  But if it's just a standard view of the library with no custom XSL in it, then it  isn't a code performance issue.
Can't you just create a new created column and copy the old data into the new column using Datasheet view in the browser?

A: We faced this same error both in a SharePoint 2010 and a SharePoint 2013 enviroment,
when executing an old report.
The cause was the farm XsltTransformTimeOut parameter.
We increased its value (default is 1 second) to 20 (our report lasted 10 seconds to run) and it got ok!
$farm = Get-SPFarm
$farm.XsltTransformTimeOut = 20
$farm.Update()

Hope it helps!

A: There whatsoever no difference between the Created Date column in SharePoint 2010 and SharePoint 2007.
The differences between the two are mainly new columns. After doing some digging I found this.

You can see the complete reference of the fields here

*

*SharePoint 2010 Document Library Column Reference

*SharePoint 2007 Document Library Column Reference

*SharePoint 2007 2010 Document Library Column Difference
Now, since we know pretty much nothing of your setup and how this is built we are left to chance a bit. But assuming that guessing a bit is alright I'd say you are either missing the data in the 'Created Date' field which is possible since the field isn't required (check the documents I've linked to). Did you verify that all documents got this value set?
This field (Created Date) use the TimeCreated property to check when the document was created. So if this column isn't filled with data that usually should mean that your documents hasn't been transfered to your new installation but the reference to the document is still there.

*

*http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.timecreated.aspx
Thats a bit of a chance but thats what I'd start somewhere around that.
Good luck.


text:
Q: Why does this ActionScript Flip cause a blur on my website? I'm using a flip mechanism to navigate through my site (flip file & demo). The problem is, once it's flipped the content been displayed good just like I want it, but there's some offset from the flipped (right) parts en the solid left part (visible when you look closely). Also the right part is now a little blurred (which is the disturbing part of my issue). This all caused by the flip (I think the rotationY is causing the problem).
When I click a button I do the following:
flip=new Flip(currentPage,nextPage,richting);
content.addChild(flip);
currentPage=nextPage;
nextPage = new MovieClip();

A: there is a fix for it, consider the following:
// store original matrix
var origMatrix:Matrix = box.transform.matrix;
// set initial position
box.rotationY = -180;
// start animation
TweenLite.to(box, 1, {rotationY:0, onComplete:cleanBlur})
// execute after animation complete
function cleanBlur():void {
    box.transform.matrix = origMatrix;
}

maybe you can find better results using other 3d library.
EDIT: sorry the "box" object, I was testing in flash, but box would be any of your pages to flip. Just apply the same logic.

A: Matteo at Flash & Math has an excellent solution for this. He actually found that when you bring an object into native 3D space it expands the object by one pixel in both the width and height. This can be counteracted by scaling your object back and then setting it's z to 0 which will scale it back up. Now the object is ready to play with without the blur.
http://www.flashandmath.com/flashcs4/blursol/index.html
adding: This fixes the scale issue, but not the blurriness. You will still need to use the matrix transformation fix posted above.


text:
Q: tensorflow results are weird. How to solve it? It has two inputs and one output.
Input: [Temperature, Humidity]
Output: [wattage]
I learned as follows
Even after 5 million rotations, it does not work properly.
Did I choose the wrong option?

var input_data = [
[-2.4,2.7,9,14.2,17.1,22.8,281,25.9,22.6,15.6,8.2,0.6],
[58,56,63,54,68,73,71,74,71,70,68,62]
];

var power_data = [239,224,189,189,179,192,243,317,224,190,189,202];

var reason_data = tf.tensor2d(input_data);
var result_data = tf.tensor(power_data);

var X = tf.input({ shape: [2] });
var Y = tf.layers.dense({ units: 1 }).apply(X);
var model = tf.model({ inputs: X, outputs: Y });
var compileParam = { optimizer: tf.train.adam(), loss: tf.losses.meanSquaredError }

model.compile(compileParam);

var fitParam = {
    epochs: 500000,
    callbacks: {
        onEpochEnd: function (epoch, logs) {
            console.log('epoch', epoch, logs, "RMSE --> ", Math.sqrt(logs.loss));
        }
    }
}
model.fit(reason_data, result_data, fitParam).then(function (result) {

    var final_result = model.predict(reason_data);
    final_result.print();
    model.save('file:///path/');
});

The following is the result for 5 million times.

It should be the same as power_data , but it failed.
What should I fix?

A: While there is rarely one simple reason to point to when a model doesn't perform the way you would expect, here are some options to consider:

*

*You don't have enough data points. Twelve is not nearly sufficient to get an accurate result.

*You need to normalize the data of the input tensors. Given that your two features [temperature and humidity] have different ranges, they need to be normalized to give them equal opportunity to influence the output. The following is a normalization function you could start with:
function normalize(tensor, min, max) {
  const result = tf.tidy(function() {
    // Find the minimum value contained in the Tensor.
    const MIN_VALUES = min || tf.min(tensor, 0);

    // Find the maximum value contained in the Tensor.
    const MAX_VALUES = max || tf.max(tensor, 0);

    // Now calculate subtract the MIN_VALUE from every value in the Tensor
    // And store the results in a new Tensor.
    const TENSOR_SUBTRACT_MIN_VALUE = tf.sub(tensor, MIN_VALUES);

    // Calculate the range size of possible values.
    const RANGE_SIZE = tf.sub(MAX_VALUES, MIN_VALUES);

    // Calculate the adjusted values divided by the range size as a new Tensor.
    const NORMALIZED_VALUES = tf.div(TENSOR_SUBTRACT_MIN_VALUE, RANGE_SIZE);

    // Return the important tensors.
    return {NORMALIZED_VALUES, MIN_VALUES, MAX_VALUES};
  });
  return result;
}

*You should try a different optimizer. Adam might be the best choice, but for a linear regression problem such as this, you should also consider Stochastic Gradient Descent (SGD).

Check out this sample code for an example that uses normalization and sgd. I ran your data points through the code (after making the changes to the tensors so they fit your data), and I was able to reduce the loss to less than 40. There is room for improvement, but that's where adding more data points comes in.


text:
Q: what is ORDER BY useful for when i do PARTITION BY i started to learn the PARTITION BY methode  with agregate functions but i dont understand why should i use ORDER BY for in this query .
i want to SUM the total amount of sales in $ on "standart paper " in each year
this is my code :
    SELECT standard_amt_usd,
   DATE_TRUNC('year', occurred_at) as year,
   SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
   ORDER BY occurred_at) AS running_total
   FROM orders ;

the answers i get are correct but i still dont understand why in need to ese ORDER BY in here and what will happen if i wont use it ?
thank for the help:)

A: Run this query:
SELECT standard_amt_usd,
       DATE_TRUNC('year', occurred_at) as year,
       SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
                                   ORDER BY occurred_at
                                  ) AS running_total,
       SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
                                  ) AS group_total
FROM orders ;

You will probably see the difference right away.  The ORDER BY says to do the summation "up to" this row.  Without the ORDER BY, the summation is the same on all rows with the same PARTITION BY key.

A: ORDER BY has mainly two rules:

*

*To actually define how another feature works. This is true when
using TOP, say, or within an OVER() partition function. It doesn't
require sorting to occur, it just says "this definition only makes
sense if we consider the rows in the result set to occur in a
particular order - here's the one I want to use"

*To dictate the sort order of the result set. This is true when it's
an ORDER BY clause on the outermost statement that is part of a
particular query - not in a subquery, a CTE, an OVER() paritition
function, etc.


text:
Q: Explain Process vs thread prioritization in Linux, simple term I found several documents in stackoverflow with complex explanation mostly i don't understand. In simple term what is difference  Process vs thread prioritization?

A: TL;DR - A simple answer is that there is no difference between a cgroup process and thread, but it is complex for multi-core systems due to migration.

The mechanics to set the thread priority versus the process priority is different from user space. Increase thread priority.  The accounting and scheduling are generally the same after the priority is set.
As a goal, the scheduling of process versus thread is equal.  Ie, there is no difference according to the goals.

In a simplifying move, Linux turns process scheduling into thread scheduling by treating a scheduled process as if it were single-threaded. If a process is multi-threaded with N threads, then N scheduling actions would be required to cover the threads. Threads within a multi-threaded process remain related in that they share resources such as memory address space. Linux threads are sometimes described as lightweight processes, with the lightweight underscoring the sharing of resources among the threads within a process. opensource.com

...but the hardware complicates this.  Technologies like Hyperthreading will make it more efficient to keep threads on the same core. The layout of L1, L2, TLB, etc shared among cores on hardware prefers that threads are kept on the same CPU islands.  This negates cache flushing and other effects.  cgroups was implemented to keep related processes together.  For instance auto-cgroup launched from the same TTY will share similar shared libraries and I/O and pipe from one process to another will benefit from data being in the cache when we move from the generating process to the consuming process.
Because threads have tighter coupling it is far less likely that they will migrate between cores independantly.  Processes that do not share a cgroup are more likely to migrate to an idle core, so it is possible that they may end up getting more CPU, due to the asymmetry of work performed on different cores due to access to hardware resources.  The configuration of 'server' versus 'desktop', or scheduling latency can also have an effect.  It is possible that power management might also come into play.  Ie, Does the code keep a core sleeping or wake it for process migration?  And of course, the particular kernel version will have an effect as well as these noted high level configuration options.
References

*

*A decade of wasted cores

*Linux fair scheduling

*Top-tier memory


text:
Q: Not seeing Plymouth graphical boot-up screen until end of boot process After reverting back from BURG to GNU GRUB2, I noticed that the purple Plymouth loading screen wasn't appearing until the very end of the boot-up process, when it flashed up for about a second.
Before this, the purple screen loaded with the Ubuntu logo and the dots at the bottom changing colour one by one.
Now, after selecting Ubuntu on the GRUB2 menu, I see a black screen for a long time (probably while Ubuntu is booting in the background), and then the purple screen shows up for a second and the dots change colour all at once. Then, it takes me to the log-in screen.
This is really bugging me, and I'd be grateful if anyone could help.
Thanks!
Ubuntu 14.04 LTS
Dual-booted alongside Windows 7
Toshiba Satellite C660-2EL

A: After a tiresome internet-searching session, I finally managed to find my answer here: https://askubuntu.com/a/79959/289337
Thanks for the replies though. (By the way, JohnnyEnglish's method didn't work for me).


text:
Q: What does "problem is bigger than any one city" mean?
But mayors and councilors can only do so much about a problem that is far bigger than any one city or town.

Does it mean the problem is the biggest problem and no city and town can deal with it? And mayors and councilors have done their best?

A: This indicates thsat the problem, whatever it is, affects many cities, perhaps an entire country or the whole world. Since it doesn't say what the problem is in this quote, there is no way to say more. It doesn't say this is the "biggest" problem -- there are many problems larger than any one city. It doesn't say that "mayors and councilors have done their best", or that they haven't. It does say that there is a limit to what such people can do, and implies that even their best will not solve the3 problem, whatever it is.  This might follow a statement that "mayors and councilors" have not taken important steps, or that they have done all that is possible, or something in between. It probably follows some sort of statement about what the "mayors and councilors" have or have not done. Again, without context, one cannot say more.


text:
Q: Significance of 0 error results I want to see how many people have COVID in a certain region (London) and I use a sample of 10 people out of 1000 (btw the sample size isn't an issue) and test them for COVID and find that none of them have COVID. What conclusions can I draw for this? Obviously I cannot say that no one in London has COVID and I cant use a margin of error from this. Are there any conclusions I can draw from my results? Is there anything else I can do?

A: This is a difficult problem, since you can't even get a standard error to create a confidence interval. One idea is to use Laplace's rule of succession where we add two artificial observations to our data. You say you observed ten people, none of whom had COVID. Then pretend that you observed two more, one who had COVID and one who did not. Then you have $1/12$ as COVID cases and can do the usual proportion testing and confidence intervals.
An alternative could be some kind of Bayesian method where you use an assumption or knowledge (such as the prevalence in Manchester) as your prior distribution.


text:
Q: How to manage publishing maven settings.xml with artifact repository, mirror and proxy details to CI servers? Is there an automated process I can rely on, as an organisation's artifact repository / proxy manager, to publish configuration updates to dependent continous integration servers and developers?
For instance, if for some reason, I have to create or move a repository / proxy URL, is there any way to update Jenkins or TeamCity or whichever CI servers are in use in my organisation?
(apart from sending emails to the server administrators, naturally)
At the moment I am carrying this out manually, so all CI servers and all developers need to edit their settings.xml files.
I imagine such integration would be easy if one organisation such as Atlassian created a CI server and repo proxy, but I don't think any organisation does, or is there another approach, based on file shares for instance?
I have seen one solution where the organisation bundled the settings.xml with the maven rpm package and rolled it out as an upgrade, but I'm hoping for something simpler.


text:
Q: How to smoothly move a UIView with the users finger on iOS in my app I have a UIImageView representing a chalk. The user can pick that up and drag it over the screen to draw with it.
I implemented that using touchesBegan, touchesMoved and touchesEnded. In touchesMoved I move the center of my UIImageView to the current touch location and draw a line with core graphics from the last to the current location.
This works well but the image view movement isn't very smooth and it also lags behind the touch. I already tried to use a UIPanGestureRecognizer (didn't recognize the gesture) and a UIScrollView in which I placed the chalk (didn't really figure out how to configure it so that it could be moved far enough in all directions).
Can you give me some hints how to improve the quality of my chalk movement?
Thanks!

A: The following tapGesture method method works smooth for me:
- (void)handlePan:(UIPanGestureRecognizer*)gesture{
View* view = (View*)gesture.view;

if (gesture.state == UIGestureRecognizerStateEnded){
    view.dragStartingPoint = CGPointZero;
    return;
}

CGPoint point = [gesture locationInView:gesture.view];

if (gesture.state == UIGestureRecognizerStateBegan){
    view.dragStartingPoint = point;
    view.dragStartingFrame = view.frame;

    return;
}

if (CGPointEqualToPoint(view.dragStartingPoint, CGPointZero))
    return;

CGFloat x = view.dragVerticallyOnly? view.frame.origin.x: view.dragStartingFrame.origin.x + point.x - view.dragStartingPoint.x;
CGFloat y = view.dragHorizontallyOnly? view.frame.origin.y: view.dragStartingFrame.origin.y + point.y - view.dragStartingPoint.y;

if (self.dragVerticallyOnly == NO){
    if (x < view.dragMinPoint.x){
        x = view.dragMinPoint.x;
    }
    else if (x  > self.dragMaxPoint.x){
        x = view.dragMaxPoint.x;
    }
}
if (self.dragHorizontallyOnly == NO){
    if (y < view.dragMinPoint.y){
        y = view.dragMinPoint.y;
    }
    else if (y  > self.dragMinPoint.y){
        y = view.dragMinPoint.y;
    }
}

CGFloat deltaX = x - view.frame.origin.x;
CGFloat deltaY = y - view.frame.origin.y;
if ((fabs(deltaX) <= 1.0 && fabs(deltaY) <= 1.0))
    return; // Ignore very small movements

[UIView animateWithDuration:0.1 animations:^{
    view.frame = CGRectMake(x, y, view.frame.size.width, view.frame.size.height);
}];

}
The most important points are:

*

*Make the movement with the animated option; (one tenth of a second seems to do the job well done).

*Avoid making movements when not necessary. Making some calculations will not make it slower, but making unnecessary movements might. However you cannot avoid to many movements otherwise it will not follow the user pan gesture.

Depending on how you want your view to behave, there can be more optimisations that you may want to make.
Remark: My method also takes into account boundaries and movement directions limits that you may define in case you need it. For instance, in my case I added a speed limit. If the user goes beyond a certain pan speed I just ignore further pan gestures and move the view (animated) where the user was pointing to, and at that speed. It may or not make sense in same cases. In mine, it did!
I hope I have been of some help!

A: Try reducing the size of the Chalk image u are using....
Edited: By size i meant the image file size.
It helped me when i faced similar issue.

A: look at this component : spuserresizableview
http://cocoacontrols.com/platforms/ios/controls/spuserresizableview
The source code is very simple and can help you to understand the view handling.

A: I rewrote how the movement is calculated and it is a little smoother now. Not perfect, but it's enough.


text:
Q: OCaml pattern match in ast.ml, the structure is below:
type beantype =
    | Bool
    | Int
    | TLr of fieldsrec
    | TId of ident
and fieldsrec = { fields : field list }
and field =
    | FIe of (ident * beantype)

in printer.ml, i use it like below:
let rec print_bean fmt = function
    | Bool -> put fmt "%s" "bool"
    | Int -> put fmt "%s" "int"
    | TLr f -> put fmt "%s" "{"; print_fieldsrec fmt f ; put fmt "%s" "}"
    | TId id -> put fmt "%s" id
and print_fieldsrec fmt = function
    | f :: fe -> print_field fmt f; put fmt "%s" "," ; print_fieldsrec fmt fe
and print_field fmt = function
    | FIe (id, beantype) -> put fmt "%s" id; put fmt "%s" ":"; print_bean fmt beantype

However it said the different pattern match in print_fieldsrec
Error: This pattern matches values of type 'a list
   but a pattern was expected which matches values of type
     Bean_ast.fieldsrec

how can i change the printer.ml?

A: You seem to be confused by the type fieldsrec = { fields : field list }. You should have followed Jeffrey's advice of using | Fields of field list instead.
fieldsrec is not a list, it is a record containing a list, so
print_fieldsrec fmt = function f :: fe -> ...

doesn't have the type its name suggests.
Also you forgot the base case for the recursive print_fieldsrec.


text:
Q: app name doesn't appear in permission request alert I am using UIImagePickerController to allow the user to pick images from the device.
When doing it the first time, I get a standard permission request alert, but the app name is missing..

I couldn't find any mention for this in the documentation.
 imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:imagePickerController animated:YES completion:nil];

Other permission request (like location services) are displaying the app name appropriately.

A: for some reason, bundle display name in info.plist was blank..
changed it back to $(PRODUCT_NAME) and issue is solved


text:
Q: Recommended utility for editing of GEOJSON files I have a geojson file with the boundaries and some very basic statistics (population) for all the counties in US. States are enumerated (1,2,...), not named.
I also have a csv file with a comprehensive demographic and health statistics for each county (county is a row, statistics are columns).
I would like to add these values from the csv file as properties, for the county.
Is there a good, open source tool you would recommend for doing this programmatically, and in bulk.
I was looking into Python's geojson.

A: It might be easiest to try using QGIS and dropping the geojson into it. Then do a join by attribute.
A side benefit of it being graphical is that you can browse/label the counties and then quite easily spot check your joined data.

A: Although it's not Python based, you should better use geojson-join package.
It works for JSON, CSV or DBF and it uses the command line. No need to code here except if you have a particular purpose I'm unaware.


text:
Q: Unix shell user input phone number I am trying to write a script so that it will check whether the user has entered a valid phone number and then check against a records.txt file.
I have the following code. However when I enter a phone number it does not recognize it.
I am also not sure how to implement a check against the text file?
echo "Enter a phone number as XXXXXXXX: "
read phoneNumber
while [ "$phoneNumber" != [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]
    do
    echo "Please enter a phone number as XXXXXXXX: "
    read phoneNumber
done
echo $$phoneNumber
pause

A: You need to include start and end anchors in your regex if you want to validate phone numbers of exactly 8 digits or otherwise, it would accept the numbers which has more than 8 digits.
#!/bin/bash
echo "Enter a phone number as XXXXXXXX: "
read phoneNumber
pat="^[0-9]{8}$"
while [[ ! $phoneNumber =~ $pat ]]
    do
    echo "Please enter a phone number as XXXXXXXX: "
    read phoneNumber
done
echo $phoneNumber

A: Put your regex in a variable like so: pat="[0-9]{8}".
The phrase {8} means 8 repetitions of the previous character set.
In this case, the "previous character set" is anything in the range [0-9].
Then write your while condition using the two variables you've created:
while [[ ! $phoneNumber =~ $pat ]]

Notice the added ! to the start, to negate the expression in brackets.
When evaluating regular expressions like this, we use double square brackets [[ expression ]] as well as =~ to test matching.


text:
Q: Moving Files to Folders with Powershell and RegEx I wrote the following script to batch process the files in to folders based on the title of the magazine (everything before the first hyphen):
magazine title - year-month.pdf eg National Geographic - 2017-07.pdf
After running the script the magazine(s) are moved from the parent folder to a new sub folder, in this case "National Geographic Magazine".
Three related questions:

*

*The '_Orphans' folder (line 38) is created even if there are no 'orphans'
to file in to it for later manual processing. How do I make the folder
creation conditional?

*Duplicate files create an error message during processing. Not a big deal as the script continues to run, but I'd like to handle duplicates the same way 'orphans' are handled, with a new "_Duplicates" folder/move.

*How do I comment multiple lines without the # at the beginning of each
line (as at the top of the script, for example). There must be a more elegant
way to handle comments/documentation...?
Bonus Question:
If you're really bored waiting for that multi-TB file copy
you're watching progress like an hour glass, could anyone help with the code
for an array of delimiters (wrong term/name probably) as shown on line 10? I'd
like to be able to specify more than just the hard-coded hyphen I used in my
regex match (line 26, which took me the better part of a day to get working).
$OrigFolder = ".\"
$NewFolder = ".\_Sorted to Move"

# Orphans folder, where files that return null in the regex match will be moved
# Example: file "- title.pdf"
# will be moved to ".\_Orphans" folder

$Orphans = '_Orphans' # Use the underscore to sort the folder to the top of the window

#### How to use an array of values for the delimiters in the regex instead of literals
#### My proposed code, but I am missing how to use the delims in the regex match
#### $delims = "\s-\s" ",\s"\s and\s"

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

# Tell the user what will happen
clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $OrigFolder ' to _Sorted to Move'

# Ask user to confirm the copy operation
Read-host -prompt 'Press enter to start copying the files'

# Regex to match filenames
$Regex = [regex]"(?:(.*?)\s-)|(?:(.*?),\s)|(?:(.*?)\sand\s)"

# Loop through the $OrigFolder directory, skipping folders
Get-ChildItem -LiteralPath $OrigFolder | Where-Object {!$_.PsIsContainer} |
    ForEach-Object {
        if($_.BaseName -match $Regex){
        $ChildPath = $_.BaseName -replace $Regex

#Caluclate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

# If first part of the file name is empty, move it to the '_Orphans' folder
if(!$Matches[1]){
    $ChildPath = $Orphans}
else {
    $ChildPath = $Matches[1]
    }

# Generate new folder name
$FolderName = Join-Path -Path $NewFolder -ChildPath ($ChildPath + ' Magazine')

# Create folder if it doesn't exist
    if(!(Test-Path -LiteralPath $FolderName -PathType Container)){
    $null = New-Item -Path $FolderName -ItemType Directory}

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Move the file to the folder
Move-Item -LiteralPath $_.FullName -Destination $FolderName

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
$i++
    }
}

Write-Host 'Total number of files in '$OrigFolder ' is ' $numFiles
Write-Host 'Total number of files copied to '$NewFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

A: Q1: I tested your script on my machine with PDFs that followed the same naming scheme and it didn't create an Orphans folder or move my Orphan PDFs. I noticed you have a if ($_.BaseName -match $Regex) immediately after your foreach. Inside that is where you are looking for Orphans, but orphans wouldn't make it into this if block because they wouldn't match the Regex. In pseudocode, you structure should be something like:
    foreach{
          if (match)
               {$childpath $_.BaseName -replace $Regex}
          else
               {Childpath = $Orphans}
          Create your folders and do your moves.
}

Q2: Try, Catch blocks: https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/05/weekend-scripter-using-try-catch-finally-blocks-for-powershell-error-handling/
Q3: You can comment multiple lines by enclosing them in <# #> pairs.
<#
 How to use an array of values for the delimiters in the regex instead of literals
 My proposed code, but I am missing how to use the delims in the regex match
 $delims = "\s-\s" ",\s"\s and\s"
#>


text:
Q: Difficult in understanding question of minimum stopping distance
A car moving with a speed of 40 km / h can be stopped by applying brakes after at least 2 m. If the same car is moving with a speed of 80 km / h, what is the minimum stopping distance.

As I have interpreted the meaning of this question  is as that a car moving with a speed of 40km/hr can be stopped or reach the rest position , Only when brakes are applied after 2m of distance covered by the car.
The formula for minimum stopping distance is $\frac{u^2}{2a}$ . From this formula , I need to retardation that will be caused in the 1st case and then equate it with the 2nd case. I am not getting how to find it from the 1st case only since it is not given how much distance will it travel after brakes are applied.

A: I'll preface this by saying the question is not completely clear to me, however I tried my best to make a sensible interpretation of it.

A car moving with a speed of 40 km / h can be stopped by applying brakes after at least 2 m.

This means that if having a speed 40km/h at a point in time, and the breaks are kicked into the maximum, then it takes 2 meters to completely reduce the velocity of the car to zero. From this, we can figure out the maximum retardation we can produce from the breaks.

The formula for minimum stopping distance is $ \frac{u^2}{2a}$ . From this formula , I need to retardation that will be caused in the 1st case and then equate it with the 2nd case. I am not getting how to find it from the 1st case only since it is not given how much distance will it travel after brakes are applied.

I'd say this is a problem of the formula you are using, instead consider the following 'more general' formula(*):
$$ v^2 -u^2 = 2as$$
Where v is the final velocity, u is the initial, a is the 'constant acceleration' , s is the distance.  For your particular case, we want the car to become at a halt in both cases, substitute $ v=0$ , then:
$$ -u^2 = 2as$$
Plug the numbers in from the first case to figure out $a$ , now for the second case plug the newly found out acceleration with the velocity into the same equation to isolate for distance.
Hope this helps.

A: You are misinterpreting it after breaks are applied the car doesnt stop instantly , there is some regarding distance travelled by car which is given as 2m

You see retardation is the rate with which velocity decreases which means after the brakes were applied the car started regarding and took some time . In this time the car travelled some distance which is 2m


text:
Q: how to json nested parsing i have parse the json string and again i get another json string against key "data" kindly guide me how to get values against this json string this is the json . i am trying to use dictionary for parsing it but i am not able to parse it second time
 {
        AC =         (
                        {
                "ac_id" = 1;
                name = Wanted;
            },
                        {
                "ac_id" = 2;
                name = "Not Wanted";
            },
                        {
                "ac_id" = 3;
                name = Available;
            },
                        {
                "ac_id" = 4;
                name = "Not Available";
            }
        );
        Accomodation =         (
                        {
                "accomodation_id" = 1;
                name = Wanted;
            },
                        {
                "accomodation_id" = 2;
                name = Available;
            }
        );
        Accomodationfor =         (
                        {
                "accomodation_for_id" = 1;
                name = "Gents Bachelor";
            },
                        {
                "accomodation_for_id" = 2;
                name = "Ladies Bachelor";
            },
                        {
                "accomodation_for_id" = 3;
                name = Couple;
            },
                        {
                "accomodation_for_id" = 4;
                name = Family;
            },
                        {
                "accomodation_for_id" = 5;
                name = "Paying Guest";
            }
        );
        Accomodationtype =         (
                        {
                name = "Bed Space";
                "type_id" = 1;
            },
                        {
                name = "Studio Room";
                "type_id" = 2;
            },
                        {
                name = "Sharing room in flats/appartments";
                "type_id" = 3;
            },
                        {
                name = "Sharing room in House/Villa";
                "type_id" = 4;
            },
                        {
                name = "Flat/Appartment";
                "type_id" = 5;
            }
        );
        Cities =         (
                        {
                "city_id" = 1;
                "country_id" = 1;
                name = Lahore;
            },
                        {
                "city_id" = 2;
                "country_id" = 1;
                name = Islamabad;
            },
                        {
                "city_id" = 3;
                "country_id" = 1;
                name = Multan;
            },
                        {
                "city_id" = 4;
                "country_id" = 1;
                name = Karachi;
            },
                        {
                "city_id" = 5;
                "country_id" = 1;
                name = Queta;
            },
                        {
                "city_id" = 6;
                "country_id" = 2;
                name = Mumbai;
            },
                        {
                "city_id" = 7;
                "country_id" = 2;
                name = Delhi;
            },
                        {
                "city_id" = 8;
                "country_id" = 4;
                name = Dhaka;
            },
                        {
                "city_id" = 9;
                "country_id" = 5;
                name = "New York";
            },
                        {
                "city_id" = 10;
                "country_id" = 5;
                name = Washington;
            }
        );
        Cooking =         (
                        {
                "cooking_id" = 1;
                name = Wanted;
            },
                        {
                "cooking_id" = 2;
                name = "Not Wanted";
            },
                        {
                "cooking_id" = 3;
                name = Available;
            },
                        {
                "cooking_id" = 4;
                name = "Not Available";
            }
        );
        Countries =         (
                        {
                "country_id" = 1;
                name = Pakistan;
            },
                        {
                "country_id" = 2;
                name = India;
            },
                        {
                "country_id" = 4;
                name = Bangladesh;
            },
                        {
                "country_id" = 5;
                name = USA;
            }
        );
        Furnish =         (
                        {
                "furnish_id" = 1;
                name = "Fully furnished";
            },
                        {
                "furnish_id" = 2;
                name = "Semi furnished";
            },
                        {
                "furnish_id" = 3;
                name = "Not furnished";
            }
        );
        Nationality =         (
                        {
                name = Pakistani;
                "nationality_id" = 1;
            },
                        {
                name = Indian;
                "nationality_id" = 2;
            },
                        {
                name = American;
                "nationality_id" = 3;
            },
                        {
                name = Russian;
                "nationality_id" = 4;
            }
        );
        Power =         (
                        {
                name = "Govt.Authority";
                "power_id" = 1;
            },
                        {
                name = "Building Generator";
                "power_id" = 2;
            }
        );
        Religion =         (
                        {
                name = Islam;
                "religion_id" = 1;
            },
                        {
                name = Christianity;
                "religion_id" = 2;
            },
                        {
                name = Judaism;
                "religion_id" = 3;
            }
        );
    }
)

A: Try this following. Then,
SBJSON *json=[[SBJSON alloc] init];
NSDictionary *dict = [json objectWithString:data error:&error];
NSDictionary *datadict=[dict objectForKey:@"data"];

NSDictionary *ac=[datadict objectForKey:@"AC"];
NSDictionary *Accomodation =[datadict objectForKey:@"Accomodation"];
NSDictionary *Accomodationfor =[datadict objectForKey:@"Accomodationfor"];
NSDictionary *Accomodationtype =[datadict objectForKey:@"Accomodationtype"];
NSDictionary *Cities =[datadict objectForKey:@"Cities"];
NSDictionary *Cooking =[datadict objectForKey:@"Cooking"];
NSDictionary *Countries =[datadict objectForKey:@"Countries"];
NSDictionary *Furnish =[datadict objectForKey:@"Furnish"];
NSDictionary *Nationality =[datadict objectForKey:@"Nationality"];
NSDictionary *Power =[datadict objectForKey:@"Power"];
NSDictionary *Religion =[datadict objectForKey:@"Religion"];

These are all your sub dictionaries. These having sub arrays. To access that use array concepts, that  "ObjectAtindex".