text:
Q: How can I automatically launch an application whenever the Mac goes idle? Is there a way to launch an application, such as Transmission, every time the computer goes idle (instead of sleeping)?

A: This is a very hard feat to accomplish, primarily because there is no specific definition of "Idle". The only programs I've seen to actually have idle features are Instant Messaging Clients and the recent Mac App Store releases of Growl. And those simply have a configurable time that goes off after the set number of minutes when there's no mouse/keyboard activity occurring.
There's been similar discussion on the Macworld Forums some years ago, and a specific post that essentially entails creating and running an AppleScript that will monitor your usage and launch an application when you go "idle".

property idleCheck : 20 as integer
property idleCheck_usr : 120 as integer
set timer to 0
on idle
    --Check idle time
    set idletime to do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'"
    set idletime to idletime as string
    set idletime to idletime as integer

    tell application "System Events"
        if idletime is less than idleCheck then (* 20 is 20 seconds. If a key was tapped within the idleCheck seconds, it quits the app. *)
            tell application "TextEdit" to quit

            return idleCheck -- checks again in ... seconds
        else
            if idletime is greater than idleCheck_usr then (*  If a key was tapped after the idleCheck_usr seconds it opens the app. *)
                tell application "TextEdit" to launch
            end if

            return idleCheck
        end if
    end tell
end idle

In this case idle is only after 2 minutes, but you can easily change that to be longer if necessary. You will also want to modify the line to open Transmission instead of TextEdit.
Note that you will have to open this AppleScript and leave it running in order for the action (launching an application on idle) to ever occur.

A: Have you tried using Scenario? It is on the Mac App Store. While I haven't tried it myself. It seems that it might do what you need. Hope this helps.

A: How about Sleepwatcher?
"SleepWatcher 2.2 (running with Mac OS X 10.5 to 10.7, source code included) is a command line tool (daemon) for Mac OS X that monitors sleep, wakeup and idleness of a Mac. It can be used to execute a Unix command when the Mac or the display of the Mac goes to sleep mode or wakes up, after a given time without user interaction or when the user resumes activity after a break or when the power supply of a Mac notebook is attached or detached. It also can send the Mac to sleep mode or retrieve the time since last user activity."
To launch an app (using a command), you'd have to do something like the following:
open /Applications/Transmission.app

A: Power Manager can be used to launch an application after inactivity.
As Jason mentions in his answer, Apple's implementation of idle time is difficult to predict. Power Manager uses a measure of inactivity based on user activity; this is easier to predict and more likely to be what you are looking for.

A: If the screen saver starting is what you mean as idel you could look at ScriptSaver which makes itself into a screen saver and then when it is called it calls your AppleScript ad a screen saver.


text:
Q: (applescript) cant use command f hi im working on a simple router cracker and this part won't compile (this is for searching the router ip so you can find its service provider) (if you get it)
tell application "Safari"
activate
open location "http://www.techspot.com/guides/287-default-router-ip-addresses/"
keystroke "f" using {command down, shift down}
set search to text returned of (display dialog "router ip" default answer "" buttons {"cancel", "find it"} default button 2)
search
keystroke "enter" using {command down, shift down}

A: As DigiMonk said, the keystroke command is provided by System Events. You can also use UI scripting to fill the search field:
tell application "Safari"
    activate
    open location "http://www.techspot.com/guides/287-default-router-ip-addresses/"
    set search to text returned of (display dialog "router ip" default answer "")
end tell
tell application "System Events"
    keystroke "f" using command down
    tell process "Safari"
        tell group 1 of group 1 of window 1
            set value of text field 1 to search
            click button 1
        end tell
    end tell
end tell

redpajama_set_name: RedPajamaStackExchange


text:
Q: multidatespicker jquery jquery-ui-dist estoy implenetando un pequeño sistema con laravel y para dar solucion a la seleccion multiple de fechas me decidi por utilizar jquery multidatespicker (http://dubrox.github.io/Multiple-Dates-Picker-for-jQuery-UI/), mi problema es que al correr el comando npm run dev me envia el siguiente error

his dependency was not found:

*

*jquery-ui-dist in ./node_modules/jquery-ui-multidatespicker/jquery-ui.multidatespicker.js

esta dependencia es llamada dentro del archivo query-ui.multidatespicker.js con la siguiente funcion
 (function(factory) {
  if (typeof define === "function" && define.amd) {
    define(["jquery", "jquery-ui-dist"], factory);
  } else {
    factory(jQuery);
  }

He estado navegando por unas horas y no he encontrado documentacion a dicho problema.


text:
Q: Put semicolons in asi mode before brackets I'm linting my JavaScript with JSHint, and have this option enabled
"asi": true,
"white": true

to avoid semicolons in my code.
But I have to begin my new line with a bracket, so I have to put a semicolon before the opening of that one
;(function () {

})

JSHint give me two errors:

*

*Missing space after ';'

*If I put a space after ';' I get: Expected '(' to have a different identation
I noticed that in this way JSHint is happy
;
(function () {

})

but I think is not a good solution.
Is there a way to solve this problem, without turning off JSHint or the white option?

A: The legacy white: true option in JSHint is used to enforce the coding style promoted by Douglas Crockford in his original JSLint tool.  Semicolon-less JavaScript code will not fit his coding style. If you don't want to be restricted to his style guidelines then don't use white: true.
This list of JSHint options doesn't show any parameters to customize the coding style they enforce.
To prove that there isn't an answer to this, I went and found the relevant check in the JSHint source:
function nonadjacent(left, right) {
    if (option.white) {
        left = left || token;
        right = right || nexttoken;
        if (left.line === right.line && left.character === right.from) {
            left.from += (left.character - left.from);
            warning("Missing space after '{a}'.",
                    left, left.value);
        }
    }
}

The only configuration option checked is option.white, so unfortunately there isn't any way to achieve your desired behavior. If you really wanted a tool that would do exactly what you want, you could easily fork JSHint, add another option, and check it in the nonadjacent function.


text:
Q: Add pre-defined icon to ASP page I'm making a table with data, and the last column needs to be have a recycle-bin icon for each row, allowing me to delete that row. Problem is, I can't find this icon or how to add it.
This is an <asp:Table> Web Control and I'm adding rows and cells via the C# file behind it.
I'm thinking of using something like:
TableCell cell = new TableCell();
cell.

And that's where I'm stuck. I need to have the cell contain that clickable recycle-bin icon, but I don't know how to add it.

A: Unless i'm missing something, can you not just add an Image to the cell?
Or you can set the HTML of the TableCell directly via the Text property:
string recycleBinImage = "<img src='/Images/recycle_bin.jpg' alt=''>";
TableCell cell = new TableCell();
cell.Text = recycleBinImage;
row.Controls.Add(cell);

OR
Image recycleBinImage = new Image();
recycleBinImage.ImageUrl = "/Images/recycle_bin.jpg";
cell.Controls.Add(recyleBinImage);
row.Controls.Add(cell);

Then if you want to "delete" something, just add the "onclick" attribute:
recycleBinImage.Attributes.Add("onclick", "someFunctionWhichDeletes();");


text:
Q: Where to find uid (User ID) list in Google Analytics I'm using the tracking pixel on a newsletter with the following URL:
<img src="http://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXXX-1&cid=111&uid=123&t=event&ec=email&ea=open&el=111&cs=newsletter&cm=email&cn=062413&cm1=1" alt="" />

I can correctly see how many times the newsletter gets opened but I cannot find on Analytics where to see who actually opened it, where do I find the uid list in order to know who opened the email?

A: You can view the same in Top Events reports.
Go to Behaviour > Events > Top Events and then select secondary dimension as User ID as below. There you will be able to see User ID with Total Events.

Hope this helps !

A: You have to

*

*enable user id tracking for this ga property first

*then create a custom view

*then send data and wait

See https://support.google.com/analytics/answer/3123666
As this is not referenced from the ga protocol documentation, this is very unclear when you start to use GA


text:
Q: Why PhpStorm inspection says `Exception` is undefined? PhpStorm doesn't recognize Exception from some reason. The code executes fine, but I cannot "go to" code (which should send me to Core_c.php):

A: Windows OS has "try rebooting the OS" advice which helps in a lot of "does not work / suddenly stopped working" scenarios.
File | Invalidate Caches is the one for PhpStorm, especially after IDE/OS crash or after upgrading your IDE to a newer version.
P.S.
I had to make up some text, otherwise it's too short for an answer.


text:
Q: encoding inferno german special characters in StatET eclipse as well as in RStudio I set
options(encoding = "ISO-8859-1")

in StatET I have:
Sys.getlocale()
[1] "LC_COLLATE=German_Germany.1252;LC_CTYPE=German_Germany.1252;LC_MONETARY=German_Germany.1252;LC_NUMERIC=C;LC_TIME=German_Germany.1252"

in RStudio the same:
Sys.getlocale()
[1] "LC_COLLATE=German_Germany.1252;LC_CTYPE=German_Germany.1252;LC_MONETARY=German_Germany.1252;LC_NUMERIC=C;LC_TIME=German_Germany.1252"

all on the same computer running at the same time, but with the same input (in both cases entered in to the console directly), I get different results.
RStudio:
strsplit("GRÜN", "")
[[1]]
[1] "G" "R" "Ü" "N"

StatET:
strsplit("GRÜN", "")
[[1]]
[1] "G" "R" "Ã" " "N"

Question: What else do I need to do besides setting Sys.setlocale() and encoding to make the two systems produce the same result?

A: I'm no expert on this, but if you are on Windows I suspect it is the system locale. In that case go to:
control panel -> region and language -> administrative -> change system locale [for non unicode programs]
I have everything set to work with Russian on my computer, and this is no problem at all, but when I tried your code with I got this:
Sys.setlocale("LC_CTYPE","german")
strsplit("GRÜN", "")
[[1]]
[1] "G" "R" "Ь" "N"

So clearly Rstudio is confusing the umlaut and the Russian soft sign, which is something Windows often does.


text:
Q: Transferring file from local machine to server in WinSCP using Java I want to write a notepad file and upload it to a WinSCP path.
I used to create those files manually: Open the WinSCP, give the credentials, open the desired path and upload the file.
Now I am in a situation to automate those things. Text will be entered in a text box or fetched from DB, it has to be written in a notepad file and should be uploaded to a WinSCP path. I have implemented writing the file and it is working fine.
Now, how do I upload the file using Java?

A: What you call "WinSCP path" is actually a storage accessible via some file transfer protocol. Most typically a FTP or SFTP site.
For the FTP, you can use for example the URLConnection class:
Uploading to FTP using Java
or the Apache FTPClient client class:
FTPClient - Java, upload file
For the SFTP, you can use JSch Library:
How to retrieve a file from a server via SFTP?
If you really want to use WinSCP, you can interact with WinSCP scripting interface from Java. See a code sample in the following question:
How to know whether SFTP was successful or not in WinSCP


text:
Q: linq to entities query which has multiple where clause and one where clause with where in condition I'm trying to build a linq to entities query. This is what I have so far:
            from x in db.BusSchedule
            join y in db.BusSchedule on x.ID equals y.ID - 1
            where Convert.ToInt32(y.StopOrder) >= Convert.ToInt32(x.StopOrder)
            && x.NameOfTown == arrival
            && x.Line in (SELECT Line FROM BusSchedule WHERE NameOfTown = destination)
            orderby x.DepartureTime ascending
            select x).Distinct()

I'm not sure how to do the IN part, and I'm pasting the actual sql query I'm using. How can I translate this SQL query

'SELECT Line FROM BusSchedule WHERE NameOfTown = destination'

in Linq to Entities query?

A: var dest = (from b in db.BusSchedule
           where b.NameOfTown = destination
           select b.Line).ToList();

var output = (from x in db.BusSchedule.Where(b => b.NameOfTown == arrival)
             join y in db.BusSchedule on x.ID equals y.ID - 1
             where Convert.ToInt32(y.StopOrder) >= Convert.ToInt32(x.StopOrder)
                   && dest.Contains(x.Line)
             orderby x.DepartureTime ascending
             select x)
             .Distinct()


text:
Q: Functional tests on Symfony 2 - issue with the default autoload.php.dist I have been trying to run FunctionalTest which extends the Symfony\Bundle\FrameworkBundle\Tests\Functional\WebTestCase with not so much success.
The issue is that:

*

*the code in FrameworkBundle\Tests\Functional\app\AppKernel.php attempts to load autoload.php.dist in the framework bundle (not the one in the app/).

*And autoload.php.dist then tries to load vendor\autoload.php which does not exist within this path.
If I remove the autoload.php.dist  in the FrameworkBundle then everything is fine, but I want to avoid doing that because each time I do composer update I will then have to remove that specific fine.
I wonder what I'm doing wrong.
The exact error from the console is posted below for your information:

Configuration read from D:\xampp\htdocs\demo\app\phpunit.xml.
  dist

*

*require_once() called at [D:\xampp\htdocs\demo\vendor\sym
  fony\symfony\src\Symfony\Bundle\FrameworkBundle\Tests\Functional\app\AppKernel.p
  hp:26]

*require_once(D:\xampp\htdocs\demo\vendor\symfony\symfony\
  src\Symfony\Bundle\FrameworkBundle\Tests\Functional\app\AppKernel.php)
  called at
  [D:\xampp\htdocs\demo\vendor\symfony\symfony\src\Symfony\Bun
  dle\FrameworkBundle\Tests\Functional\WebTestCase.php:47]
Fatal error: main(): Failed opening required
  'D:\xampp\htdocs\demo\vendor\symfony\symfony/vendor/autoload.php'
  (include_path='.;D:\xampp\php\PEAR') in
  D:\xampp\htdocs\demo\vendor\symfony\sym
  fony\autoload.php.dist on line 9

The test class simply extends WebTestCase with the setUp looks like this:
static::$kernel = static::createKernel(array('test_case'));
static::$kernel->boot();
$this->containter = static::$kernel->getContainer();

A: Okay.  I see the problem.  You are extending from Tests\Functional\WebTestCase.  That is actually a test for testing the WebTestCase.  You want to extend from Test\WebTestCase.
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PersonRepositoryTest extends WebTestCase
{
    public function testProject()
    {
        $client = static::createClient();

        $manager = $client->getContainer()->get('cerad_person.manager');

And you might want to get one or two working using the $client line shown above.  All the setup stuff can be a bit tricky.


text:
Q: How to get the calling code for a filter in jinja tl;dr: is it possible to find out where in a jinja template calls a jinja filter from within the filter?
Background
So I have a filter that I'm using in a jinja template called get_image_path(), essentially it takes in a file path and/or url and puts it into the proper format for the app.
I am trying to format traceback outputs so that I can get some idea where they are coming from if someone has an error. Basically when someone passes something that isn't a usable path I want to be able to throw an error and provide a message with the line in the template that called the filter so people know which variable to look for.
So is it possible for me to get the line in the template that called the filter, or do I have to do manual traceback formatting?
Current code for get_image_path()
def get_image_path(path:str) -> str:
    # I omitted the docstring
    try:
        if path.startswith("http"):
            return path

        elif path.startswith("images"):
            return f"{path}"

        else:
            return f"images/{path}"
    except AttributeError as e:
        traceback.print_tb(e.__traceback__, limit=7)
        ValueError(f"ValueError: Could not get image path: {path}")

A: My solution
For me the issue is caused by an AttributeError:
def get_image_path(path:str) -> str:
    try:
        if path.startswith("http"):
            return path

        elif path.startswith("images"):
            return f"{path}"

        else:
            return f"images/{path}"
    except AttributeError:
        for frameInfo in stack(): # Get the frame for the error raised
            if frameInfo.frame.f_globals.get("__jinja_template__") is not None: # Find the jinja template namespace if it exists
                template = frameInfo.frame.f_globals.get("__jinja_template__")
                break
        if not path: # If the image path is False (usually because a required image wasn't provided)
            raise ValueError(f"\n\nNo path provided for required image in {template.filename} #line {template.get_corresponding_lineno(currentframe().f_back.f_lineno)}")
        else: # If it's just an invalid image path
            raise ValueError(f"\n\nCould not get image path: {path}\n Error occured on \n{template.filename} #line {template.get_corresponding_lineno(currentframe().f_back.f_lineno)}")

When the filter fails because a boolean is passed instead of an image path this message is now provided:

ValueError:
No path provided for required image in
c:\users\kieran\appdata\local\programs\python\python39\lib\site-packages\ezcv\themes\ethereal\index.jinja
#line 45

Background & How it works
So when in the except statement these lines:
for frameInfo in stack(): # Get the frame for the error raised
            if frameInfo.frame.f_globals.get("__jinja_template__") is not None: # Find the jinja template namespace if it exists
                template = frameInfo.frame.f_globals.get("__jinja_template__")
                break

are using the inspect module to check if a value in the global namespace called __jinja_template__ is found. If this value is found it means the error was raised in a template and from that we can get the Jinja Template Object. This object contains the info about the line number and filename I want so it gets assigned to the template variable.
From there template.filename will give you the source file path, and template.get_corresponding_lineno(currentframe().f_back.f_lineno) (documentation here) will give you the line number, and the rest of the code is just formatting the ValueError to pass the information I want back to the user.
Thanks to @β.εηοιτ.βε for the suggestion of looking at their answer to How to get current line of source file when processing a macro? to figure all this out


text:
Q: Checking that an email address is google based or not I am working on rails application that take user email and check that if user email id is google based then it redirect to google login else it redirect to application login page.
example:
1) if it regular gmail email address like(example@gmail.com)
2) if it google apps based email address like(example@company.com where company.com uses google apps)
3) if it use any other email address like(example@yahoo.com or example@hotmail.com)
So,how can I check that the user mail is gmail based that fulfill my 1st & 2nd condition.
Thank you :)

A: For the first and the last points you can use a simple regex and check if domain=="google" or domain=="yahoo":
email = 'tired@mydomain.com'
domain = email.sub(/.+@([^.]+).+/, '\1')

The upper lines will extract only mydomain. You can add a condition later to check whether is gmail / yahoo.
As for the second point you could dig the emails' MX records (you can check how this can be done in ruby). Here's the flow:
$> dig domainname.com mx

If they're with Google, you'll know it.
domainname.com.            2198    IN      MX      10 ASPMX.L.GOOGLE.com.
domainname.com.            2198    IN      MX      20 ALT1.ASPMX.L.GOOGLE.com.
domainname.com.            2198    IN      MX      20 ALT2.ASPMX.L.GOOGLE.com.
domainname.com.            2198    IN      MX      30 ASPMX2.GOOGLEMAIL.com.
domainname.com.            2198    IN      MX      30 ASPMX3.GOOGLEMAIL.com.
domainname.com.            2198    IN      MX      30 ASPMX4.GOOGLEMAIL.com.
domainname.com.            2198    IN      MX      30 ASPMX5.GOOGLEMAIL.com.


text:
Q: Add a CC to a mail to script I have a form that sends an email and I want to add a cc email to the mail to line. Please show me how I would need to have the line below to acomplish this. Thanks
mail("mainemail@email.com;CCemail@email.com", $subject, $message, $header);

A:     public function SMTPClient($subject,$content,$instance) {
            try {
                $mailer = new PHPMailer(true);
                $mailer->IsSMTP();
                $mailer->SMTPDebug  = 1;
                $mailer->SMTPAuth   = def_SMTP_AUTHENTICATION;                  // enable SMTP authentication
                $mailer->SMTPSecure = def_SMTP_SECURE;                 // sets the prefix to the servier
                $mailer->Host       = def_SMTP_SERVER;                      // sets GMAIL as the SMTP server
                $mailer->Port       = def_SMTP_PORT;                   // set the SMTP port for the GMAIL server
                $mailer->Username   = def_SMTP_USERNAME;              // GMAIL username
                $mailer->Password   = def_SMTP_PASSWORD;            // GMAIL password

                $mailer->SetFrom(def_MAIL_FROM_ADDRESS, def_MAIL_FROM_NAME);

                $to = def_MAIL_TO;

                $mailer->AddAddress($to);
                $mailer->Subject    = $subject;
                $mailer->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                $mailer->WordWrap   = 80; // set word wrap
                $mailer->AddCC('xzy@gmail.com', 'xyz');
                $mailer->AddReplyTo(def_MAIL_TO, 'abc');
                $mailer->MsgHTML($content);
                $mailer->IsHTML(true); // send as HTML

                $mailer->Send();
                $this->logger("Message has been sent Successfully","INFO",$instance);
                echo 'Message has been sent Successfully.';
            } catch (phpmailerException $e) {
                echo $e->errorMessage()`enter code here`;
            }
        }

Note:Use the mailer component from http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.4.zip&can=2&q=


text:
Q: Prove that $1-\Phi(x)\leq \frac{1}{2}e^{-\frac{x^2}{2}}$ I've managed to simplify it as
$\int_x^{\infty}exp(-u^2/2)[\frac{1}{\sqrt{\pi}}-u]du\leq 0$
But I'm not sure how to prove it for all $x$ since I can only see this as obviously true when $\frac{1}{\sqrt{\pi}}\leq u$

A: This classical relation is only valid for $x \ge 0$.
By definition,
$$1 - \Phi(x)  = \frac{1}{\sqrt{2 \pi}} \int_x^{+\infty} \exp{\{-u^2/2\}} du $$
By letting $v = u - x$, we get
$$ \int_x^{+\infty} \exp{\{-u^2/2\}} du = \exp{\{-x^2/2\}} \int_0^{+\infty}\exp{\{-v^2/2\}} \exp{\{-xv\}} dv $$
Then, we use that, for $x \ge 0$ and $v \ge 0$,
$$ \exp{\{-xv\}} \le 1$$
and that
$$ \int_0^{+\infty}\exp{\{-v^2/2\}}\, dv = \frac{\sqrt{2 \pi}}{2}$$
To get the desired result.
$$ 1-\Phi(x)\leq \frac{1}{2} \exp{\left(-\frac{x^2}{2}\right)} $$

A: The statement only holds for $a\geq0$.
Let $\phi(a)=\frac{1}{\sqrt{2\pi}}e^{-a^2/2}$ the density of the standard normal distribution, and $F(a)=\int^a_{-\infty}\phi(s)\,ds$.
Let $$G(a)=1-F(a)-\frac{c}{2}\phi(a)$$
where $c=\sqrt{2\pi}$. Then
$$G'(a)=-\phi(a)+\frac{c}{2}a\phi(a)=\phi(a)(\frac{c}{2}a-1)$$
The only critical point is $a_*=\frac{2}{c}$ which corresponds to a local minimum at which $G(a_*)\approx -0.151\ldots<0$.
Notice that  $\lim_{a\rightarrow\infty}G(a)=0$ and $\lim_{a\rightarrow-\infty}G(a)=1$.
Thus, for $a$ negative but large the statement in the OP fails. For $a>0$
$$ G''(a)=-a\phi(a)(\frac{c}{2}a-1)+\phi(a)\frac{c}{2}=\phi(a)\Big(\frac{c}{2}+a-\frac{c}{2}a^2\Big)$$
and so, $G$ has only one nonnegative inflection point at $a_i=\frac{1+\sqrt{1+2c^2}}{c}$. Hence, $g(a_*)\leq G(a)<0$ for all $a>0$.


text:
Q: Filter data obtained through GitHub API I created this function to obtain GitHub issues:
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
  let data = null;

  // token auth
  octokit.authenticate({
    type: 'basic',
    username: config.githubEnterprise.username,
    password: config.githubEnterprise.token
  });

  async function paginate(method) {
    let response = await method({
      q: "repo:" + repoOrg + "/" + repoName + " is:issue",
      per_page: 100
    });
    data = response.data.items;
    var count = 0;
    while (octokit.hasNextPage(response)) {
      count++;
      console.log(`request n°${count}`);
      response = await octokit.getNextPage(response);
      data = data.concat(response.data.items);
    }
    return data;
  }

  paginate(octokit.search.issues)
    .then(data => {
      callback(data);
    })
    .catch(error => {
      console.log(error);
    });
  }

It is called in this function which takes the issues, filters out all of the unwanted keys into json format and puts it in my db.
extractToDb: function() {
  let gitIssues = null;
  for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
    for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
      gitHubService.retrieveEnerpriseIssues(
        config.githubEnterprise.orgs[i].owner,
        config.githubEnterprise.orgs[i].repos[j].repoName,
        function(data, err) {
          if(err) {
            console.log('err: ', err);
          } else {
            gitIssues = data;
          }
          gitIssues = JSON.stringify(gitIssues);
          gitIssues = JSON.parse(gitIssues);
          let issueFormatForDb = null;
          for(var i = 0; i < gitIssues.length; i++) {
            issueFormatForDb = gitIssues[i];
            const body = '{' +
              '"github_id": "' + issueFormatForDb.id + '",' +
              '"issue_title": "' + issueFormatForDb.title + '",' +
              '"issue_number": "' + issueFormatForDb.number + '",' +
              '"issue_url": "' + issueFormatForDb.url + '",' +
              '"issue_state": "' + issueFormatForDb.state + '"' +
          '}';
          console.log('Body: ', body);
          getGitHubIssues.postToDb(body);
        }
      });
    }
  }
}

I'd like to take this a step further by filtering out any issues where the state is closed. How is this done and should it be handled in my retrieveEnerpriseIssues function or my extractToDb?
Possible solution
I tried this in my extractToDb function:
gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;

Is it the best solution or is there a better way?

A: As @givehug stated:
Better use _.filter, or native filter method like
gitIssues = gitIssues.filter(i => i.state === 'open')

I think .where was deprecated in later versions of lodash github.com/lodash/lodash/wiki/Deprecations. Other than that its perfectly fine.
I just realsied I can filter the state in my paginate function with this:
let response = await method({
    q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
    per_page: 100
  });


text:
Q: Продублировать каждую букву слова на СИ В рядок вводится имя, фамилия и отчество. Нужно взять имя, продублировать кажую букву, после чего засунуть обратно в исходную строку.
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char s[80];
    int i;
    printf("Enter a string: ");
    gets(s);
    for (i = 0; i < strlen(s); i++)
    {
        s[i] = s[i] * 2;
        if (s[i] != " ")
        {
            break;
        }
    }
    printf("%s", s);
    return 0;
}

A: алгоритм

*

*выделить имя из строки, т.е. найти позицию первого разделителя ',' - pos

*создать новую строку размером не меньшим, чем pos + len(text)

*вписать в новую строку буквы первого слова (по 2 раза), можно через функцию strncat()

*вписать в новую строку часть старой строки, начиная с pos
чтобы все сделать именно в одной строке - это в общем случае невозможно ибо новая строка большего размера и не факт, что в старой было выделено достаточно памяти
P.S.
касательно вашего кода:
s[i] = s[i] * 2;

это не питон, в c++ так буквы не удваиваются,в c++ все более примитивно:
new_str[j++] = old_str[i];
new_str[j++] = old_str[i];

ну или через strncat


text:
Q: Append elements form JSON response to multidimensional array I am using Alamofire and SwiftyJSON.
Code:
var array = Array<Array<String>>()

Alamofire.request(.GET, url, parameters: ["postType": "live"], encoding: ParameterEncoding.URL).responseJSON { (_, _, result) in
        switch result {

            case .Success(let data):

                let json = JSON(data)

                for(_,subJSON):(String, JSON) in json["Info"] {

                    let Tag = subJSON["Tag"].string!
                    let Location = subJSON["Location"].string!

                    array.append(Array(count: 4, repeatedValue: concertTag))

                }

            case .Failure(_, let error):

                print("Request failed with error: \(error)")
        }
    }

I want to create an array multidimensional. And add JSON variables to it for after pass the array to TableView.
So basically i need "array" to be like:
[[Tag1; Location1],[Tag2, Location2], .... ]

How can I do this? any ideas?
Thank you

A: You just would have to replace
array.append(Array(count: 4, repeatedValue: concertTag))

with
array.append([Tag, Location])

And you would get the data back like this for example:
for arr in array {
    print("tag: " + arr[0])
    print("loc: " + arr[1])
}

But I would suggest another approach: using tuples.
First let's create a type result because it's convenient:
typealias TagAndLocation = (tag: String, location: String)

Then prepare an empty array of results:
var resultTuples = [TagAndLocation]()

Fill the array of tuples in the loop:
for (_, subJSON) in json {
    let Tag = subJSON["Tag"].string!
    let Location = subJSON["Location"].string!

    let tagloc = (tag: Tag, location: Location)
    resultTuples.append(tagloc)
}

Then you can access your data in two ways:
for (tag, loc) in resultTuples {
    print("tag: " + tag)
    print("loc: " + loc)
}

for result in resultTuples {
    print("tag: " + result.tag)
    print("loc: " + result.location)
}

Note: your variables names should begin with a lowercase letter. Beginning with uppercase is usually for classes, types, protocols and such.


text:
Q: How to make datetime.now function update when put within a loop I have created a for Loop that repeats the piece of code 100 times, the problem is that the datetime import won't update within the loop.
Code below:
from datetime import datetime
now = datetime.now()

print("%02d-%02d-%04d") % (now.year, now.month, now.day)
#below is the loop
for i in range(0, 100):
  time.sleep(1)
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

all it outputs is the same hours, minutes and seconds as when I first pressed run.
Output below:

11:59:0711:59:07

11:59:0711:59:07

(This carries on for 100 times)

A: You have to call now again:
for i in range(0, 100):
  time.sleep(1)
  now = datetime.now()
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

now is an object, it doesn't get the new time when you use it (it would be terrible).

A: you are only sampling now one time, you need to do it inside the for loop like so
from datetime import datetime
now = datetime.now()

print("%02d-%02d-%04d") % (now.year, now.month, now.day)
#below is the loop
for i in range(0, 100):
  time.sleep(1)
  now = datetime.now()
  print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)

A: Why don't you move the now = datetime.now() within the loop?
for i in range(0,100):
    time.sleep(1)
    now = datetime.now()
    print ("%02d:%02d:%02d") % (now.hour, now.minute, now.second)


text:
Q: time returns negative numbers I am trying to create a 24hr timer on a database using quick.db, but my timer isn't ticking, and time logs negative number.
const db = require('quick.db');
const Discord = require('discord.js');
const ms = require('parse-ms');

let timer = await db.fetch(`daily_timer`);
let timeout = 86400000;

if (timer !== null && timeout - (Date.now() * -2 - timer) > 0) {
    let time = ms(timeout - (Date.now() * -2 - timer));
    console.log(time);
    etc..
};

If the * -2 is removed from let time = .. then it logs everything as negative.
Date.now() returns as normal.
console.log for time:
{ days: -18950, hours: -9, minutes: -56, seconds: -51, milliseconds: -673, microseconds: -0, nanoseconds: -936 }
console.log for Date.now():
1637488611676
Any help would be appreciated, as I really have no idea why the time is negative.

A: The unix timestamp 86400000 represents the 27th of September 1972.
With timeout - Date.now() you are asking, how much time do i need to add to the current date, to get to the 27th of September 1972. Since the current date is FAR beyond 27th of September 1972, the time you need to add will be negative.


text:
Q: MARS Backup (system state) backup failing - Windows server 2012 MARS Backup - system state backup failing
I am having issues with few servers, where the system state is not getting backup.
MARS system backup failure
I did follow the article below and attempt it, by changing the scratch folder to different location, it did not made any difference.
How do I change the cache location for the MARS agent?
Run this command in an elevated command prompt to stop the Backup engine:
Net stop obengine
If you have configured System State backup, open Disk Management and unmount the disk(s) with names in the format "CBSSBVol_".
By default, the scratch folder is located at \Program Files\Microsoft Azure Recovery Services Agent\Scratch
Copy the entire \Scratch folder to a different drive that has sufficient space. Ensure the contents are copied, not moved.
Update the following registry entries with the path of the newly moved scratch folder.
Table 2Registry path Registry Key Value
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Azure Backup\Config
ScratchLocation
New scratch folder location
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Azure Backup\Config\CloudBackupProvider
ScratchLocation
New scratch folder location
Restart the Backup engine at an elevated command prompt:
command Copy
Net stop obengine
Net start obengine
Run an on-demand backup. After the backup finishes successfully using the new location, you can remove the original cache folder.
Can I please have some advice, as I have got few servers where the system state is not being backed up.

A: This is actually a failure in the Windows Server Backup operation. See this KB article for steps on how you can modify required registry keys to fix the Windows Server Backup failures.
https://support.microsoft.com/en-us/help/4053355/microsoft-azure-recovery-services-agent-system-state-backup-failure


text:
Q: Getting PostId for CommentId using Autoform for Meteor Without the autoform, normally, we will do the below to submit comment:
comment-submit.js
 'submit form': function(e, template) {
     e.preventDefault();

     var $body = $(e.target).find('[name=body]');
     var status = {
       body: $body.val(),
       postId: template.data._id
     };

We can inject the postId into the each comment.
How to do that with Autoform?
I had try with this near the comment collection:
 Comments = new Mongo.Collection('comments');

 Comments.before.insert(function (userId, doc) {
   doc.postId = Posts.findOne()._id;
 });

 Comments.attachSchema(new SimpleSchema({
   body: {
     type: String,
     autoform: {
       'label-type': 'placeholder',
       placeholder: 'Add your comment…'
     }
   },
   postId: {
     type: String
   }
 }));

It's work but it always get the postId of the 1st post in the collection even it is actually the 2nd, 3rd or other than 1st post.
Please guide. Thanks.

A: collection.findOne() always returns the first document that was inserted into a collection. So the nicest way to do this, that comes to my mind, is a hidden field. Just add a field to your autoForm
{{ > afQuickField name="postId" value=_id style="display: hidden;" }}

This solution will work without any hooks or special attributes.


text:
Q: Filtering Users in MSGraph I'm trying to filter users by attributes in Microsoft Graph API. Essentially trying to get a list of users that have a given jobTitle assigned.
For example, https://graph.microsoft.com/v1.0/users?$filter=jobtitle eq 'ACCOUNT EXECUTIVE' returns a list of users.
My requirement is to query for users that do not have a JobTitle.
Tried https://graph.microsoft.com/v1.0/users?$filter=jobtitle ne null and got the following message.
{
    "error": {
        "code": "Request_UnsupportedQuery",
        "message": "Unsupported property filter clause operator 'NotEqualsMatch'.",
        "innerError": {
            "request-id": "c9b290bf-2902-4b79-b35b-0f5d251ad80b",
            "date": "2017-09-14T11:18:52"
        }
    }
}

A: $filter=department ge '!' appears to be a workaround here.

A: According to this Git Issue, I don't think it's supported: https://github.com/microsoftgraph/microsoft-graph-docs/issues/239 (it eventually just revolves around finding rooms)

There is no way to filter the users collection for entities with surname equal to null or empty string. The value of the filter must be between 1 and 64 characters as documented here: https://msdn.microsoft.com/en-us/Library/Azure/Ad/Graph/api/entity-and-complex-type-reference#userentity - marych Apr 26, 2016
The lack of null filtering is due to the way users are indexed. We can't efficiently retrieve users with an indexed property unset. There are no plans to change that. - marych May 13, 2016


text:
Q: What is stopping me from installing npm packages please check the code and tell me. Unable to install any library IMP: My PC is windows 10 32 bit

(current: {"os":"win32","arch":"ia32"})

Is this the reason ?
E:\My Projects\app>npm i faker
npm WARN @apideck/better-ajv-errors@0.3.3 requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
npm WARN @react-aria/ssr@3.1.2 requires a peer of react@^16.8.0 || ^17.0.0-rc.1 but none is installed. You must install peer dependencies yourself.
npm WARN fork-ts-checker-webpack-plugin@6.5.1 requires a peer of typescript@>= 2.7 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >=
3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install
peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})

+ faker@6.6.6
added 1 package from 1 contributor and audited 1424 packages in 53.178s

173 packages are looking for funding
  run `npm fund` for details

found 4 vulnerabilities (1 moderate, 3 high)
  run `npm audit fix` to fix them, or `npm audit` for details

A: There is no error in there.
It's just warn-informing you that fsevents is a Mac-only (darwin is the codename for macOS) package and won't be installed on your Windows box.
Based on "audited 1424 packages" you already have 1424 packages installed, so there's seemingly nothing stopping you from installing packages.


text:
Q: How do I copy and insert rows to a master sheet, and place these multiple rows in different locations based on keywords found on the master sheet? Here is the current code I'm running.
Sub PullTally()
 ' get source and destination workbook files
    Dim pullFile As String
    pullFile = Application.GetOpenFilename(fileFilter:="All Files (* . *) , * . * ")  'Copy From'
    Dim putFile As String
    putFile = Application.GetOpenFilename(fileFilter:="All Files (* . *) , * . * ")   'Insert To'
    'open source workbook
    Dim SourceWb As Workbook
    Set SourceWb = Workbooks.Open(fileName:=pullFile)
    ' open destination workbook
    Dim DestWb As Workbook
    Set DestWb = Workbooks.Open(fileName:=putFile)

Dim destWS As Worksheet:  destWS = DestWb.Worksheets("Sheet1")
Dim sourceWS As Worksheet:  sourceWS = SourceWb.Worksheets("Sheet1")
Dim sourceRowNum As Long
For sourceRowNum = 1 To 13 Step 1
    With sourceWS
        Dim findTerm As String
        Select Case True
            Case .Cells(sourceRowNum, 4).Value = "(OUTSOURCED)"
                findTerm = "OUTSOURCED"
            Case .Cells(sourceRowNum, 5).Value = "No"
                findTerm = "COMING UP…"
            Case .Cells(sourceRowNum, 4).Value = "(DESIGN ONLY)"
                findTerm = "DESIGN; DESIGN ONLY ORDERS"
            Case .Cells(sourceRowNum, 5).Value = "Yes"
                findTerm = "DESIGN;PRODUCTION/ACTUAL ORDERS"
            Case Else
            'can add other cases
        End Select
    End With
    With destWS
        Dim findRange As Range
        Set findRange = .Columns(1).Find(findTerm)
        If Not findRange Is Nothing Then
            Dim destInsertRow As Long
            If findRange.Offset(1).Value = "" Then
                destInsertRow = findRange.Row + 1
            Else
                destInsertRow = findRange.End(xlDown).Row + 1
            End If
            sourceWS.Rows(sourceRowNum).Copy
            destWS.Rows(destInsertRow).Insert xlDown
        End If
    End With
Next sourceRowNum

End Sub

Currently, It takes the whole block of information in K4:M19 on the subsheet , inserts 13 rows on the master @ A60, and copy/pastes K4:M19(sub) @ A60(master). (There are normally many blank rows that it copies over which I'm not sure how to eliminate with the current code setup.)
I'd like it to search the master sheet for specific text like:
"DESIGN; PRODUCTION/ACTUAL ORDERS"
"DESIGN; DESIGN ONLY ORDERS"
"OUTSOURCED"
"COMING UP…"

and insert the copied SourceWb rows under these keywords on the DestWb based on the information in the SourceWb row. For example, if row 4 needs Design ("Yes" in column E), the row should be inserted under "DESIGN; PRODUCTION/ACTUAL ORDERS" on the master workbook.
The DestWb keywords relate to SourceWb like so:
"DESIGN; PRODUCTION/ACTUAL ORDERS" - SourceWb, Column E: "Yes" AND Column D: <> "(DESIGN ONLY)"
"DESIGN; DESIGN ONLY ORDERS"       - SourceWb, Column D: "(DESIGN ONLY)"
"OUTSOURCED"                       - SourceWb, Column D: "(OUTSOURCED)"
"COMING UP…"                       - SourceWb, Column E: "No"

I'm thinking it will need a vlookup() and loop for each row? As I am a complete novice, I have no clue what I'm doing and all I'm good for is Frankenstein-ing multiple codes together from stackoverflow...
I appreciate any help anyone can lend me.

A: Assuming you can work out your own cases of logic (for each "DESIGN; PRODUCTION/ACTUAL ORDERS", "DESIGN; DESIGN ONLY ORDERS", "OUTSOURCED", "COMING UP…"), you could do something like this:
'untested
dim sourceWS as worksheet:  destWS = destWB.Sheets(name1)
dim destWS as worksheet:  sourceWS = sourceWB.Sheets(name2)
dim sourceRowNum as long
for sourceRowNum = 1 to 10 step 1
    with sourceWS
        dim findTerm as string
        select case true
            case .cells(sourceRowNum,5).value = "Yes"
                findTerm = "DESIGN; PRODUCTION/ACTUAL ORDERS"
            case else
                'can add other cases
        end select
    end with
    with destWS
        dim findRange as range
        set findRange = .columns(1).find(findTerm)
        if not findRange is nothing then
            dim destInsertRow as long
            if findRange.offset(1).value = "" then
                destInsertRow = findRange.Row+1
            else
                destInsertRow = findRange.end(xldown).row+1
            end if
            sourceWS.rows(sourceRowNum).copy
            destWS.rows(destInsertRow).insert xldown
        end if
    end with
next sourceRowNum

Edit1:  Verified that OP's modified code from above works... here is my use of the code, which does work:
Option Explicit

Sub PullTally()
'###
    Dim SourceWb As Workbook
    Set SourceWb = ThisWorkbook
    Dim DestWb As Workbook
    Set DestWb = ThisWorkbook
'###
    Dim destWS As Worksheet:  Set destWS = DestWb.Worksheets(1)
    Dim sourceWS As Worksheet:  Set sourceWS = SourceWb.Worksheets(2)
    Dim sourceRowNum As Long
    For sourceRowNum = 1 To 13 Step 1
        With sourceWS
            Dim findTerm As String
            Select Case True
                Case .Cells(sourceRowNum, 4).Value = "(OUTSOURCED)"
                    findTerm = "OUTSOURCED"
                Case .Cells(sourceRowNum, 5).Value = "No"
                    findTerm = "COMING UP…"
                Case .Cells(sourceRowNum, 4).Value = "(DESIGN ONLY)"
                    findTerm = "DESIGN; DESIGN ONLY ORDERS"
                Case .Cells(sourceRowNum, 5).Value = "Yes"
                    findTerm = "DESIGN;PRODUCTION/ACTUAL ORDERS"
                Case Else
                'can add other cases
            End Select
        End With
        With destWS
            Dim findRange As Range
            Set findRange = .Columns(1).Find(findTerm)
            If Not findRange Is Nothing Then
                Dim destInsertRow As Long
                If findRange.Offset(1).Value = "" Then
                    destInsertRow = findRange.Row + 1
                Else
                    destInsertRow = findRange.End(xlDown).Row + 1
                End If
                sourceWS.Rows(sourceRowNum).Copy
                destWS.Rows(destInsertRow).Insert xlDown
            End If
        End With
    Next sourceRowNum
End Sub

My destination/sheet1 output after running code:

My source/sheet2 data being used (looks like you may want to add lines for skipping blank rows):


text:
Q: Android:video as splash screen I want to play the video as splash screen.I have implement the play video but it show the default control like play,pause and seek etc.I want to remove the
   so that the after video finish I need to call the new activity.
 MediaController mc = new MediaController(this);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    video.setMediaController(mc);
    video.setVideoURI(uri);
    video.setOnCompletionListener(this);
    video.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View arg0, MotionEvent arg1) {
                Toast.makeText(getApplicationContext(), "ontouch",Toast.LENGTH_LONG).show();
                return true;
            }
        }) ;

and the main.xml

Thank in advance.

A: Disable the touchable property in the layout.xml file:
<VideoView
android:layout_width="fill_parent"
android:id="@+id/videoView1"
android:layout_height="wrap_content"
android:clickable="false"/>

Hope that helps you
Now there is a Method called
setMediaController(MediaController mCtrl)

http://d.android.com/reference/android/widget/VideoView.html#setMediaController%28android.widget.MediaController%29
You can call this method and pass the argument as MediaController.hide()
Here is a Sample Code:
MediaController controller=MediaController(Context);
controller.hide();
VideoView videoView= (VideoView) findViewById(R.id.videoView1);
videoView.setMediaController(controller);
//try passing null here as well

A: The answer was too simple
         remove the line
 video.setMediaController(mc);

because i did not want to use the control.
Thank you


text:
Q: Integral image box filtering I'm trying to compare the performance in Halide of a 2-pass, separable approach to the integral-image-based box filtering approach to gain a better understanding of Halide scheduling. I cannot find any examples of Integral Image creation in Halide where the Integral Image Function is used in the defintion of a subsequent function.
ImageParam input(type_of<uint8_t>(), 3, "image 1");

Var x("x"), y("y"), c("c"), xi("xi"), yi("yi");

Func ip("ip");

ip(x, y, c) = cast<float>(BoundaryConditions::repeat_edge(input)(x, y, c));

Param<int> radius("radius", 15, 1, 50);

RDom imageDomain(input);
RDom r(-radius, radius, -radius, radius);

// Make an integral image
Func integralImage = ip;
integralImage(x, imageDomain.y, c) += integralImage(x, imageDomain.y - 1, c);
integralImage(imageDomain.x, y, c) += integralImage(imageDomain.x - 1, y, c);

integralImage.compute_root(); // Come up with a better schedule for this

// Apply box filter to integral image
Func outputImage;

outputImage(x,y,c) = integralImage(x+radius,y+radius,c)
                + integralImage(x-radius,y-radius,c)
                - integralImage(x-radius,y+radius,c)
                - integralImage(x-radius,y+radius,c);

Expr normFactor = (2*radius+1) * (2*radius+1);
outputImage(x,y,c) = outputImage(x,y,c) / normFactor;
result(x,y,c) = cast<uint8_t>(outputImage(x,y,c));

result.parallel(y).vectorize(x,8)

I did find the following code in the tests:
https://github.com/halide/Halide/blob/master/test/correctness/multi_pass_reduction.cpp
But this example uses realize to compute the integral image as a buffer over a fixed domain and doesn't consume the definition of integral image as a function in the definition of a subsequent function.
When I run this code, I observe that:

*

*The computation of the Integral Image is extremely slow (moves my pipeline to 0 fps)

*I get an incorrect answer. I feel like I must be somehow misdefining my integral image

I also have a related question, how would one best schedule the computation of an integral image in this type of scenario in Halide?

A: My problem was in the definition of my integral image. If I change my implementation to the standard one pass definition of the integral image, I get expected behavior:
Func integralImage;
integralImage(x,y,c) = 0.0f; // Pure definition
integralImage(intImDom.x,intImDom.y,c) = ip(intImDom.x,intImDom.y,c)
                  + integralImage(intImDom.x-1,intImDom.y,c)
                  + integralImage(intImDom.x,intImDom.y-1,c)
                  - integralImage(intImDom.x-1,intImDom.y-1,c);

integralImage.compute_root();

I still have remaining questions about the most efficient algorithm/schedule in Halide for computing an integral image, but I'll re-post that as a more specific question, as my current post was kind of open-ended.
As an aside, there is a second problem in the code above in that padding of the input image is not handled correctly.


text:
Q: Module-finite extensions and reflexive modules. $\textbf{Question:}$
Let $R\rightarrow S$ be a module-finite extension of complete local rings, with $S$ Regular. Prove that if $M$ is a reflexive $R-$module such that ${\rm Ext}^i_R(M^*,S) = 0$ for $i=1,…,n-2$, (where $n=\dim R$), then $M \in {\rm add}_R(S)$.
This is an exercise in the book 'Cohen-Macaulay representations'. And I know the completeness in the condition implies that the KRS theorem  holds for module category over $R$. Therefore, it is enough to prove that $M$ is a $R-$summand of a free $S-$module, or MCM $S-$module since $S$ is regular. But I don't know how to deduce this.
The origin exercise does not describe the mean of letter '$n$'. I guess it represents $\dim R$, thus, I enclose the guess.


text:
Q: Python conditional statements def Fitness(a, b, c):
    if ((a&b&c) >= 4) & ((a+b+c) >= 13):
        return('Gold')
    if ((a&b&c) >= 3) & ((a+b+c) >= 10):
        return('Silver')
    if ((a&b&c) >= 2) & ((a+b+c) >= 07):
        return('Pass')
    else:
        return('Fail')

now the Problem is  when Fitness(2,2,5) is given, the control jumps to default ie. 'Fail'.
Where is the actual output is 'Pass'. ?

A: Use and instead of & (binary and). And don't write 07 - numbers starting with 0 may be interpreted as octal depending on your version of Python.
Together with Howard's inspiration, I'd suggest this:
def Fitness(a, b, c):
    if all(x>=4 for x in (a,b,c)) and (a+b+c) >= 13:
        return('Gold')
    if all(x>=3 for x in (a,b,c)) and (a+b+c) >= 10:
        return('Silver')
    if all(x>=2 for x in (a,b,c)) and (a+b+c) >= 7:
        return('Pass')
    return('Fail')

Also, it's sad that you're not awarding a bronze medal...

A:
Where is the actual output is 'Pass'.

No it isn't. 2 (0b010) & 2 & 5 (0b101) is 0, so the expressions will all fail even if you change the & separating the two terms to and. Perhaps you meant to use a completely different expression?

A: I'd post this as a comment to Tim Pietzcker's answer, since it's just an improvement on it, but the comment field would mess up the formatting, so I'm making it a separate answer.
def fitness(*args):
    arg_sum = sum(args)
    smallest_arg = min(args)

    if smallest_arg >= 4 and arg_sum >= 13:
        return 'Gold'
    if smallest_arg >= 3 and arg_sum >= 10:
        return 'Silver'
    if smallest_arg >= 2 and arg_sum >= 7:
        return 'Pass'
    return 'Fail'

First the important stuff:

*

*Enclosing the return value in parenthesis like in return('Gold') is not wrong per se, but will confuse the reader; return is a statement, not a function. It works nontheless because the parenthesis are in effect silently ignored. If what you wanted was in fact to return a tuple with a single string element, do return ('Gold',).

*DRY: Compute the sum and smallest element of the arguments once, and use the computed values in the if blocks, as shown above.

*Since the arguments are all treated equally and together, gather them in an *args tuple. This will also generalize the function to work with any number of arguments. If that should not be allowed, add this to the beginning of the function:
if len(args) != 3:
    raise TypeError("Need exactly 3 arguments, got {0}".format(len(args)))

Finally I'll just mention that functions should have lower_case_names according to the python style guide. Following the style guide is of course not mandatory, just recommended. :)

A: Note that
a&b&c >= 2

is different from
a>=2 and b>=2 and c>=2.

I think you mean the second one, i.e. all values are larger than two. (The first one does a binary and with all your values and compares this to the value two.)

A: def fitness(*args):
    arg_sum = sum(args)
    smallest_arg = min(args)

    if smallest_arg >= 4 and arg_sum >= 13:
        return 'Gold'
    if smallest_arg >= 3 and arg_sum >= 10:
        return 'Silver'
    if smallest_arg >= 2 and arg_sum >= 7:
        return 'Pass'
    return 'Fail'


text:
Q: 'QuerySet' object has no attribute 'pk' , how I can get the Id of the post from home view? How I can get the pk of objects in home view, I try to make personal blog with posts and this posts include comments, I tried to get the post pk in order to get the comments that related to this post but I failed
Firstly I tried to get th pk by add it in   def home_view(request, pk) but this template in home page www.mywebsite.com that's mean as I know, I cann't pass pk to the url so that's failed with me
My qustion is how I can get the Id of the post from home view?
My home View
post = []
for u in users:
  p = Account.objects.get(username=u)
            posts = p.post_set.all()

post.append(posts)
  if len(video):
 video = sorted(chain(*video), reverse=True, key=lambda video:         video.created_date)

# here I tried to get the pk
comma = Post.objects.all()
our_post = Post.objects.get(pk=comma.pk)
comment = PostCommentIDF.objects.filter(post=our_post)

My Post Model
class Post(models.Model):
 author = models.ForeignKey(Account, on_delete=models.CASCADE)
    article = models.TextField(null=True, blank=True)
    photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath)
    created_date = models.DateTimeField(auto_now_add=True)

My Comment Model
class PostCommentIDF(MPTTModel):

post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com')
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children')
author = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)

The Home View Url
path('', home_screen_view, name='home'),

A: Really not sure what's your goal by let me try it...
comma = Post.objects.all() returns QuerySet. It's something like list or array. Attribute pk is on each item in that 'array' not on array itself.
If you have QuerySet (list of your posts) you can loop over it:
comma = Post.objects.all()  # returns all posts
for post in comma:  # now post is single post
    our_post = Post.objects.get(pk=post.pk)  # now you can call 'pk' because post is single post and not QuerySet... this line is not needed because you already have post
    comment = PostCommentIDF.objects.filter(post=post)  # now get comments for that one post

EDIT:
How to use in view and template:
post_with_comments = []

comma = Post.objects.all()  # returns all posts
for post in comma:  # now post is single post
    our_post = Post.objects.get(pk=post.pk)  # now you can call 'pk' because post is single post and not QuerySet... this line is not needed because you already have post
    comment = PostCommentIDF.objects.filter(post=post)  # now get comments for that one post
    post_with_comments.append({"post": post, "comments": comment})

context = {"items": post_with_comments}
return context

and then in the template you loop over all post_with_comments
{% for item in items %}
  {{ item.post }}
  {{ item.comments.count }}
{% endfor %}


text:
Q: Conflict appcompat with sherlock library I am using the image cropper library cropper and therefore have this gradle:
 compile ('com.theartofdev.edmodo:android-image-cropper:2.3.+'){
        exclude group: 'com.android.support'
    }
I have added the exclude as i have included the actionbarsherlock lib too.
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
Now I get the error:
Error:(5) No resource identifier found for attribute 'showAsAction' in package 'blubblub'


text:
Q: Delete expired products from SQLite and treeview I want to delete elements at today's date. But this statement doesn't work.
cur.execute("DELTE FROM medicine WHERE date DATE('now') AND DATE('now', '-1 day')")
     try:
        tree.delete(cur)
    except IndexError:
        pass

A: If the column's date format is YYYY-MM-DD then you need this statement:
DELETE FROM medicine WHERE date = DATE('now')

or:
DELETE FROM medicine WHERE date = CURRENT_DATE


text:
Q: JQUERY: Change value from text input having a checkbox selected I need to change the value of a text input only if a checkbox is selected. Both inputs (text and checkbox) have the same class:

        Write your text:
        <input type="text" id="text_to_apply" name="text_to_apply" value="">
        <button type="button" id="btn_apply">Change</button>

        <form id="theform">
            <input type="text" value="1" id="one1" class="one"><input type="checkbox" id="one1_" class="one">

            <input type="text" value="1" id="one2" class="one"><input type="checkbox" id="one2_" class="one">

            <input type="text" value="1" id="one3" class="one"><input type="checkbox" id="one3_" class="one">

            <input type="text" value="1" id="one4" class="one"><input type="checkbox" id="one4_" class="one">

            <input type="text" value="2" id="two1" class="two"><input type="checkbox" id="two1_" class="two">

        </form>

I am running out of ideas. Please Help!
Thanks!!

A: Try
    $('#btn_apply').click(function() {
        var mytext = $('#text_to_apply').val();
        $('#theform').find('input:checked').each(function(){
            $(this).prev().val(mytext);
        });
    });

DEMO

A: If I got your question right - it will look like this:
    $('#btn_apply').click(function() {
        if ($('#yourCheckboxId').is(':checked')){
             $('#inputId').val('some text you want');
        }
    });

Here is fiddle http://jsfiddle.net/Goodluck/2XBcK/

A: There is no :text in jQuery that I'm aware of. Presuming your HTML stays the same, you can use the .prev() method to target the input before each input:checked.
    $('#btn_apply').click(function() {
        var mytext = $('#text_to_apply').val();
        if ($('#theform').find('input:checked')) {
            $('#theform').find('input:checked').prev('input').attr('value', mytext);
        }
    });

Fiddle: http://jsfiddle.net/willthemoor/5qmH8/


text:
Q: Access to Office 365 account "on behalf of" through EWS I need help with EWS service. I need to read inbox/sent mails of an account Office 365, the access to this account is "on behalf of" and I usually login with my domain credentials. This is the firt time I need to do this, so searching on Google I found this solution:
    static void Main(string[] args)
            {
                ExchangeService _service;

                try
                {
                    Console.WriteLine("Registering Exchange connection");

                    _service = new ExchangeService
                    {
                        Credentials = new WebCredentials("user", "pwd", "domain")
                    };

                    AutodiscoverRedirectionUrlValidationCallback validurl = new AutodiscoverRedirectionUrlValidationCallback((a) => { return true; });

                    _service.AutodiscoverUrl("email@mail.com", validurl);
                }
                catch (Exception e)
                {
                    Console.WriteLine("new ExchangeService failed with error '" + e.Message + "'. Press enter to exit:");
                    return;
                }

                // This is the office365 webservice URL
                _service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

When I run this code, the program goes up to the line "_service.AutodiscoverUrl("email@mail.com", validurl);", so it remains as "suspended", no error no timeout.
I don't know what the problem is, can anyone help me?
Thanks everyone
Nick


text:
Q: VbA Worksheet_Change doesnt recognize DELETE key on cell simple thing:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, ThisWorkbook.ActiveSheet.Range("C1")) Then
        debug.print "value changed"
        If IsEmpty(Target.Value2) Then
            debug.print "ie empty"
        else
            debug.print "is not empty"
        end if
    end if
end sub

I have added the:
debug.print "value changed"

to see if the "delete" key is triggering the Worksheet_Change() and it does NOT, it is triggered only on changing the value (or add if was empty)! But once there is something, and I select the cell and press DELETE on keyboard, nothing happens :(
what is wrong with the code?

A: Replace:
If Intersect(Target, ThisWorkbook.ActiveSheet.Range("C1")) Then

with:
If Not Intersect(Target, Range("C1")) Is Nothing Then

EDIT#1:
One possible  issue is that If expects a Boolean and Intersect() is returning a Range.  Excel is trying to interpret the Range and succeeds some of the time.


text:
Q: How to get the last 7 days from now using Moment.js? So, I have the following data in UTC format.
0: "2021-07-29T09:55:16.475Z"
1: "2021-09-01T13:21:02.652Z"
2: "2021-08-27T09:55:16.475Z"
3: "2021-08-30T13:21:02.652Z"
4: "2021-08-29T09:55:16.475Z"

And what I want is to get only the last 7 days from now and based from the given data above, it should not return the first data. For now, I only have this code which helps me to format dates and I can't seem to think on how can I achieve what I want. Thanks in advance.
 const date = concerns.map((concern) =>
    moment(concern.dateCreated).format("LL")
  );

A: const cutOffDate = moment().subtract(7, 'days');
const dates = concerns.filter((concern) => moment(concern.dateCreated) > cutOffDate
).map((concern) => moment(concern.dateCreated).format("LL"));


text:
Q: Laravel "top-down" template rendering I've got a simple problem with Laravel and/or Blade and didn't figure out how to fit this into the Laravel-paradigms:
I have a parent view which should display a list of different child-views. In my current understanding I need to go down to the list-element and "extend" the parent element. But how should I insert the sibling-templates? I need a way to render the templates "top-down" and not "bottom-up".
------ Parent template -----
group.show

    --------- List ---------
    group_assets.type-A.show
    group_assets.type-B.show
    group_assets.type-B.show
    group_assets.type-B.show
    group_assets.type-C.show
    group_assets.type-A.show

My approach was the following:
class GroupController extends Controller {
    ...

    public function show($id){
        $group = Group::find($id);

        $view = view('groups.show', [
            'group' => $group
        ]);

        $groupAssetController = new GroupAssetController();

        foreach($group->assets as $i => $asset){
            $view->with($groupAssetController->show($asset->id));
        }

        return $view;
    }

    ...
}

class GroupAssetController extends Controller{
    ...

    public function show($id){
        $asset = GroupAsset::find($id);

        return view('group_assets.' . $asset->type . '.show', [
            "asset" => $asset
        ]);
    }

    ...
}

A: You can include subviews from within your master view by using the @include directive. First you should eager-load the assets:
class GroupController extends Controller {

    public function show($id) {
        // Eager load assets
        $group = Group::with('assets')->find($id);

        return view('groups.show', [
            'group' => $group
        ]);
    }

}

Then you can include the subviews dynamically and pass the asset model that should be available to each subview:
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Master View</title>
</head>
<body>
    {{-- include subviews for each asset --}}

    @foreach($group->assets as $asset)
        @include('group_assets.' . $asset->type . '.show', ['asset' => $asset])
    @endforeach
</body>
</html>


text:
Q: Captured URL parameters in form I am using Userena and I am trying to capture URL parameters and get them to my form but I'm lost how to do this.
What I would like to do in my template is:
Free Plan

Pro Plan

Enterprise Plan

And then in my urls.py
url(r'^accounts/signup/(?P<planslug>.*)/$','userena.views.signup',{'signup_form':SignupFormExtra}),

Then, ideally, I'd like to use that planslug in my forms.py to set the user plan in the profile.
I'm lost how to get the captured URL parameter into the custom form. Can I use the extra_context, do I have to override the Userena signup view?

A: If you use class based views, you can overwrite the def get_form_kwargs() method of the FormMixin class. Here you can pass any parameters you need to your form class.
in urls.py:
url(r'^create/something/(?P<foo>.*)/$', MyCreateView.as_view(), name='my_create_view'),

in views.py:
class MyCreateView(CreateView):
    form_class = MyForm
    model = MyModel

    def get_form_kwargs(self):
        kwargs = super( MyCreateView, self).get_form_kwargs()
        # update the kwargs for the form init method with yours
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

in forms.py:
class MyForm(forms.ModelForm):

    def __init__(self, foo=None, *args, **kwargs)
        # we explicit define the foo keyword argument, cause otherwise kwargs will
        # contain it and passes it on to the super class, who fails cause it's not
        # aware of a foo keyword argument.
        super(MyForm, self).__init__(*args, **kwargs)
        print foo  # prints the value of the foo url conf param

hope this helps :-)

A: You can access the url in your template using -
{% request.get_full_path %}

(see the docs for more info).
However if you just want to get the planslug variable then pass it from the view to the template and access it in the template (it's available in the view because it's a named parameter in the url) -
def signup(request, planslug=None):
    #
    render(request, 'your_template.html', {'planslug':planslug}

and then in your template you get it with -
{% planslug %}

If you're using class based views then you'll need to override get_context_data to add the planslug variable to your context before you pass it to the template-
def get_context_data(self, *args, **kwargs):
    context = super(get_context_data, self).get_context_data(*args, **kwargs)
    context['planslug'] = self.kwargs['planslug']
    return context


text:
Q: Is it possible to dispatchEvent() a mouse click to a  element? Basically I'm trying to dispatch a custom made mouse click event to a text input element using the following code (see this jsFiddle):
function simulateClick(id) {
    var clickEvent = document.createEvent("MouseEvents");
    clickEvent.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
        false, false, false, false, 0, null);

    var element = document.getElementById(id);
    element.dispatchEvent(clickEvent);
}

When I run that code on a type="checkbox" element it works perfectly fine but it doesn't work at all when called on a type="text" element.
Now here's the definition of initMouseEvent() on MDN:
event.initMouseEvent(type, canBubble, cancelable, view,
                 detail, screenX, screenY, clientX, clientY,
                 ctrlKey, altKey, shiftKey, metaKey,
                 button, relatedTarget);

So in the above example screenX, screenY, clientX and clientY would all be 0 (still, the above code works perfectly fine with checkboxes regardless of their position). I tried capturing a real event and passing the screen and client coordinates to the cusom made event, to no avail.
I though maybe text input elements ignore custom mouse events due to security reasons, but then element.focus() should't work either, which it does.
Any ideas or insights would be greatly appreciated!

A: As far as i can tell your code works fine. However it does not focus the input field as you may think, but the event is fired on the input field just fine, as seen in this fiddle: http://jsfiddle.net/ENvZY/
Note: the code is not crossbrowser compatible though, it fails in ie8.
Consider using a good crossbrowser library like jQuery instead of going the native DOM way - the wheel exists and works perfectly, reinventing it is a waste of time :)


text:
Q: Symfony2 app, MongoDB: Count all records matching criteria In my controller I'm fetching limited number of objects (for pagination) like this:
    $dm   = $this->get('doctrine_mongodb');
    $repo = $dm->getRepository('AcmeMyBundle:MyDocument');

    $criteria = array(
        'field1'    => 'value1',
        'field1'    => 'value1',
    );

    $logs = $repo->findBy(
        $criteria,                      /* criteria */
        array($field => $direction),    /* sort */
        $limit,                         /* limit */
        (($page-1)*$limit)?:null        /* skip */
    );

Now I like to get total number of records that meet the $criteria.
I was trying to count it like this:
$count = $repo->createQueryBuilder('MyDocument')
    ->count()->getQuery()->execute();

But it counts all records in collection. How can I apply $criteria to that counting query?
I need result as native MongoDB db.MyDocument.find({'field2': "value1", 'field2': "value2"}).count()

A: Done it like this:
    $countQuery = $repo
        ->createQueryBuilder('MyDocument')
        ->requireIndexes(false)
        ;

    foreach(array_filter($criteria) as $field=>$value){
        $countQuery->field($field)->equals($value);
    }

    $count = $countQuery->count()->getQuery()->execute();


text:
Q: Displaying unknown amount of data to screen I have a sqlite database which contains multiple messages.
Each message has a

*

*Title

*Body

*Importance level (0/1/2)

*Possible calander _id

I want to display them to the screen in a scrollable list. Each list item can be clicked on which will then start another activity to edit the message.
I don't want direct code on how to do it, I'd prefer suggestions on how to do it so I can learn myself. If I need to give any extra info please ask.

A: You need to use adapter in your case CursorAdapter would be appropriate. There are many tutorials on internet about CursorAdapter and using it alongside with SQLite:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
https://coderwall.com/p/fmavhg/android-cursoradapter-with-custom-layout-and-how-to-use-it
A general note about Adapters is that they are a mean to transfer your data to appropriate View so you can populate your ListView, GridView, ... with the customized data. But this need a whole tutorial. You can also look to see how to work with different type of views which allow to be populated with Adapters.


text:
Q: Reading Excel file on condition Hi I'm writing an WinForm application and I want to read an excel file. My excel is something like this:
------------------------------------------------------
first_name |last_name|ID      |Skill   |exam_date |certification_number|
john       |  smith  |12345678|engineer|2013/12/12|3543546647
john       |  smith  |12345678|electronic|2013/07/12|35477776647
.....
.....

because my excel doesn't have primary key ,as you can see for one person I can have several rows(up to 20) which the first 3 columns are the same .
I wrote this code to read excel but it reads just one row .How can I read all rows with the same ID?
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\book3.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
        DataSet ds = new DataSet();
        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [SHEET1$]", ConnectionString);
        adapter.Fill(ds);

        DataRow dataRow = (from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr).FirstOrDefault();

Thanks in advance

A: Your FirstOrDefault() only picks the 'First'
try this:
IEnumerable<DataRow> dataRows = (from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr);
foreach (DataRow dataRow in dataRows)
{
      // do stuff with current dataRow
}

A: var query = from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr;

foreach (DataRow dataRow in query.ToList())
{
      // do something with dataRow
}

A: In my C# applications I use the EPPLUS library (http://epplus.codeplex.com/)
It is really good and fast I would say.
Here is my code to open a sheet of a file using EPPLUS and load the data into a DataTable:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Drawing.Chart;
using System.Xml;

public class ProjectLoad {

        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        public void Load ( string filePath ) {

            // Get the file we are going to process
            FileInfo existingFile = new FileInfo( filePath );

            try {
                if ( existingFile.Exists == true ) {
                    // Open and read the XlSX file.
                    using ( ExcelPackage package = new ExcelPackage( existingFile ) ) {
                        // Get the work book in the file
                        ExcelWorkbook workBook = package.Workbook;
                        if ( workBook != null ) {
                            if ( workBook.Worksheets.Count > 0 ) {

                                // read some data
                                int sheet_number = 0;
                                DataTable table = load_sheet_toDataGrid( workBook.Worksheets[sheet_number] );
                            }
                        }
            } catch ( System.IO.IOException ) {
                //error message
            }

        }

        /// <summary>
        /// loads the content of a sheet into a datatable
        /// </summary>
        /// <param name="currentWorksheet"></param>
        /// <returns></returns>
        private DataTable load_sheet_toDataGrid ( ExcelWorksheet currentWorksheet ) {
            DataTable dt = new DataTable( );

            int rows = currentWorksheet.Dimension.End.Row;
            int cols = currentWorksheet.Dimension.End.Column;

            //Add columns
            for ( int c = 0 ; c < cols ; c++ ) {
                dt.Columns.Add( currentWorksheet.Cells[0 + 1 , c + 1].Value.ToString( ) );
            }

            //add values
            for ( int r = 1 ; r < rows ; r++ ) {
                object[] ob = new object[cols];
                for ( int c = 0 ; c < cols ; c++ ) {

                    double value;
                    bool isDouble = Double.TryParse( currentWorksheet.Cells[r + 1 , c + 1].Value.ToString( ) , out value );

                    bool isDate = false;
                    DateTime date = new DateTime( );
                    if ( c == 0 && !isDouble ) {
                        isDate = DateTime.TryParse( currentWorksheet.Cells[r + 1 , c + 1].Value.ToString( ) , out date );
                    }

                    if ( isDouble ) {
                        ob[c] = value;
                    } else if ( isDate ) {
                        ob[c] = date;
                    } else {
                        ob[c] = currentWorksheet.Cells[r + 1 , c + 1].Value;
                    }
                }
                dt.Rows.Add( ob );
            }

            return dt;
       }
}


text:
Q: C++ Parsing a line out of a large file I have read an entire file into a string from a memory mapped file Win API
CreateFile( "WarandPeace.txt", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 )

etc...
Each line is terminated with a CRLF. I need to find something on a line like "Spam" in the line "I love Spam and Eggs" (and return the entire line (without the CRLF) in a string (or a pointer to the location in the string) The original string cannot be altered.
EDITED:
Something like this:
string ParseStr( string sIn, string sDelim, int nField )
{
    int match, LenStr, LenDelim, ePos, sPos(0), count(0);
    string sRet;

        LenDelim = sDelim.length();
        LenStr   = sIn.length();
        if( LenStr < 1 || LenDelim < 1 ) return ""; // Empty String
        if( nField < 1 ) return "";
        //=========== cout << "LenDelim=" << LenDelim << ", sIn.length=" << sIn.length() << endl;

        for( ePos=0; ePos < LenStr; ePos++ ) // iterate through the string
        { // cout << "sPos=" << sPos << ", LenStr=" << LenStr << ", ePos=" << ePos << ", sIn[ePos]=" << sIn[ePos] << endl;
            match = 1; // default = match found
            for( int k=0; k < LenDelim; k++ ) // Byte value
            {
                if( ePos+k > LenStr ) // end of the string
                    break;
                else if( sIn[ePos+k] != sDelim[k] ){ // match failed
                    match = 0; break; }
            }
            //===========

            if( match || (ePos == LenStr-1) )  // process line
            {
                if( !match ) ePos = LenStr + LenDelim; // (ePos == LenStr-1)
                count++; // cout << "sPos=" << sPos << ", ePos=" << ePos << " >" << sIn.substr(sPos, ePos-sPos) << endl;
                if( count == nField ){ sRet = sIn.substr(sPos, ePos-sPos); break; }
                ePos = ePos+LenDelim-1; // jump over Delim
                sPos = ePos+1; // Begin after Delim
            } // cout << "Final ePos=" << ePos << ", count=" << count << ", LenStr=" << LenStr << endl;
        }// next

    return sRet;
}

If you like it, vote it up. If not, let's see what you got.

A: If you are trying to match a more complex pattern then you can always fall back to boost's regex lib.
See: http://www.boost.org/doc/libs/1_41_0/libs/regex/doc/html/index.html
#include <iostream>
#include <string>
#include <boost/regex.hpp>

using namespace std;

int main( )
{
   std::string s;
   std::string sre("Spam");
   boost::regex re;

   ifstream in("main.cpp");
   if (!in.is_open()) return 1;

   string line;
   while (getline(in,line))
   {
      try
      {
        // Set up the regular expression for case-insensitivity
        re.assign(sre, boost::regex_constants::icase);
      }
      catch (boost::regex_error& e)
      {
        cout << sre << " is not a valid regular expression: \""
          << e.what() << "\"" << endl;
         continue;
      }
      if (boost::regex_match(line, re))
      {
         cout << re << " matches " << line << endl;
      }
    }
}

A: Do you really have to do it in C++? Perhaps you could use a language which is more appropriate for text processing, like Perl, and apply a regular expression.
Anyway, if doing it in C++, a loop over Prev_delim_position = sIn.find(sDelim, Prev_delim_position) looks like a fine way to do it.

A: system("grep ....");


text:
Q: Maintain formatting when emailing a generated .PDF from a DIV populated using regex I am unable to generate a PDF from a DIV for emailing to a client while maintaining formatting and variables changed using Regex. Essentially, the PDF file sends as it should attached, but the formatting is messed up (i.e., break space, etc.) and the variables are showing up as {input1}, {input2}, etc, even after being generated.
I've tried multiple other answers on the site I found, including CakePHP and it doesn't work for me.
indexing.html:
  For some reason, I can't post HTML code. Basically it's just a Div with the id 'string1' with some text in between which includes {input1}.
*I used regex to replace {input1} with user input.
pdf.php:

require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf extends Dompdf{

public function __construct(){
    parent::__construct();
}
}

?>

PHP:

$message = '';

$html= file_get_contents("indexing.html");
$dom = new DOMDocument;
$dom->loadHTML($html);
$div = $dom->getElementById('string1');
$result = $dom->saveHTML($div);

if(isset($_POST["action"]))
{
include('pdf.php');
$file_name = md5(rand()) . '.pdf';
$html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
$pdf = new Pdf();
$pdf->load_html($result);
$pdf->render();
$file = $pdf->output();
file_put_contents($file_name, $file);

require 'class/class.phpmailer.php';
$mail = new PHPMailer();
#$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host       = ''; // Specify main and backup SMTP servers
#$mail->SMTPAuth   = true; // Enable SMTP authentication
$mail->Username   = ''; // SMTP username
$mail->Password   = ''; // SMTP password
#$mail->SMTPSecure = 'SSL'; // Enable SSL
$mail->Port       = 587; // TCP port to connect to
$mail->setFrom("", "");
$mail->addAddress("");
$mail->isHTML(true);
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Generate Legal Document'; //Sets the Subject of the message
$mail->Body = 'Please see attached PDF File.'; //An HTML or plain text message body
if($mail->Send())   //Send an Email.
Return true on success or false on error
{
$message = '<label class="text-success">Sent successfully...
</label>';
}
unlink($file_name);
header("Location: indexing.html");
}

The PDF file sends as it should attached, but the formatting is messed up (i.e., break space, etc.) and the variables are showing up as {input1}, {input2}, etc, even after being generated...


text:
Q: Android display an image based on a calculation I have an EditText box where the user inputs a number and 3 TextViews that display the result of some calculations. Instead of showing "2" as the result, I would like to show a specific picture based on the result. i.e. "1"=pic1 "2"=pic2....

A: If you need to load a picture from the /sdcard based on the result of the calculations, then this is one way of doing it:

int calculationsResult = ... //do your calculations here
String fileName = "/sdcard/path_to_your_pictures/pic" + calculationsResult + ".jpg"; Bitmap image = BitmapFactory.decodeFile(fileName);
ImageView resultImageHolder = findViewById(R.id.result_holder_id);
resultimageHolder.setImageBitmap(image);
Hope this helps!

A: Assuming all results are integers, you could do it like Todor suggests (by giving each picture a predictable title that you can use). Another way of getting the right filename, though, would be to simply use a HashMap to describe what image should be shown for what result.
Map<String, Integer> hm = new HashMap<String, Integer>();

// Put elements to the map
hm.put(new Integer(2), "number_two.png");
hm.put(new Integer(20), "the_number_is_twenty.png");
hm.put(new Integer(42), "douglas_adams.png");

And when you have done your calculation, you look up in the HashMap to find the filename.
Integer result = 3+1-2; // Your calculation here

String filename = "dummy.png"; // When all else fails
if (hm.containsKey(result))
{
        filename=(String)hm.get(result);
}


text:
Q: Is it possible to using Type Inference for the first parameter and specify another type This is a simple contrived example, but hopefully will illustrate my query.
public class Test
{
    public string Name = "test";
}

public static class Ext
{
     public static Test ConvertToTest<T1>(this T1 source)
     {
         return new Test();
     }

     public static T2 Convert<T1,T2>(this T1 source) where T2 : new()
     {
         return new T2();
     }
}

ConvertToTest only needs one Type, so the following compile
    Ext.ConvertToTest<string>("hello");
    "hello".ConvertToTest();

The last uses type-interfence and this means it also works with anonymous classes, eg
    var anon = (new { Name = "test" }) ;
    anon.ConvertToTest();

However this is hardcoded to always use the class Test, whereas I want to be able to specify the type as in the second method
I can write
   Ext.Convert<string, Test>("hello");

and this compiles, because I know both types at compile time, but I can't use it with anonymous classes, and I can't find a way of using type-inference plus the extra Type
It would be nice if I could do something like
    anon.Convert<,Test>()  ;

and the compiler would know to use inference for the first type (which isn't specified) and use Test as the second type.
Is there any way around this issue?

A: You can't do what you're asking on a single method, but if you're clever and willing to define a couple of different classes you should be able to make syntax like this possible:
var test = Ext.Convert("hello").To<Test>();

Just make Convert be based on a single generic type, and have it return a generic type based on that:
public Converter<T> Convert<T>(T source)
{
    return new Converter<T>(source);
}

Then add a method to the type it returns which serves as a basic wrapper for your original method:
public class Converter<T>
{
    T _source;
    internal Converter(T source)
    {
        _source = source;
    }
    public T2 To<T2>()
    {
        return Ext.Convert<T, T2>(_source);
    }
}

A: There is a way to do what you want. You use a template pattern - it's a little bit of a kludge but it allows you to infer both types. It can also be use to infer anonymous types.
Here it is:
public static T2 Convert<T1,T2>(this T1 source, Func<T2> template)
    where T2 : new()
{
    return new T2();
}

You can call it like this:
var anon = (new { Name = "test" }) ;
anon.Convert(() => new Test());

Which isn't too far from your pseudo-code.


text:
Q: convert from string to integer of apiLink value in Javascript i have an apiLink for pdf open.
i want to convert companyValue and empValue into integer format.
`https://mobileapi.unq.co.il/api/TlushSachar/GetPrintTlushMisradHinuch?company=${companyValue}&year_month=${yearMonthValue}&employee=${empValue}`)

How can i convert those two value from string to integer?

A: Try it:
`https://mobileapi.unq.co.il/api/TlushSachar/GetPrintTlushMisradHinuch?company=${parseInt(companyValue)}&year_month=${yearMonthValue}&employee=${parseInt(empValue)}`)

You can see: https://www.w3schools.com/js/js_number_methods.asp

A: you can use parseInt() Method
for reference see this

A: use the following method to convert the string to a number
Number(companyValue)
Number(empValue)


text:
Q: How to get MongoDB ObjectID as hex string into the renderer I'm missing something here. I want the hex string in the renderer. So I wrote a Mongo Util function that returns the hex string. That works fine. Then I wrote a handler / invoke pair to pass the object and return the hex string. The handler does receive the hex string. But at the renderer, I see the object back.
How to get the hex string at the renderer?
//main.js
ipcMain.handle('ObjectIDtoHexString', async (event,args) => {
  const result = mongoUtil.ObjectIDtoHexString(args)
  console.log(result) //as string
  return result
})

//renderer.js
console.log(JSON.parse(data.value)) //as Object
ipcRenderer.invoke('ObjectIDtoHexString', JSON.parse(data.value)).then(console.log) //as object ??

//mongoUtil.js
const { ObjectID } = require( 'mongodb' )

function ObjectIDtoHexString (object) {
  let hexString = ''
  Object.values(object.id).forEach(elem =>{
    const result = elem.toString(16)
    if(result.length === 2) {
      hexString += result
    } else {
      hexString += "0" + result
    }
  })
  const id = new ObjectID(hexString)
  console.log(id) //as string
  return id
}


text:
Q: Does VS C++ Character Set compiler setting influence character encoding? Are there any direct consequences of toggling between Unicode, MBCS, and Not Set for the VS C++ compiler settings Configuration Properties->General->Character Set, apart from the setting of the _UNICODE, _MBCS and _T macros (which then, of course, indirectly has consequences through the generic text mappings for string functions)?
I am not expecting it to, but since the documentation says "Tells the compiler to use the specified character set", I'd like to be certain that, specifically, it doesn't have any influence on how any literal non-ASCII text put into strings or wstrings is encoded? (I am aware that non ASCII literals in the source is not portable, but am maintaining a solution where this is used heavily.)
Thanks in advance.

A: No, it only affects the macro definitions.  Which in turn can have wide-ranging effects on anything from <tchar.h> or the Windows T string pointer types (LPTSTR etc).
If you use any non-ASCII codes in your string literals then you depend heavily on the way the compiler decodes the text in your source code file.  The default encoding it assumes is your system code page as configured in Control Panel + Regional and Language options.  This will not work well when your source code file ever strays too far away from your machine.  Specifying utf8 with a BOM is wise so this is never a problem.  In the IDE that's set with Save As, arrow on the Save button, "Save with encoding", pick 65001.  Support for utf8 encoded source code files is spotty in older versions of C++ compilers.

A: For unadorned strings, C++ follows C: it's ASCII. If you wrap them with anything, the game changes.
C++0x standardises Unicode strings. UTF in particular. This is a new feature.


text:
Q: manipulation after loading non http:// url scheme I am trying to create a program that loads an application then can manipulate the application as if it were another UIWebView (a.k.a. I want to execute javascript). I figured this may be possible because you can load it using a webView and a URL scheme. However, I can't seem to manipulate the application at all once it is loaded. This is closely tied to the fact that for http:// schemes webViewDidFinishLoad is being successfully called, but for non http:// schemes webViewDidFinishLoad is not being called..
Here is some of the code I am using:
let fb:NSURL! =  NSURL(string:"fb://feed");
webView.loadRequest(NSURLRequest(URL:fb));

...
The following function is called only on http:// schemes.
func webViewDidFinishLoad(webView: UIWebView) {

    print("hellO");
}

Note: It is successfully loading the Facebook feed (but the finished loading method

A: Unfortunately, this is not possible.

*

*For security reasons, iOS apps can not manipulate other apps, like you could with a webpage inside of a web view you controlled.

*For technical reasons, injected JavaScript could not be used to manipulate a typical native iOS app, as most apps are not web-based.

The custom url schemes that iOS apps can provide are only capable of launching the app (switching away from your app; not inside of the web view), and providing functionality published by the other app (such as jumping into Facebook's feed in your example).
webViewDidFinishLoad is not being called because iOS is switching from your app to the Facebook app.


text:
Q: error C2660: 'MouseListener::MousePressed' : function does not take 4 arguments Im working on an c++ pseudo graphic button for a school assignment.
I use the observer pattern.
in Button.cpp:
void Button::notify()
{
    for (int iterator = 0; iterator < listeners.size(); iterator++)
    {
        listeners[iterator]->MousePressed(*this, x, y, isLeft);
    }
}

as you can see the MousePressed function receive 4 arguments but i get:

function does not take 4 arguments

in Button.h:
struct MouseListener
{
    virtual void MousePressed(Button &b, int x, int y, bool isLeft) = 0;
};

class Button : public Label
{
public:

    vector <MouseListener*> listeners;
.
.
.

in main:
struct MyListener : public MouseListener
{
    MyListener(iControl &c) : _c(c) { }
    void  MousePressed(Button &b, int x, int y, bool isLeft)
    {
        _c.setForeground(Color::Red);
    }
private:
    iControl &_c;
};

int main(VOID)
{

errors:

*

*Error    2   error C2061: syntax error : identifier 'Button' c:\users\gonen\unitedproj\unitedproj\Button.h   14  1   unitedProj

*Error    4   error C2061: syntax error : identifier 'Button' c:\users\gonen\unitedproj\unitedproj\Button.h   14  1   unitedProj

*Error    5   error C2660: 'MouseListener::MousePressed' : function does not take 4 arguments C:\Users\Gonen\unitedProj\unitedProj\Button.cpp 24  1   unitedProj

when the first two are for the declartion in main and the last is in the use of the function in Button.cpp.
help? when im standing with the mouse curser on the function in Button.cpp i get:

void MouseListener::MousePressed(Button &b,int x,int y, bool isLeft)

I just need this to work so i can move on and let the rest of the group members to use the button in the controls they implementing... and move on to the next i need to do :-(
edit: thank you for the fast answer.
I tried to do what you asked. now i get:

*Error    3   error LNK2019: unresolved external symbol main referenced in function __tmainCRTStartup C:\Users\Gonen\unitedProj\unitedProj\MSVCRTD.lib(crtexe.obj)    unitedProj

A: Button is not declared at the point where MousePressed is declared, so it cannot be used. I suggest you should use forward declaration.
class Button; // add this line

struct MouseListener
{
    virtual void MousePressed(Button &b, int x, int y, bool isLeft) = 0;
};

class Button : public Label
{
public:

    vector <MouseListener*> listeners;
.
.
.


text:
Q: Issue in reading text corpus for Glove word embeddings Implementation I am trying to train my text corpus using Glove implementation as mentioned in this link https://github.com/hans/glove.py/blob/master/glove.py.I have created a text-corpus of words separated by a single space.The size of the file is 3.6 GB.I am getting this error when I am trying to load the file.
2017-08-09 12:51:47,848 Fetching vocab..
Traceback (most recent call last):
  File "Glove_python_bbc.py", line 378, in <module>
    main(parse_args())
  File "Glove_python_bbc.py", line 347, in main
    vocab = get_or_build(arguments.vocab_path, build_vocab, corpus)
  File "Glove_python_bbc.py", line 83, in get_or_build
    obj = msgpack.load(obj_f, use_list=False, encoding='utf-8')
  File "msgpack\_unpacker.pyx", line 164, in msgpack._unpacker.unpack (msgpack/_unpacker.cpp:2622)
  File "msgpack\_unpacker.pyx", line 143, in msgpack._unpacker.unpackb (msgpack/_unpacker.cpp:2143)
msgpack.exceptions.ExtraData: unpack(b) received extra data.

Help me read the file.Thanks


text:
Q: Show that $Var(\theta_1)>Var(\theta_2)$.

I calculated that
    $$
Var(\theta_1)=\frac{2\sigma^2}{(x_n-x_1)^2},~~~~~Var(\theta_2)=\frac{\sigma^2}{\sum_{i=1}^{n}(x_i-\overline{x})^2}.
$$
    Now I have to show that for $\sigma^2 >0$ and $\overline{x}\neq\frac{(x_1+x_n)}{2}$ it is
    $$
Var(\theta_1) > Var(\theta_2).
$$

I have to show that it is
$$
\frac{2\sigma^2}{(x_n-x_1)^2} > \frac{\sigma^2}{\sum_{i=1}^{n}(x_i-\overline{x})^2}.
$$
Do you have an idea how to show that?
Unfortunately, I have not.
Edit:
I've already tried to show that
$$
Var(\theta_2)/Var(\theta_1)<1,
$$
i.e. that
$$
\frac{(x_n-x_1)^2}{\sum_{i=1}^{n}(x_i-\overline{x})^2}=\frac{x_1^2+x_n^2-2x_1x_n}{\sum_{i=1}^{n}x_i^2-n\overline{x}^2}<1
$$
but with no success.

A: We wish to show that
$$ \frac{2\sigma^2}{(x_1 - x_n)^2} \geq \frac{\sigma^2}{\sum_{i=1}^n (x_i - \bar{x})^2} $$
Cancelling the sigmas and inverting the fractions shows that the desired result is
$$ \sum_{i=1}^n (x_i - \bar{x})^2 \geq \frac{1}{2}(x_1 - x_n)^2.$$
Now, in order to avoid typing $\bar{x}$ all over the place, let's define $y_i = x_i - \bar{x}$. We then have $y_1 - y_n = x_1 - x_n$, and the desired result is
\begin{align*}
\sum_{i=1}^n y_i^2 &\geq \frac{1}{2}(y_1 - y_n)^2\\ &= \frac{1}{2}(y_1^2 + y_n^2 - 2y_1y_n).
\end{align*}
Subtracting $y_1^2$ and $y_n^2$ from both sides yields that we want to show
\begin{align*}
\sum_{i=2}^{n-1} y_i^2 &\geq -\frac{1}{2}(y_1^2 + y_n^2 + 2y_1y_n)\\
&= -\frac{(y_1+y_n)^2}{2},
\end{align*}
which is trivially true as the left hand side is a sum of non-negative terms, and must therefore be greater than zero.
For $\bar{x} \neq \frac{1}{2}(x_1 + x_n)$ we see that the right hand side is negative, and the inequality is strict.