text:
Q: IntegrityError when adding null value to foreign key using web2py I am receiving an IntegrityError from web2py when trying to insert a record into a table named Foods. The table has a foreign key to Recipes, but I would like to add a row without a recipe_id.
<class 'gluon.contrib.pymysql.err.IntegrityError'>((1452, u'Cannot add or update a child row: a foreign key constraint fails (`pymeals`.`foods`, CONSTRAINT `foods_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE)'))

This is my table
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| name      | varchar(255) | YES  |     | NULL    |                |
| recipe_id | int(11)      | YES  | MUL | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

I have defined the table in web2py using the following code:
db.define_table('foods',
                Field('name'),
                Field('recipe_id', db.recipes, required=False, notnull=False, requires=None))

I believe the problem I am having lies with web2py as I can insert into the Foods table directly from the mysql command line prompt without specifying a recipe_id.
Am I missing something here? I'm new to MySQL and web2py :(

A: Make sure your Foods and Recipes have same engines. If you have different engines, then this problem will be occured.
Eg: Foods (MyISAM) and Recipes (InnoDB) will give error.


text:
Q: apt-get upgrade holds back a kernel update. What are the official instructions for applying updates on Debian 9? I saw the following on Debian 9 "stretch":
# apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages have been kept back:
  linux-image-marvell
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.

An update does not install, despite this command being an official way to update Debian according to the "Securing Debian Manual".  (Snapshot at time of reading here).
By contrast, both aptitude and the newer apt command are prepared to install it.  That said, this particular version is not a security update.  I understand that apt and potentially aptitude have different defaults.  I would like to ask how deliberate this behaviour on Debian's part...
The Securing Debian Manual lists aptitude first, when describing how to apply updates.  And I know apt has some changed defaults that are supposed to be more user-friendly.  Looking carefully at the current Debian Installation Guide, it is pointing new users to apt or aptitude.  I think all the example commands now reference apt, not apt-get.
My starting assumption is that security updates to the kernel would not be held back by an update method endorsed by the Debian Security Manual.  (Let me know if I assume wrongly :-).  But I want to make sure I understand how to update my Debian system.
Questions

*

*If I want to get the defaults that modern Debian is setting up for new users, I'm being recommended to train my fingers to type apt instead of apt-get.  Right?

*The previous Installation Guide (for Debian 8) references apt-get, as does the documentation for upgrading from Debian 8 to Debian 9.  So very broadly, I guess the safest option is not to use apt before the Debian 8 -> Debian 9 transition?

*Is there a widely known case or cases that you would like to suggest I watch out for, where the current solution is to use apt-get for some task?

*Does Debian have a comment somewhere about the choice to make apt more eager to apply updates, which specifically confirms there is is distinction of security and non-security updates?

*On a slightly different angle, is there any information about Debian's choice to arrange a (non-security) kernel update like this, that avoids them being applied with the normal configuration used by apt-get on my system?

Details of this update
# apt-cache policy linux-image-marvell
linux-image-marvell:
  Installed: 4.9+80+deb9u4
  Candidate: 4.9+80+deb9u5
  Version table:
     4.9+80+deb9u5 500
        500 http://ftp.uk.debian.org/debian stretch/main armel Packages
 *** 4.9+80+deb9u4 500
        500 http://security.debian.org stretch/updates/main armel Packages
        100 /var/lib/dpkg/status

Version of "apt-get" used
# apt-cache policy apt
apt:
  Installed: 1.4.8
  Candidate: 1.4.8
...

Different behaviour with different update methods
# aptitude upgrade
Resolving dependencies...
The following NEW packages will be installed:
  linux-image-4.9.0-7-marvell{a}
The following packages will be upgraded:
  linux-image-marvell
1 packages upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/21.9 MB of archives. After unpacking 91.2 MB will be used.
Do you want to continue? [Y/n/?] n
Abort.

# apt upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following NEW packages will be installed:
  linux-image-4.9.0-7-marvell
The following packages will be upgraded:
  linux-image-marvell
1 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/21.9 MB of archives.
After this operation, 91.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] n
Abort.

A: First, I'll start by explaining the behaviour you're seeing. By default, apt-get is very conservative and won't install new packages when running upgrade, only dist-upgrade (this can be changed with the --with-new-pkgs option). apt on the other hand will (it enables the APT::Get::Upgrade-Allow-New option by default), as will aptitude (which has a different resolution algorithm anyway). Since the kernel went through an ABI bump, upgrading it involves installing a new package...
Note too that strictly speaking you're not getting this kernel update as a security fix, but as part of last weekend's 9.5 point release. That's neither here nor there though since the priorities are the same. (You're aware of this already, I mention this for other readers.) Security updates to the kernel can involve ABI bumps, so this situation can arise with security updates as well as point-release updates; the distinction, as far as the kernel packages in Debian are concerned, is mostly one of opportunity and timing, since all kernel updates are security updates anyway.
Now to answer your questions:

*

*apt is now the recommended APT front-end, yes, at least for interactive use; it's supposed to have user-friendlier defaults (compared with apt-get). Both tools use the same algorithms and apt-get can be configured to behave like apt; run apt-config dump | grep Binary::apt to see the specific settings apt enables. If you prefer aptitude you can keep on using that too.

*In Debian 8, as far as I can tell, apt is exactly equivalent to apt-get, so you can use it too; apt came to the forefront with Debian 9 following work by its developers to make it more useful as a user-facing tool. The Debian FAQ suggests using apt instead of apt-get and apt-cache starting with Debian 8 (Jessie). (I see it gets the description of apt update slightly wrong.)

*The current recommendation is to avoid apt in scripts since its interface may change. Apart from that, there shouldn't be any scenarios where you'd need apt-get rather than apt.

*apt doesn't distinguish between security and non-security updates, unless you configure it to do so.

*I'm not sure it's a conscious decision... The last update to the Securing Debian Manual is quite a bit older than Debian 9. Note that, when using apt-get, the Debian FAQ refers to apt-get dist-upgrade to keep a Debian system up-to-date. The FAQ is also older than Debian 9, but was updated more recently.

redpajama_set_name: RedPajamaStackExchange


text:
Q: prove that $\sum_{cyc}\frac{a(b^2+c^2)}{a^2+bc}\ge 3$
if $a,b,c$ are positive prove $$\sum_{cyc}\frac{a(b^2+c^2)}{a^2+bc}\ge 3$$ given $ab+bc+ca=3$

My try:using  AM-GM and Titu's lemma :
$$\sum_{cyc}\frac{a(b^2+c^2)}{a^2+bc}\ge 2\sum_{cyc}\frac{abc}{a^2+bc}\ge  \frac{18abc}{a^2+b^2+c^2+ab+bc+ca}$$
But $a^2+b^2+c^2+ab+bc+ca\le 6abc$ need not be true!
I am stuck

A: Let $a+b+c=3u$, $ab+ac+bc=3v^2$, where $v>0$ and $abc=w^3$.
Thus, our inequality is equivalent to $f(w^3)\leq0$, where $$f(w^3)=
(10u+8v)w^6+9(6u^4-7u^2v^2+3u^3v-6uv^3-v^4)w^3-81u^3v^4+81uv^6+27v^7.$$
Since $10u+8v>0$, we see that $f$ is a convex function.
Thus, it's enough to prove our inequality for an extreme value of $w^3$,
which  by $uvw$ happens in the following cases:

*

*$w^3\rightarrow0^+$.

Let $c\rightarrow0^+$.
Thus, we need to prove that:
$$\frac{3b}{a^2}+\frac{3a}{b^2}\geq3,$$ where $ab=3,$ which is true by C-S:
$$\frac{3b}{a^2}+\frac{3a}{b^2}=3\left(\frac{b^2}{a^2b}+\frac{a^2}{b^2a}\right)\geq\frac{3(a+b)^2}{ab(a+b)}=a+b\geq2\sqrt{ab}=2\sqrt3>3.$$
2. Two variables are equal.
Let $b=a$.
Thus, $$c=\frac{3-a^2}{2a}$$ and we need to prove that:
$$(a-1)^2(7a^6+9a^5-9a^4-36a^3-9a^2+27a+27)\geq0,$$  which is true.
Can you end it now?

A: Using known inequality $(x+y+z)^2 \geqslant 3(xy+yz+zx),$ we have
$$\left[\sum \frac{a(b^2+c^2)}{a^2+bc}\right] ^2 \geqslant 3 \sum \frac{ab(a^2+c^2)(b^2+c^2)}{(a^2+bc)(b^2+ca)}.$$
Therefore, we need to prove
$$\sum \frac{ab(a^2+c^2)(b^2+c^2)}{(a^2+bc)(b^2+ca)} \geqslant ab+bc+ca,$$
equivalent to
$$abc\left[\frac{a(a-b)(a-c)}{(b^2+ca)(c^2+ab)}+\frac{b(b-c)(b-a)}{(c^2+ab)(a^2+bc)}+\frac{c(c-a)(c-b)}{(a^2+bc)(b^2+ca)}\right] \geqslant 0.$$
Suppose $a \geqslant b \geqslant c$ then
$$\frac{c(c-a)(c-b)}{(a^2+bc)(b^2+ca)} \geqslant 0,$$
and
$$\frac{a(a-b)(a-c)}{(b^2+ca)(c^2+ab)}+\frac{b(b-c)(b-a)}{(c^2+ab)(a^2+bc)} = \frac{(a^2+b^2)(a-b)^2(a+b-c)}{(a^2+bc)(b^2+ca)(c^2+ab)} \geqslant 0.$$
The proof is completed.

A: Another way.
Since for positives $x$, $y$, $z$, $a$, $b$ and $c$ we have $$x(b+c)+y(c+a)+z(a+b)\geq2\sqrt{(xy+xz+yz)(ab+ac+bc)}$$ (the proof see here: Bordered Hessian matrix to find a minimum of the function ),
for $x=\frac{a(b^2+c^2)}{b(a^2+c^2)+c(a^2+b^2)}$, $y=\frac{b(a^2+c^2)}{a(b^2+c^2)+c(a^2+b^2)}$ and $z=\frac{c(a^2+b^2)}{a(b^2+c^2)+b(a^2+c^2)}$ we obtain:
$$\sum_{cyc}\frac{a(b^2+c^2)}{a^2+bc}=\sum_{cyc}\frac{a(b^2+c^2)(b+c)}{(a^2+bc)(b+c)}=\sum_{cyc}\frac{a(b^2+c^2)(b+c)}{b(a^2+c^2)+c(a^2+b^2)}=$$
$$=x(b+c)+y(a+c)+z(a+b)\geq\sqrt{4(xy+xz+yz)(ab+ac+bc)}.$$
Id est, it's enough to prove that $$4(xy+xz+yz)\geq3.$$
Now, let $a(b^2+c^2)=p$, $b(a^2+c^2)=q$ and $c(a^2+b^2)=r$.
Thus, we need to prove that:
$$4\sum_{cyc}\frac{pq}{(p+r)(q+r)}\geq3$$ or $$\sum_{cyc}r(p-q)^2\geq0$$ and we are done!

A: Another way.
$$\sum_{cyc}\frac{a(b^2+c^2)}{a^2+bc}=\sqrt{\sum_{cyc}\frac{a^2(b^2+c^2)^2}{(a^2+bc)^2}+2\sum_{cyc}\frac{ab(a^2+c^2)(b^2+c^2)}{(a^2+bc)(b^2+ac)}}\geq$$
$$\geq\sqrt{3\sum_{cyc}\frac{ab(a^2+c^2)(b^2+c^2)}{(a^2+bc)(b^2+ac)}}.$$
Thus, it's enough to prove that:
$$\sum_{cyc}\frac{ab(a^2+c^2)(b^2+c^2)}{(a^2+bc)(b^2+ac)}\geq ab+ac+bc$$ or
$$abc\sum_{cyc}(a^5-a^4b-a^4c+2a^3bc-a^2b^2c)\geq0,$$ which is true by Schur:
$$\sum_{cyc}(a^5-a^4b-a^4c+a^3bc)\geq0$$ and Muirhead:
$$\sum_{cyc}(a^3bc-a^2b^2c)\geq0.$$


text:
Q: Stata: Uniquely sorting points within groups I'm conducting a household survey with a random sample of 200 villages. Using QGIS, I picked a random point 5-10km from my original villages. I then obtained, from the national statistical office, the village codes for those 200 "neighbor" villages - as well as a buffer of 10 additional neighbor villages. So my total sample is:
200 original villages + 210 neighbor villages = 410 villages, total
We're going to begin fieldwork soon, and I want to give each survey team a map for 1 original village + the nearest neighbor village. Because I'm surveying in some dense urban areas as well, sometimes a neighbor village is actually quite close to more than one original village.
My problem is this: if I run Distance Matrix in QGIS, matching an old village to its nearest neighbor village, I get duplicates in the latter. To get around this, I've matched each old village to the nearest 5 neighbor villages. My main idea/goal is to pick the nearest neighbor that hasn't already been picked.
I end up with a .csv like so:

As you can see, picking the five nearest villages, I'm getting repeats - neighbor village 79 is showing up as nearby to original villages 1, 2, 3, and 4. This is fine, as long as I can assign neighbor village 79 to one (and only one) original village, and then have the rest uniquely match as well.
What I want to do, then, is to uniquely match each original village to one neighbor village. I've tried a bunch of stuff, none of which has worked: My sense is that I need to loop over original village groups, assign a variable (e.g. taken==1) to one of the neighbor villages, and then - somehow - have each instance of that taken==1 apply to all instances of, say, neighbor village 79.
Here's some sample code of what I was thinking. Note: this uniquely matches 163 of my neighbors.
        gen taken = 0
        so ea distance

        by ea: replace taken=1 if _n==1

        keep if taken==1

        codebook FID ea

This also doesn't work; it just sets taken to 1 for all obs:
        foreach i in 5 4 3 2 1 {
            by ea: replace taken=1 if _n==`i' & taken==0
        }

What I need to do, I think, is loop over both _N and _n, and maybe use an if/else. But I'm not sure how to put it all together.
(Tangentially, is there a better way to loop over decreasing values in Stata? Similar to i-- in other programming languages?)

A: This should work but the setup is a little different than what you say you need. By comparing with only five neighbors, you have an ill-posed problem. Imagine that geography is such that you end up with six (or more) original villages that have all the same list of five neighbors. What do you assign the sixth original village?
Given this, I compare the original village with all other villages, not only five.  The strategy is then to assign original village 1 its closest neighbor; to original village 2 its closest neighbor after discarding the one previously assigned, and so on. This assumes equal number of original and neighbor villages but you have ten additional, so you need to give that a thought.
clear
set more off

*----- example data -----

local numvilla = 4 // change to test
local numobs = `numvilla'^2

set obs `numobs'

egen origv = seq(), from(1) to(`numvilla') block(`numvilla')
bysort origv: gen neigh = _n

set seed 1956
gen dist = runiform()*10

*----- what you want ? -----

sort origv dist

list, sepby(origv)

quietly forvalues villa = 1/`numvilla' {

    drop if origv == `villa' & _n > `villa'
    drop if neigh == neigh[`villa'] & _n > `villa'

}

list

The other issue is that results will depend on which original village is set to first, second, and so on; because order of assignments will change according to that. That is, the order in which available options are discarded changes with the order in which you set up the original villages. You may want to randomize the order of the original villages before you start the assignments.
You can increase efficiency substituting out & _n > `villa' for in `=`villa'+1'/L, but you won't notice much with your sample size.
I'm not qualified to say anything about your sample design, so take this answer to address only the programming issue you pose.
By the way, to loop over decreasing values:
forvalues obs = 5(-1)1 {
    display "`obs'"
}

See help numlist.


text:
Q: Method gets called two times I am doing a NSURLConnection that downloads a file only if there is a new one (checked with the last-modified date). But to accomplish this I am using two methods with two different NSURLRequests and NSURLConnection. Well, they do the same.
    - (IBAction)uppdatera:(id)sender
{
    checkHeaders = YES;

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.forellgatan.se/site/ftp_files/Kapareskolan.zip"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection)
    {
        self.receivedData = [[NSMutableData data] retain];
    }

    else
    {
        UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"Ingen internetanslutning! 1" message:@"Anslut dig till internet för att ladda ner!"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [connectFailMessage show];
        [connectFailMessage release];
    }
}

- (void)downloadNewFile
{
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.forellgatan.se/site/ftp_files/Kapareskolan.zip"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];

    NSURLConnection *theConnection2 = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection2)
    {
        self.receivedData = [[NSMutableData data] retain];
    }

    else
    {
        UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"Ingen internetanslutning! 2" message:@"Anslut dig till internet för att ladda ner!"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [connectFailMessage show];
        [connectFailMessage release];
    }

    checkHeaders = NO;

    self.progressView.hidden = NO;
}

It goes through the didReceiveResponse method:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (checkHeaders == YES)
    {
        NSHTTPURLResponse *test = (NSHTTPURLResponse *)response;

        if ([test respondsToSelector:@selector(allHeaderFields)])
        {
            NSDictionary *metaData = [test allHeaderFields];

            NSString *lastModifiedString = [metaData objectForKey:@"Last-Modified"];

            NSString *savedString = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastModified"];

            if (![lastModifiedString isEqualToString:savedString])
            {
                [self downloadNewFile];
            }

            else if ([lastModifiedString isEqualToString:savedString])
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ingen uppdatering tillgänglig" message:@"Det finns ingen uppdatering att hämta just nu." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];
                [alert release];
            }

            NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
            [standardUserDefaults setObject:lastModifiedString forKey:@"LastModified"];
            [standardUserDefaults synchronize];
        }
    }

    [self.receivedData setLength:0];
    self.fileSize = [[NSNumber numberWithLong: [response expectedContentLength]] retain];
}

Last the connectionDidFinishLaunching method:
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (checkHeaders == NO)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        [self.receivedData writeToFile:[basePath stringByAppendingPathComponent:@"Kapareskolan.zip"] atomically:YES];

        [self unzipDownloadedFile];

        self.progressView.hidden = YES;

        NSLog(@"Finished...");
    }

    [connection cancel];
}

I know the didFinishLaunching method gets called twice, but I want to know how I could get so the method doesn't get called twice if there is an update?
I know it's a lot asked and much code here but just give me a hint and I'll be very thankful.

A: If you're done with the first connection object in the didReceiveResponse method you should cancel it then. Otherwise it's going to make it to the connectionDidFinishLoading method.
I think this is what you want:
if (![lastModifiedString isEqualToString:savedString])
  {
    [connection cancel];
    [self downloadNewFile];
  }

Also It looks like you're setting checkHeaders to NO after you start the second request which could cause a race condition.

A: According to the programming guide, a connection "can be canceled any time before the delegate receives a connectionDidFinishLoading: or connection:didFailWithError: message by sending the connection a cancel message".
so why not try moving
      [connection cancel];

from the connectionDidFinishLoading method to just after your if-else block in the didReceiveResponse delegate method?  You want to cancel the "checkHeaders==YES" connection in either case; either you're about to kick off a new connection, or you already know all you need to know about the current connection.
UPDATED as requested:
  if (![lastModifiedString isEqualToString:savedString]) {
      [self downloadNewFile];
  } else { // you've already implicitly checked for equality above
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ingen uppdatering tillgänglig" message:@"Det finns ingen uppdatering att hämta just nu." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
      [alert show];
      [alert release];
  }
  // you've used the connection for everything that you need, so cancel it in either case
  [connection cancel];

as downloadNewFile kicks off its NSURLConnection asynchronously, this should be okay in the event that the two strings are equal.  Slightly safer would be to move the cancel method call to just prior to the if-else check.


text:
Q: Some problems in coding a "guessing random number in C" under some conditions such as using input(), output() I tried going beyond just guessing random numbers. The conditions were these:

*

*use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number

*use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())

*make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!

I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)

int input();
int random(int);
void myflush();
void output(int, int);

int main()
{
    int num;
    int i;
    int ran;

    srand((unsigned int)time(NULL));
    i = 0;
    while (i < 1) {
        ran = 1 + random(101);
        ++i;
    }

    num = input();
    output(ran, num);

    printf("You got it right on your    th try!");a

    return 0;
}

int input()
{
    int num;
    printf("insert a number : ");
    scanf("%d", &num);
    while (num < 1 || num > 100 || getchar() != '\n') {
        myflush();
        printf("insert a number : ");
        scanf("%d", &num);
    }
    return num;
}

int random(int n)
{
    int res;
    res = rand() % n;
    return res;
}

void myflush()
{
    while (getchar() != '\n') {
        ;
    }
    return;
}

void output(int ran, int num) {
    while (1) {
        if (num != ran){
            if (num < ran) {
            printf("bigger than %d \n", num);  //
            }
            else if (num > ran) {
                printf("smaller than %d.\n", num);
            }
            printf("insert a number : ");
            scanf("%d", &num);
        }
        else {
            break;
        }
    }
    return;
}

A: There are many problem and possible simplifications in this code.

*

*use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn't work properly.

*the function random is not needed since picking a random number is a simple expression.

*if the range of the random number is [1,100], you should use 1+rand()%100.

*there is no real need for the function output since it's the core of the main program. The input function is however good to keep to encapsulate input.

*you should test the return value of scanf because the input may not always contain a number.

Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)

int input() {
    char line[100];
    int num, nVal;
    printf("insert a number : ");
    fgets(line, sizeof line, stdin);
    nVal = sscanf(line, "%d", &num);
    while (nVal != 1 || num < 1 || num > 100) {
        printf("insert a number : ");
        fgets(line, sizeof line, stdin);
        nVal = sscanf(line, "%d", &num);
    }
    return num;
}

int main()
{
    int cnt = 0, lowerLimit = 0, upperLimit = 101;

    srand((unsigned int)time(NULL));

    // pick a random number in the range [1,100]
    int ran = 1 + rand()%100;

    while(1) {
        cnt++;
        int num = input();
        if (num == ran)
            break;
        if (num > lowerLimit && num < upperLimit) {
            if (num < ran)
                lowerLimit = num;
            else
                upperLimit = num;
        }
        printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
    }
    printf("You got it right on your %dth try!\n", cnt);
    return 0;
}

A: I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
    int count = 0;//create a variable to track tries
    while (1) {
        if (num != ran){
            count++;//increment tries here and...
            if (num < ran) {
                printf("bigger than %d \n", num);  //
            }
            else if (num > ran) {
                printf("smaller than %d.\n", num);
            }
            printf("insert a number : ");
            scanf("%d", &num);
        }
        else {
            count++;//... here
            break;
        }
    }
    return count;//return value for accumulated tries
}

Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);

With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)

A: If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)

int main()
{
    const char *ordinals[4] = { "st", "nd", "rd", "th" };
    int num_tries = 0;
    int bigger_than = 0, smaller_than = 101;
    int input_num;
    int random_num;

    srand( (unsigned int)time( NULL ) );
    random_num = 1 + rand() % 101;

    for (;;) //infinite loop, equivalent to while(1)
    {
        printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );

        printf( "enter a number: " );
        scanf( "%d", &input_num );
        printf( "You entered: %d\n", input_num );

        num_tries++;

        if ( input_num == random_num ) break;

        if ( input_num < random_num )
        {
            if ( bigger_than < input_num )
            {
                bigger_than = input_num;
            }
        }
        else
        {
            if ( smaller_than > input_num )
            {
                smaller_than = input_num;
            }
        }
    }

    printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );

    return 0;
}

Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.


text:
Q: Windows Phone 8: Add FrameworkElement to PanoramaItem from code behind When I add FrameworkElements to a PanoramaItem from code behind the panorama "selects" the panoramaItem, causing a really bad user experience.
I made a small test project where the problem is reproduced.
Tha MainPage contains just a panorama with three items:
<Grid x:Name="LayoutRoot" Background="Transparent">
    <phone:Panorama Name="m_Panorama">
        <phone:PanoramaItem Header="Item 1"
                            Name="m_Item1">
            <StackPanel Orientation="Vertical" Name="m_Stack1">
            </StackPanel>
        </phone:PanoramaItem>
        <phone:PanoramaItem Header="Item 2"
                            Name="m_Item2">
            <StackPanel Orientation="Vertical" Name="m_Stack2">
            </StackPanel>
        </phone:PanoramaItem>
        <phone:PanoramaItem Header="Item 3"
                            Name="m_Item3">
            <StackPanel Orientation="Vertical" Name="m_Stack3">
            </StackPanel>
        </phone:PanoramaItem>
    </phone:Panorama>
</Grid>

The code behind uses a DispatcherTimer to start adding the elements to the PanoramaItems:
public partial class MainPage : PhoneApplicationPage
{
  public MainPage()
  {
    InitializeComponent();
  }

  protected override void OnNavigatedTo(NavigationEventArgs e)
  {
    base.OnNavigatedTo(e);
    if (e.NavigationMode == NavigationMode.New){
      StartDelayed(UpdateItem1, 1000);
      StartDelayed(UpdateItem2, 1000);
      StartDelayed(UpdateItem3, 1000);
    }
  }

  private void AddTextblock(StackPanel stackPanel, string text, bool animate)
  {
    TextBlock tb = new TextBlock();
    tb.Text = text;
    stackPanel.Children.Add(tb);

    if (animate){
      tb.Measure(new Size(double.MaxValue, double.MaxValue));
      tb.UpdateLayout();

      Storyboard sb = new Storyboard();
      DoubleAnimation anim = new DoubleAnimation();
      anim.Duration = new Duration(TimeSpan.FromMilliseconds(500));
      anim.From = 0;
      anim.To = tb.DesiredSize.Width;
      sb.Children.Add(anim);
      Storyboard.SetTarget(anim, tb);
      Storyboard.SetTargetProperty(anim, new PropertyPath("Width"));
      sb.Begin();
    }
  }

  private async void UpdateItem1(object sender, EventArgs e)
  {
    while (true){
      m_Stack1.Children.Clear();
      for (int i=0; i<10; i++){
        await Task.Delay(500);
        AddTextblock(m_Stack1, "This is item 1", false);
      }
    }
  }

  private async void UpdateItem2(object sender, EventArgs e)
  {
    while (true){
      m_Stack2.Children.Clear();
      for (int i=0; i<10; i++){
        await Task.Delay(1000);
        AddTextblock(m_Stack2, "This is item 2", false);
      }
    }
  }

  private async void UpdateItem3(object sender, EventArgs e)
  {
    while (true){
      m_Stack3.Children.Clear();
      for (int i=0; i<10; i++){
        await Task.Delay(1500);
        AddTextblock(m_Stack3, "This is item 3", false);
      }
    }
  }

  private static void StartDelayed(EventHandler handler, int milliseconds)
  {
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromMilliseconds(milliseconds);
    if (handler != null)
      timer.Tick += new EventHandler(handler);
    timer.Tick += new EventHandler(OnLoadedTimerTick);
    timer.Start();
  } // StartDelayed

  private static void OnLoadedTimerTick(object sender, EventArgs e)
  {
    DispatcherTimer timer = sender as DispatcherTimer;
    if (timer != null)
      timer.Stop();
  } // OnLoadedTimerTick
}

The problem can be seen if you scroll slowly the panorama: as soon as one item is added to the stack panel the Panorama will reposition to the PanoramaItem containing the added element.
My question is: what am I doing wrong? How can I avoid the panorama to select the panoramaItem?

A: A quick solution is to enclose the StackPanel in a fixed size container.
For example
<phone:PanoramaItem Header="Item 1" Name="m_Item1">
    <ScrollViewer Height="1024">
        <StackPanel Orientation="Vertical" Name="m_Stack1"/>
    </ScrollViewer>
</phone:PanoramaItem>

What I think is going on is that it is dynamically resizing the element and its container resulting in that jerking motion you see when you scroll horizontally to the next panorama item. And if you want you can bind the height of that ScrollViewer to the height of the screen for optimal use.


text:
Q: I am trying to retrieve a List of Category and Comments By Using the Sprint Boot where Comment ID is Repeating for every Object Here is the Background information of my Restful API. I am trying to create Many to One Relation between Comments and Category Where Many Comments belong to One Category. If I am trying to call the Get All Categories -> I am getting the correct response. Also, If I am trying to call the Comments API where I am passing the CategoryID as a Path Variable I am able to retrive the correct response as well. However, When I am trying to consolidate the API, it is repeating the comments even though they are not belong to category one For instance.
Category Entity
package com.mshakir.restfulwebservice.dto.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "categories")
`
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "category_generator")
@SequenceGenerator(name = "category_generator", sequenceName = "category_sequence", initialValue = 20000, allocationSize = 1)
@Column(name = "category_id")
private Long id;

@Column(name = "category_name", nullable = false, length = 32)
private String categoryName;

@Column(name = "category_desc", nullable = false, length = 64)
private String categoryDescription;

@Column(name = "is_published", nullable = false, length = 32)
private boolean isPublished = true;

@Transient
private String publishedMessage;

private String isActive;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getCategoryName() {
    return categoryName;
}

public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
}

public String getCategoryDescription() {
    return categoryDescription;
}

public void setCategoryDescription(String categoryDescription) {
    this.categoryDescription = categoryDescription;
}

public boolean getIsPublished() {
    return isPublished;
}

public void setIsPublished(boolean isPublished) {
    this.isPublished = isPublished;
}

public String getPublishedMessage() {
    String message = "";
    if (isPublished) {
        message = "Category Id has been published to the Website";
    } else {
        message = "Category Id has not been published to the Website";
    }
    return message;
}

public String getIsActive() {
    return isActive;
}

public void setIsActive(String isActive) {
    this.isActive = isActive;
}

public void setPublishedMessage(String publishedMessage) {
    this.publishedMessage = publishedMessage;
}

@Override
public String toString() {
    return "Category [id=" + id + ", categoryName=" + categoryName + ", categoryDescription=" + categoryDescription
            + " , isActive=" + isActive + "]";
}

}`

Comment Entity
package com.mshakir.restfulwebservice.dto.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
`@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comment_generator")
@SequenceGenerator(name = "comment_generator", sequenceName = "comment_sequence", initialValue = 15001, allocationSize = 1)
@Column(name = "comment_id")
private Long id;

@Lob
@Column(name = "comment_content")
private String content;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "category_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Category category;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}

@Override
public String toString() {
    return "Comment [id=" + id + ", content=" + content + ", category=" + category + "]";
}

}`
Category Controller with Implement Service
`
@RestController
@RequestMapping("/categories")
public class CategoryController {
public static Logger log = LoggerFactory.getLogger(CategoryController.class);
@Autowired
CategoryRepository categoryRepository;

@Autowired
CommentRepository commentRepository;

private final CategoryServiceImpl categoryServiceImpl;

@Autowired
public CategoryController(CategoryServiceImpl categoryServiceImpl) {
    this.categoryServiceImpl = categoryServiceImpl;
}

@PostMapping("/create-new-category")
public ResponseEntity<Category> createCategoryRecord(@RequestBody Category category) throws Exception {
    log.info("Category Controller: createCategoryRecord()");
    Category createNewCategory = categoryServiceImpl.createNewCategory(category);
    HttpStatus statusCreated201 = HttpStatus.CREATED;
    return new ResponseEntity<Category>(createNewCategory, statusCreated201);
}
}`

Implement Service Method For this Post Category
`
@Service
public class CategoryServiceImpl implements CategoryService {
private CategoryRepository categoryRepository;

@Autowired
public CategoryServiceImpl(CategoryRepository categoryRepository) {
    this.categoryRepository = categoryRepository;
}

@Override
public Category createNewCategory(Category category) {
    String categoryName = category.getCategoryName();
    Optional<Category> findByCategoryName = categoryRepository.findByCategoryName(categoryName);
    if (findByCategoryName.isPresent()) {
        throw new InvalidDataException("Category already exists in the Database");
    }
    Category newCategory = categoryRepository.save(category);
    return newCategory;
}
}`

Show All Categories
`
@GetMapping("/show-all-categories")
public ResponseEntity<List>
showAllCategoriesAll(@RequestParam(required = false) String categoryName) {
List listOfCategories = new ArrayList();
if (Utils.isEmptyString(categoryName)) {
categoryRepository.findAll().forEach(category -> {
listOfCategories.add(category);
});
    }
    else {
        List<Category> findByCategoryNameContaining = categoryRepository.findByCategoryNameContaining(categoryName);
        findByCategoryNameContaining.forEach(category -> listOfCategories.add(category));
    }

    if (listOfCategories.isEmpty()) {
        return new ResponseEntity<List<Category>>(listOfCategories, HttpStatus.OK);
    }

    return new ResponseEntity<List<Category>>(listOfCategories, HttpStatus.OK);
}`

Get List of Comments Based on Category ID
`
@GetMapping("/categories/{categoryId}/comments")
public ResponseEntity<List>
getAllCommentsByTutorialId(@PathVariable(value = "categoryId") Long categoryId) {
if (!categoryRepository.existsById(categoryId)) {
throw new ResourceNotFoundException("Not found Tutorial with id = " + categoryId);
}
    List<Comment> comments = commentRepository.findByCategoryId(categoryId);

    List<Comment> findAll = commentRepository.findAll();
    for (Comment comment: findAll) {
        System.out.println(comment.getCategory().getCategoryName());
        System.out.println(comment.getCategory().getCategoryDescription());
    }
    System.out.println(findAll);
    return new ResponseEntity<>(comments, HttpStatus.OK);
  }`

Consolidated API
`
@RestController
@RequestMapping("/list-of-categories")
public class ListOfCategory {
@Autowired
CategoryRepository categoryRepository;

@Autowired
CommentRepository commentRepository;

@GetMapping("/show-all")
public ResponseEntity<List<CategoryCommentResponse>> showAll() {
    List<CommentInfo> listOfComments = new ArrayList<CommentInfo>();
    List<CategoryCommentResponse> listofAll = new ArrayList<CategoryCommentResponse>();
    List<Category> categoryList = categoryRepository.findAll();
    System.out.println(categoryList);
    for (Category category : categoryList) {
        CategoryCommentResponse response = new CategoryCommentResponse();
        Long categoryId = category.getId();
        response.setCategoryId(categoryId);
        response.setCategoryDescription(category.getCategoryDescription());
        response.setCategoryName(category.getCategoryName());
        List<Comment> listOfCommentsByCategoryId = commentRepository.findByCategoryId(categoryId);

        for (Comment comment : listOfCommentsByCategoryId) {
            CommentInfo commentInfo = new CommentInfo();
            Long commentId = comment.getId();
            commentInfo.setId(commentId);
            commentInfo.setContent(comment.getContent());
            System.out.println(commentInfo);
            listOfComments.add(commentInfo);
            response.setComments(listOfComments);
        }
        listofAll.add(response);
    }

    return new ResponseEntity<List<CategoryCommentResponse>>(listofAll, HttpStatus.OK);

}
}`

Please find attached Screenshot to review as well. Thank you
ConsolidatedAPI
List Of Categories
List Of Comments based on Category Id

A: Error is a logic flaw in your showAll method. You instantiate and build a single listOfComments List and populate it with comments as you process categories, and use this same list for all categories. As it runs, the list will contain all comments from them all.
Each Category needs its own independent list:
public ResponseEntity<List<CategoryCommentResponse>> showAll() {
  ..
    List<Comment> listOfCommentsByCategoryId =commentRepository.findByCategoryId(categoryId);
    List<CommentInfo> listOfCommentInfos = new ArrayList<CommentInfo>();

    for (Comment comment : listOfCommentsByCategoryId) {
      CommentInfo commentInfo = new CommentInfo();
      commentInfo.setId(comment.getId());
      commentInfo.setContent(comment.getContent());
      System.out.println(commentInfo);
      listOfCommentInfos.add(commentInfo);
      response.setComments(listOfCommentInfos);
    }
    listofAll.add(response);
  }

  return new ResponseEntity<List<CategoryCommentResponse>>(listofAll, HttpStatus.OK);
}


text:
Q: xml to csv - headers Can anyone help me please?
How can I add headers to csv from xml? I´m not a programator, because of that, I don´t know, how to do it.
Thanks a lot.
Sorry for my English.
Peter
My php code:
`

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://velkoobchod.carero.sk/feed/zbozi.aspx",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  $file = fopen("./csv/sklad.xml", 'w+');
fwrite($file, $response);
fclose($file);
}
$filexml='./csv/sklad.xml';
if (file_exists($filexml)) {
  $xml = simplexml_load_file($filexml);
  $f = fopen('./csv/sklad.csv', 'w');
  foreach($xml->SHOPITEM as $shopitem) {

    $values = array(
   "PRODUCT" => (string)$shopitem->PRODUCT,
   "KOD" => (string)$shopitem->KOD,
   "SKLADOVOST" => (string)$shopitem->SKLADOVOST
);

    fputcsv($f, $values,',','"');
  }
  fclose($f);
}

?>

A: You can add the following above your for loop:
$values = array(
  "PRODUCT" => "PRODUCT",
  "KOD" => "KOD",
  "SKLADOVOST" => "SKLADOVOST"
);
fputcsv($f, $values,',','"');
//your existing code:
foreach($xml->SHOPITEM as $shopitem) {
...


text:
Q: react native scoped storage not executing well I am using react native scoped storage in which I used that package react-native-scoped-storage so I used this package like that
import * as ScopedStorage from "react-native-scoped-storage"
let dir = await ScopedStorage.openDocumentTree(true);

What should I do next after this means how should I tell my app that it will used read and write permission until android 10 and after select folder from react native scoped storage save that folder permission to use later ?


text:
Q: Need advice on using Wireshark + aircrack-ng I am making acquiantance with wireless security and attacks and was told to run some tests with aircrack-ng and wireshark.
So I installed both of them and ran airmon to switch wi-fi card to monitor mode:
sudo airmon-ng start ra0 (this is my DWA-140 usb wi-fi adapter) The wi-fi adapter seems to have restarted after that. Gues that's ok. Still it gave some warnings on processes that might interfere with normal work like network manager, dhclient and a few more. I tried to stop them, but they seem to restart all the time.
After that I ran wireshark as a superuser, chose the ra0 adapter and tried to sniff the test open network. I have my PC connected to it (via dwa-140) and an HTC phone and some stranger PCs. Wireshark runs on my PC.
The problem is that when I login to %sitename% with a PC browser, I can see the cookies sent to it in Wireshark. But when I do the same thing with an Opera Mobile browser on my HTC (Turbo option disabled), there is nothing detected. I know that stranger PCs are also sending data to %sitename%, but I see nothing from them as well. Actually I see a lot of packets from stranger PCs, but not the ones I need.
I'd like to know what I'm doing wrong. Will be thankful for any advice.
P.S. This runs on Ubuntu 12.04.1

A: From wikipedia: Opera Mini requests web pages through Opera Software's servers, which process and compress them before sending them to the mobile phone, speeding up transfer by two to three times and dramatically reducing the amount of data transferred, chargeable on many mobile phone data plans. The pre-processing increases compatibility with web pages not designed for mobile phones.
Perhaps this caching, processing and resending is making the cookies look like a different type of packet. The connection between opera and the proxy server is encrypted, so you will have a lot of difficulty trying to recover plain text cookies by sniffing.

A: The issue was solved by installing an rt2800usb driver. Now monitor mode can be enabled, though sometimes the connection is lost.


text:
Q: Execute shell commands with excel VBA and collect output I am trying to make a ticket tool we have where I work a little better and make it so the tech team doesn't have to open Active Directory to make sure the ticket sender is eligible to make certain requests. What I need is the ability to run net user /domain <username> then collect the comment line and store it in a variable in VBA. The variable will then be sent in an email to the ticket software along with anything the user entered in the text boxes.
My thoughts were to run the command and send the output string to another variable then pull the line information from the larger output since I cant seem to find a way to get only the comment.
I've added a sample of the output below with an arrow pointing at the data that needs extracted into the variable.
I'm still pretty new to VBA so bear with me.
C:\Users\jdoe\Desktop>net user /domain jdoe
The request will be processed at a domain controller for domain StackOverflow.wh.

User name                    jdoe
Full Name                    John Doe
Comment                      Anlst Tech Supp  <----- this is what needs extracted
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            11/1/2021 8:58:44 AM
Password expires             1/30/2022 8:58:44 AM
Password changeable          11/1/2021 8:58:44 AM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   1/15/2022 11:43:12 AM

Logon hours allowed          All

Local Group Memberships
Global Group memberships     *Domain Users

The command completed successfully.

A: On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

Set config = objWMIService.ExecQuery("Select * From Win32_UserAccount")
For Each thing in Config
        Msgbox thing.caption & "  " & thing.Description
Next

Programmers don't call user's commands. They are for humans not programs.
See https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-useraccount for more info.


text:
Q: How do I determine whether bumblebee is working as expected? I followed the instructions at https://wiki.ubuntu.com/Bumblebee
sudo add-apt-repository ppa:bumblebee/stable
sudo add-apt-repository ppa:ubuntu-x-swat/x-updates

sudo apt-get update

Instead of installing the proprietary nvidia drivers, via:
sudo apt-get install bumblebee bumblebee-nvidia linux-headers-generic

I did:
sudo apt-get install --no-install-recommends bumblebee linux-headers-generic

How do I determine that power savings mode is active and that my dedicated GPU isn't running?
One thing that bugs me is that if I go to System Settings - Details - Graphics. Driver is shown as Unknown.

A: To get the graphics card model, install mesa-utils .Remember the graphics card model won't be nvidia one. It will be intel, because in nvidia optimus the nvidia card isn't exposed directly. Nvidia card is wired via the intel one
--no-install-recommends prevent certain packages from being installed, mainly the nvidia driver.
You need to follow the instruction for getting it worked. If you don't install the correct driver, it may fail while loading. What is the problem in installing the driver? the driver won't be used unless you use optirun
Regarding, 2nd question. I really don't know the exact answer.
After installation, my fan noise went down, battery life increased very much. I think that is the indication that powersaving is working.
You can use dmesg to know what is happening. On reboot try
dmesg | grep bbswitch
you will see somthing like below
[   25.305974] bbswitch: version 0.4.2
[   25.305983] bbswitch: Found integrated VGA device 0000:00:02.0: \_SB_.PCI0.GFX0
[   25.305991] bbswitch: Found discrete VGA device 0000:01:00.0: \_SB_.PCI0.PEG0.PEGP
[   25.306182] bbswitch: detected an Optimus _DSM function
[   25.306192] bbswitch: Succesfully loaded. Discrete card 0000:01:00.0 is on
[   25.325482] bbswitch: disabling discrete graphics
[   25.325620] bbswitch: Result of Optimus _DSM call: 11000059

As I can see, in your previous question, Lekensteyn assures you about power management. He is the developer of bumblebee

A: You can check if bumblebee is working with glxgears. For instance, in my computer if I do:
$ glxgears -info
Running synchronized to the vertical refresh.  The framerate should be
approximately the same as the monitor refresh rate.
GL_RENDERER   = Mesa DRI Intel(R) Haswell Mobile
GL_VERSION    = 3.0 Mesa 19.0.2
GL_VENDOR     = Intel Open Source Technology Center
GL_EXTENSIONS = GL_ARB_mu...... [AND A LOT OF OUTPUT]

but if I do:
$ optirun glxgears -info
GL_RENDERER   = GeForce GTX 960M/PCIe/SSE2
GL_VERSION    = 4.6.0 NVIDIA 418.56
GL_VENDOR     = NVIDIA Corporation
GL_EXTENSIONS = GL_AMD_multi_draw_indirect...... [AND A LOT OF OUTPUT]

So, it is clear that the nvidia card is only used when I use optirun.


text:
Q: ASP .NET Core 6 dependency injection error with params keyword constructor I'm migrating my project from ASP.NET Core 2.1 to ASP.NET Core 6.0.
I encounter a problem with the dependency injection when I try to register a class with a constructor containing params keyword. The actual error I received:

Some services are not able to be constructed (Error while validating
the service descriptor 'ServiceType:
DotNet60DIWebApp.AuthorizePermission Lifetime: Scoped
ImplementationType: DotNet60DIWebApp.AuthorizePermission': Unable to
resolve service for type 'System.String[]' while attempting to
activate 'DotNet60DIWebApp.AuthorizePermission'.)

The same code works in ASP .NET Core 2.1 but not in ASP .NET Core 6.0. Below is the code snippet which produces the error I encounter in ASP .NET Core 6.0.
Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddScoped<AuthorizePermission>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

AuthorizePermission.cs
namespace DotNet60DIWebApp
{
    public class AuthorizePermission
    {
        object[] Arguments;

        public AuthorizePermission(params string[] permissions)
        {
            Arguments = new object[] { permissions };
        }
    }
}

Does anyone know why?

A: You can try this way:
Define an interface IAuthorizePermission separately, and use AuthorizePermission as the implementation method of the interface,inject the IAuthorizePermission interface when using.
Below is my test code,you can refer it:
IAuthorizePermission:
public interface IAuthorizePermission
{
    object[] Arguments { get; }
    void Permission(params string[] permissions);
}

AuthorizePermission:
public class AuthorizePermission : IAuthorizePermission
{
    public object[] Arguments { get; set; }
    public  void Permission(params string[] permissions)
    {
        Arguments = new object[] { permissions };
    }
}

Program:
builder.Services.AddScoped<IAuthorizePermission,AuthorizePermission>();

Controller:
private readonly IAuthorizePermission _authorizePermission;
public HomeController(IAuthorizePermission authorizePermission)
{
      _authorizePermission = authorizePermission;
}

public IActionResult Index()
{
     _authorizePermission.Permission("Test1","Test2", "Test3");
     return View();
}

Test Result:


text:
Q: Is it possible to tag a user/page through Facebook open graph api? I found this post on SO as well as some other links on the web but they all seem outdated and seem to indicate that FB has not yet exposed this through the Open Graph API and i couldnt find anything to the contrary on the web. I am trying to find a way to post an image to a users wall and be able to tag multiple users in the post title or caption?
Is there still no way to do this through the api or somehow achieve the same result?

A: Tagging user/page in photo caption
This is not possible through the Graph API, and as far as I know the old @[user_id:0:link_text] is currently unavailable. Sadly I'm going to say that it is not possible at the time of writing this post.
I'll update this post with relevant info if I come across any.

Tagging user/page in Photo
This is possible through the Graph API.
The documentation for how to accomplish what you are looking for is located under the headline "tags" if you follow the link below:

*

*developers.facebook.com - Core Concepts › Graph API › Photo


text:
Q: Spark SQL - How to SUM values over date range linked to a especific date I need to do a sum of the values in the last 30 days (exclusive) relative to that date, with every product in every store.
Assuming all months with 30 days:
date|store|product|values
2020-06-30|Store1|Product1|1
2020-07-02|Store1|Product2|4
2020-07-01|Store2|Product1|3
2020-07-18|Store1|Product1|4
2020-07-18|Store1|Product2|2
2020-07-18|Store2|Product1|2
2020-07-30|Store1|Product1|1
2020-08-01|Store1|Product1|1
2020-08-01|Store1|Product2|1
2020-08-01|Store2|Product1|6

In the lines of day 2020-08-01, sum the values of (2020-08-20 - 30 days) to 2020-08-19 and put it in the 2020-08-20 line, like this:
(first line doesn't include '2020-06-30' because is more than 30 days ago and '2020-08-01' because is the same day, and this goes on...)
date|store|product|sum_values_over_last_30_days_to_this_date
2020-08-01|Store1|Product1|5
2020-08-01|Store1|Product2|6
2020-08-01|Store2|Product1|5
....

Tried this below and nothing too:
spark.sql("""
SELECT
a.date,
a.store,
a.product,
SUM(a.values) OVER (PARTITION BY a.product,a.store ORDER BY a.date BETWEEN a.date - INTERVAL '1' DAY AND a.date - INTERVAL '30' DAY) AS sum
FROM table a
""").show()

Anybody can help me?

A: Here is my trial with the sampel dataframe.
+----------+------+--------+------+
|      date| store| product|values|
+----------+------+--------+------+
|2020-08-10|Store1|Product1|     1|
|2020-08-11|Store1|Product1|     1|
|2020-08-12|Store1|Product1|     1|
|2020-08-13|Store1|Product2|     1|
|2020-08-14|Store1|Product2|     1|
|2020-08-15|Store1|Product2|     1|
|2020-08-16|Store1|Product1|     1|
|2020-08-17|Store1|Product1|     1|
|2020-08-18|Store1|Product1|     1|
|2020-08-19|Store1|Product2|     1|
|2020-08-20|Store1|Product2|     1|
|2020-08-21|Store1|Product2|     1|
|2020-08-22|Store1|Product1|     1|
|2020-08-21|Store1|Product1|     1|
|2020-08-22|Store1|Product1|     1|
|2020-08-20|Store1|Product2|     1|
|2020-08-21|Store1|Product2|     1|
|2020-08-22|Store1|Product2|     1|
+----------+------+--------+------+

df.withColumn("date", to_date($"date"))
  .createOrReplaceTempView("table")

spark.sql("""
    SELECT
        date,
        store,
        product,
        COALESCE(SUM(values) OVER (PARTITION BY 1 ORDER BY date RANGE BETWEEN 3 PRECEDING AND 1 PRECEDING), 0) as sum
    FROM table
""").show()

+----------+------+--------+---+
|      date| store| product|sum|
+----------+------+--------+---+
|2020-08-10|Store1|Product1|0.0|
|2020-08-11|Store1|Product1|1.0|
|2020-08-12|Store1|Product1|2.0|
|2020-08-13|Store1|Product2|3.0|
|2020-08-14|Store1|Product2|3.0|
|2020-08-15|Store1|Product2|3.0|
|2020-08-16|Store1|Product1|3.0|
|2020-08-17|Store1|Product1|3.0|
|2020-08-18|Store1|Product1|3.0|
|2020-08-19|Store1|Product2|3.0|
|2020-08-20|Store1|Product2|3.0|
|2020-08-20|Store1|Product2|3.0|
|2020-08-21|Store1|Product2|4.0|
|2020-08-21|Store1|Product1|4.0|
|2020-08-21|Store1|Product2|4.0|
|2020-08-22|Store1|Product1|6.0|
|2020-08-22|Store1|Product1|6.0|
|2020-08-22|Store1|Product2|6.0|
+----------+------+--------+---+

A: You can try self-join rather than window function, maybe this kind of join will work -
SELECT
    a.date,
    a.store,
    a.product,
    SUM(IFNULL(b.value,0))
FROM
    table a
LEFT JOIN
    (
        SELECT
            a.date,
            a.store,
            a.product,
            a.value
        FROM
            table  a
    )b
ON
    a.store = b.store
AND
    a.product = b.product
AND
    a.date > b.date - INTERVAL 30 DAYS
AND a.date <= b.date
GROUP BY
    1,2,3

Make sure to sum the value from the inner query, to have the sum up until this daye.


text:
Q: Center align my content with css I did little boxes on my website to shortly describe our activity, The text is that the same length for all the boxes so I am trying to center the text in the middle of the box with my css. I tried display:table-cell, vertical-align:center, but it doesn't work.
Did someone has an idea about what I can do?
Thank you :)

A: In css,
.text-center {
    text-align : center;
}

Add a class .text-center to you div.

A: You need to add display: table; to the text container and
display: table-cell;
    vertical-align: middle;
    text-align:center;

to your text span/h1/p

body {
  width: 100%;
  height: 100%;
}
div {
  position: absolute;
  height: 50%;
  width: 50%;
  display: table;
  background: blue;
}
h1 {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

Text

You need to add your code and be very specific about the question next time.


text:
Q: Empty PHP Contact form = 500 error I've done quite a few contact forms before but for some reason if any field is empty then i get sent to the error 500 page saying
"500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed."
The odd thing is that the form still sends, with whatever information has been entered so the submit function and asset seems to be working.
I've tried setting the variables to have a value before the form, and after the submit (adding " ".$variablename) so they aren't empty but it doesn't seem to work.  I'm using the form with instructions to fill in each field but it's for a web enquiry form so I want clients to be able to add as much or as little as they want (so don't need form validation for example).
I'm using bootstrap for the framework of the site.
 Any ideas??  Code below
HTML

Not sure what you need?

Fill in form below as you can and we will get in touch with some suggestions.  Please ensure you fill in every field, if you're not sure, say you're not sure!

            <form action="scripts/contactscript.php" method="post" class="form-horizontal">

                    Name:

                        <input type="text" class="form-control" id="name"  name="name" placeholder="Please give us your full name">

                    Email:

                        <input type="email" class="form-control" id="email" name="email" placeholder="Example@youremail.com">

                    Website:

                        <input type="text" class="form-control" id="url" name="url" placeholder="www.yourexample.com">

                    What:

                        <textarea class="form-control" name="bkgrd" placeholder="Tell us about what you want to achieve" rows="3" id="background"></textarea>

                    Content:

                            <input type="checkbox" name="content[]" id="contact" value="contact form">Contact form

                            <input type="checkbox" name="content[]" id="booking" value="booking system">Booking system/interactive calender

                            <input type="checkbox" name="content[]" id="commerce" value="ecommerce"> E-commerce/secure check out

                            <input type="checkbox" name="content[]" id="cms" value="cms"> Content management system

                            <input type="checkbox" name="content[]" id="users" value="profiles"> Secure log in/user profiles

                            <input type="checkbox" name="content[]" id="social" value="social"> Embedded social media

                            <input type="checkbox" name="content[]" id="none" value="none"> None

                        <textarea class="form-control" rows="2" placeholder="Let us know any specific ideas you may have in mind or have discovered on other sites while browsing"></textarea>

                    Anything else?

                        <textarea id="other" name="other" class="form-control" rows="2" placeholder="Anything else you feel might be useful" ></textarea>

                <button type="submit" class="btn-default" name="submit" value="submit">Submit</button>
            </form>

PHP(not on the same page)
    if(isset($_POST['submit'])) {
    $to = "noreply@mywebsite.com";
    $subject = "Website Enquiry";
    $name = $_POST['name'];
    $email = $_POST['email'];
    $url = $_POST['url'];
    $bkgrd = $_POST['bkgrd'];
    $content = implode(": ", $_POST['content']);
    $other = $_POST['other'];

}

$sub2 = "Thank you for your enquiry";
$msg= "Thank you for your enquiry.  We have received your contact form and will be in touch soon to discuss this further\n

Thanks\n

;

$message = "From:  $name\n Email: $email\n URL: $url\n Overview: $bkgrd\n Content: $content \n Other: $other   ";

mail($email, $sub2, $msg);

if(mail($to, $subject, $message)){

    header("location: http://www.mywebsite.com");

}else{

    header("location: http://www.mywebsite.com");
}


text:
Q: How to use serializeObject() with require.js Error: Cannot read property 'fn' of undefined How can I use the script below which exstends jquery $.fn.serializeObject() with require.js?
I'm getting the following error:
Uncaught TypeError: Cannot read property 'fn' of undefined serializeObject.js:
(anonymous function)
   $.fn.serializeObject = function() {
      var o = {};
      var a = this.serializeArray();
      $.each(a, function() {
          if (o[this.name] !== undefined) {
              if (!o[this.name].push) {
                  o[this.name] = [o[this.name]];
              }
              o[this.name].push(this.value || '');
          } else {
              o[this.name] = this.value || '';
          }
      });
      return o;
    };

this is my view save function giving the error:
 var participantDetails = $(ev.currentTarget).serializeObject();

does it need some other dependance I have missed?
This is my main.js:
require.config({

  shim: {

   "jquery": {
        exports: '$'
    },

    underscore: {
      exports: '_'
    },
    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone',
      init: function (_, $) { Backbone.$ = $; return Backbone; }
    },
    backbone_tastypie: {
      deps: ['backbone',  'underscore', 'jquery'],
      attach: "Backbone"
    },
     serialize: {
      deps: ['jquery']
      //exports: 'jQuery.fn.serializeObject'
    }
  },
  paths: {
    jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
    underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min',
    backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min',
    backbone_tastypie: '/static/js/libs/backbone-tastypie',
    serialize: '/static/js/libs/serializeObject',
    text: 'text',
    templates: '/static/'

  }

});

require([
  'app'
], function(App){

  App.initialize();

});

A: Are you defining a module? You need to:
define([
  'jquery'
],

etc


text:
Q: How to resolve this query? I need to sum all the values of this query before the output, i do not know how
This is the query:
SELECT u.usuario, u.id_usuario, d.id, COUNT(v.valoracion) AS votos, COUNT(d.id) * 4 AS dibujos, COUNT(c.id) AS comentarios
FROM icar_dibujos d
LEFT JOIN icar_valoraciones v ON d.id = v.id_dibujo
LEFT JOIN icar_usuarios u ON d.id_quien = u.id_usuario
LEFT JOIN icar_comentarios c ON u.id_usuario GROUP BY d.id_quien

What i want is to output the sum of votos + dibujos + comentarios
How can i achieve that?
Thanks in advance

A: You can simply sum the counts:
SELECT u.usuario, u.id_usuario, d.id, COUNT(v.valoracion) AS votos, COUNT(d.id) * 4 AS dibujos, COUNT(c.id) AS comentarios, COUNT(v.valoracion) + COUNT(d.id) * 4 + COUNT(c.id) AS TotalSum
FROM icar_dibujos d
LEFT JOIN icar_valoraciones v ON d.id = v.id_dibujo
LEFT JOIN icar_usuarios u ON d.id_quien = u.id_usuario
LEFT JOIN icar_comentarios c ON u.id_usuario GROUP BY d.id_quien


text:
Q: TP Link Powerline disconnects at very specific times I have a TL-WPA4220 kit which consists of a main adapter which connects to the router and power socket next to the router, and  an extender which is plugged in upstairs. I have a Samsung Smart TV and a PS4 connected to the extender with Ethernet.
If I connect my Macbook to the upstairs SSID general browsing works fine. However, if I do a speed test (for instance at speedtest.net) the PowerLine lights will flash and it will lose connection. The second I turn on my PS4, the connection is also lost. It will then reconnect and disconnect every 5 or so seconds. If I disconnect the cable, it stops dropping, but if I try to connect the PS4 by WiFi, the same issue persists.
I am at a complete loss as to what this could be. Why do these very specific actions cause the extender to lose connection while normal web browsing doesn't?


text:
Q: C++ ostream referencing Why does line 4 in the following print a memory address instead of the original string printed by line 2, and how do I correct this? Many thanks.
std::stringstream os (std::stringstream::in | std::stringstream::out);
std::cout << result->studentId;
os << result->studentId;
std::cout << &os << std::endl;

A: Use the str() function to get the underlying string:
std::cout << os.str() << std::endl;

For future reference here's a reference on std::stringstream, which contains every member function.

A: remove & operator
std::cout << os.str() << std::endl;


text:
Q: .htaccess How to set expiry time for downloads? I don't want the browser to cache my exe (setup/installer) files. One hour is more than enough. Is this a good .htaccess setup?
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType application/x-msdownload "access 1 hour"
</IfModule>
## EXPIRES CACHING ##


text:
Q: sort mongodb collection by date in node.js I'm new to mongodb and trying to figure out sorting with MongoClient in a node.js/express application.
This works in the mongo command line client:
db.mycollection.find().sort({"date":-1}); // displays by date, newest to oldest

I'm trying to achieve the same thing in my application:
db.collection('mycollection').find().sort({"date":-1}); //order remains the same

How can I achieve the same result as the first query? Thank you.

A: So, first, I'd recommend using Mongoose.  Failing that, however, the Node MongoClient puts things like sorting into the find() arguments, like so:
db.collection('mycollection').find({}, {sort:{date:-1}});


text: Q: AuthService.Authenticate does not create a persistent session when RememberMe = true. Intentional? I have an ASP.NET MVC project that is following the example in the ServiceStack.UseCases/CustomAuthenticationMvc project, where the account controller logs authenticates with ServiceStack when the user logs in to the MVC site by setting the AuthService's RequestContext and then calling Authenticate(). This works, but I noticed that even when RememberMe is true, no ss-opt cookie with "perm" is sent to the client. I poked around a little bit and found the code in AuthService.Post that sets this session option and added it to my code, and now I do get the ss-opt cookie and I can close the browser and re-open it to my project's URL and authentication succeeds using the persistent cookie. So, I have my solution or workaround, but it seemed odd that this behavior would be omitted from the Authenticate method, so I wanted to ask here: is this intentional or is it a bug?


text:
Q: socket connection using service name We are using sockets in our project to transfer data from one system to another system. In socket connect call, we are using Ipaddress and the port number to establish socket connection to the other system where our service is running.
Would it be possible to use the service name also in the connect call along with or without port number?
or can this be done in any other way?
Thanks in advance.


text:
Q: Find two finite groups $G_1$ and $G_2$ such as: Find two finite groups $G_1$ and $G_2$ such as:
$1)$ $|G_1|=|G_2|$
$2)$ for all prime $p$ every $p$-sylow subgroup of $G_1$ isomorpic to $p$-sylow subgroup of $G_2$.
but $G_1\not\cong G_2$.
hello I tried to find an example but I couldn't find one please help me.
I look on all the groups from order 6 (I choose this order randomly) but I don't know how to prove that every p-sylow subgroup of $G_1$ isomorpic to every p-sylow subgroup of $G_2$ for all primes p.

A: If $p, q$ are distinct primes then every two groups of order $pq$ will have isomorphic Sylow subgroups (being cyclic subgroups of order $p$ and $q$). So all you have to do is to find two nonisomorphic subgroups of order $pq$, e.g. $\mathbb{Z}_6$ and $S_3$.


text:
Q: How can I allow the cursor to continue moving immediately after clicking the trackpad? I have a Macbook, though I assume this behavior occurs on all of Apple's newer trackpads (the multitouch ones where the entire trackpad acts as a button).
For a split second after clicking the trackpad, the cursor won't move (try it!), even if you continue sliding your finger across it. This probably improves usability in some areas (like double clicking), but I don't like it. Is there a way to disable this behavior?
Edit:
I went to a local Best Buy, and every single Macbook had the same behavior. The pause is for only a split second. If you try spam-clicking as you move your finger across the trackpad, does the cursor move at all? If you click fast enough, it won't move.

A: I tried moving the curser with my left-hand, and clicking with my right as I dragged. Nothing unexpected happened; The curser changed temporarily during the click then reverted.

A: This really isn't a problem in practice. Your brain gets all the little nuance and adjusts to these refinements with ease. Most come to depend on them and other hardware / OS starts to feel wrong. ( just as you do at present )
If you have exquisite motor control, you will end up with the tracking setting very high. The demo macs might be set up even slower than the default to prevent surprise to people using them on the less than ideal store setting.
Set the double click speed to max and the tracking to max and see if you can immobilize the cursor.

A: It does do this exactly as you say. A way around it is to enable 3 finger dragging, and then instead of clicking, just add 2 more fingers. It will essentially act as a click & hold but it won't pause.


text:
Q: Argo workflows CI on GitHub Hi I have a question about argo workflows CI, did I can connect argo workflows to GitHub, when creating pull request I want to see on GitHub tests jobs end (some tests), how can I connect argo workflows to GitHub, now I connects only GitHub webhooks.
Here I want to see when jobs end on argo workflows
enter image description here
And here is my argo workflow job
enter image description here


text:
Q: Question on statics Consider a uniform beam that is supported by 3 pivots that are the same distance from each other (shown below). What will the normal force exerted by each pivot be?
The situation seemed rather paradoxical to me because depending on the order you place the pivots in the normal force exerted by each pivot will be different.
For instance, in (1), I first place in the 2 pivots on the sides, and then the one in the centre. Logically, the final weight will be borne entirely by the 2 pivots on the side... right? Since the 2 systems (the  rod and 2 pivots, and the 3rd pivot) are entirely stable on their own, and there is no need for the weight to redistribute.
But I can also place in the centre pivot first, and then the side pivots (2) and then I get a different distribution of weight!
In fact I think the solution can be anything that looks like the situation in (3).
But of course, we can do the experiment in real life, and swap the pivots with mass balances, and each time we perform the experiment we can expect to get the same reading.  So what is going on? Is there some missing information in the reasoning above that leads to the solution being indeterminate?

A:
Is there some missing information in the reasoning above that leads to
the solution being indeterminate?

The beam is statically indeterminate. It is not "missing information" that makes it  so. It is because there is a redundant vertical reaction. If you remove any one of the supports the beam remains stable and the reactions can be determined solely by the equations for equilibrium, i.e., the sum of the moments equals zero and the sum of the forces equals zero.
When the structure is statically indeterminate you need to use additional equations with respect to the constraints in deformation, such as equations of deflection.
For an introduction to the method of analysis, check out the following.
http://ocw.nthu.edu.tw/ocw/upload/8/259/Chapter_10-98.pdf
By the way, you didn't indicate what type of supports are involved (pins and/or rollers). More than one pin would mean the beam is statically indeterminate with respect to horizontal reactions as well a vertical reactions.
Hope this helps.

A: The solution to your apparent paradox is that when the beam is supported at each end it deflects and sags slightly in the middle. When you introduce a third support in the middle you change this deflection and so redistribute the weight of the beam between the supports. This is why the load on the central support is not zero.


text:
Q: How to create a modal popup using addEventListener? i'm studying JS at the moment so i don't know a lot of things about it.
i created a page with an "edit" button.
when i click on the button, it should appear a popup:

*

*with toogle() i could do it

function toggle() {
var overlay = document.getElementById("overlay");
overlay.classList.toggle("active");
var popup = document.getElementById("popup");
popup.classList.toggle("active");}

*

*but the exercise require the use of addEventListener.

i'm trying to do it, but i can't figure it out how to make appear the popup, with the following code the console doesn't show any error but i don't see the popup
const overlay = document.querySelector(".profile__edit-form-overlay");
const popup = document.querySelector(".profile__edit-form");

popup.addEventListener('click', function() {});
overlay.addEventListener('click', function() {});

this is my code:

.profile__edit-form-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  content: "";
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
  visibility: hidden;
}

.profile__edit-form-overlay#overlay.active {
  visibility: visible;
}

.profile__edit-form {
  position: fixed;
  top: 21.08%;
  right: 33.5%;
  left: 33.5%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: rgb(255, 255, 255);
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.15);
  border-radius: 10px;
  width: 33.59%;
  min-height: 330px;
  opacity: 100%;
  z-index: 20;
  visibility: hidden;
}

.profile__edit-form#popup.active {
  visibility: visible;
}

Jaques

        <button type="submit" class="profile__edit-button" onclick="toggle()"></button>

Ocean researcher

    <button type="button" class="profile__add-button"></button>

      <button class="profile__edit-form-close-icon" onclick="toggle()"></button>

Edit profile

      <input type="text" placeholder="Name" class="profile__edit-form-first-field">
      <input type="text" placeholder="About me" class="profile__edit-form-second-field">
      <button type="submit" class="profile__edit-form-submit" onclick="toggle()">Save</button>

A: try
document.querySelector('.profile__add-button').addEventListener('click',function (){
        document.querySelector('.profile__edit-form-overlay').style.visibility = 'visible';
    })

the listener is on the button .profile__add-button
remove visibility in css style .profile__edit-form


text:
Q: How to debug openGL code? I have problem with openGL debugging. I find that a lot of the time, OpenGL will show you it failed by not drawing anything. Every time code looks fine but it is not drawing anything on GL window.
For e.g consider the below code.I write it to draw the cube but it is not drawing anything and i am unable to find the cause.
========================================================
// cube_vertex_array.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <glut.h>

static GLfloat vertex[]=
                        {
                            100.0,100.0,0.0,
                            400.0,100.0,0.0,
                            400.0,400.0,0.0,
                            100.0,400.0,0.0,
                            100.0,100.0,-300.0,
                            400.0,100.0,-300.0,
                            400.0,400.0,-300.0,
                            100.0,400.0,-300.0
                    };

static GLfloat color[]=
                        {
                            1.0,0.0,0.0,
                            0.0,1.0,0.0,
                            0.0,0.0,1.0,
                            1.0,1.0,0.0,
                            1.0,0.0,1.0,
                            0.0,1.0,1.0
                        };

static GLubyte frontIndices[] = {0,1,2,3};
static GLubyte leftIndices[] = {1,5,6,2};
static GLubyte backIndices[] = {4,7,6,5};
static GLubyte rightIndices[] = {0,3,7,4};
static GLubyte topIndices[] = {3,2,6,7};
static GLubyte bottomIndices[] = {0,4,5,1};

void init(void)
{
    glClearColor(0.0,0.0,0.0,0.0);                              //Set default background color to black.
    glClearDepth(2.0);                                      //Set the depth level for clearing depth buffer.
    glShadeModel(GL_FLAT);                                  //Set the     shading model to FLAT
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     //Clear the color and depth buffer.
}

void Display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     //Clear the color and depth buffer.

glColor3f(1.0,0.0,0.0);

//glBegin(GL_LINE_STRIP);
//  glVertex3f(0.0,0.0,0.0);
//  glVertex3f(200.0,100.0,0.0);
//glEnd();

glEnableClientState(GL_VERTEX_ARRAY);                   //Enable vertex array.
glEnableClientState(GL_COLOR_ARRAY);                    //Enable vertex array color.

glColorPointer(3,GL_FLOAT,0,color);                     //Specify the array for colors.
glVertexPointer(3,GL_FLOAT,0,vertex);                   //Specify the array for vertex.

glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,frontIndices);      //Draw front face.
glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,leftIndices);       //Draw left face.
glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,backIndices);       //Draw back face.
glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,rightIndices);      //Draw right face.
glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,topIndices);        //Draw top face.
glDrawElements(GL_QUADS,4,GL_UNSIGNED_BYTE,bottomIndices);     //Draw bottom face.

glutSwapBuffers();               //Swap the buffers.
}

void Reshape(int w,int h)
{
    glViewport(0.0,(GLsizei)w,0.0,(GLsizei)h);           //Set the viewport according to new window size.
    glMatrixMode(GL_PROJECTION);                         //Set matrix mode to projection.
    glLoadIdentity();                                    //Replace the top matrix in the stack to the identity matrix.
    gluOrtho2D(0.0,(GLdouble)w,0.0,(GLdouble)h);         //Set the orthographic projection.
    glMatrixMode(GL_MODELVIEW);                          //Set matrix mode to modelview.
}

int main(int argc, char **argv)
{
    glutInit(&argc,argv);                             //Initialize the glut.
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);      //Set display mode and also enable double buffering.
    glutInitWindowSize(500,500);                      //Set the initial window size.
    glutCreateWindow("Cube");                         //Create the window and also assign name to it.
    init();                                           //Initialize the app.
    glutDisplayFunc(Display);                         //Register the Display function.
    glutReshapeFunc(Reshape);                         //Register the Reshape function.
    glutMainLoop();                                   //Start the main loop.
    return 0;
}

A: You have put GL_UNSIGNED_BYTE as the type parameter in glDrawElements(). This will cause openGL to interpret the array of indices you throw in as one byte per index. You should use GL_UNSIGNED_INT here instead.
Here's the working code based on the code your provided (I did port it to java though):
import java.nio.ByteBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import static org.lwjgl.opengl.GL11.*;

public class GLTest {
    public static void main(String[] args) {
        try {
            Display.create();
            Display.setDisplayMode(new DisplayMode(500, 500));
            Display.setResizable(true);

            //the same arrays as the ones you specified.

            float[] vertices = new float[]{100.0f,100.0f,0.0f,
                    400.0f,100.0f,0.0f,
                    400.0f,400.0f,0.0f,
                    100.0f,400.0f,0.0f,
                    100.0f,100.0f,-300.0f,
                    400.0f,100.0f,-300.0f,
                    400.0f,400.0f,-300.0f,
                    100.0f,400.0f,-300.0f};

            float[] color = new float[]{1,0,0,
                    0,1,0,
                    0,0,1,
                    1,1,0,
                    1,0,1,
                    0,1,1};

            int[] frontIndices = new int[]{0, 1, 2, 3};

            //JWJGL bookkeeping..
            ByteBuffer vertexBuffer = BufferUtils.createByteBuffer(vertices.length * 4);
            ByteBuffer colourBuffer = BufferUtils.createByteBuffer(color.length * 4);

            for(int i = 0; i < vertices.length; i++) {
                vertexBuffer.putFloat(vertices[i]);
            }
            vertexBuffer.rewind();

            for(int i = 0; i < color.length; i++) {
                colourBuffer.putFloat(color[i]);
            }
            colourBuffer.rewind();

            ByteBuffer indexBuffer = BufferUtils.createByteBuffer(4 * frontIndices.length);
            for(int i = 0; i < frontIndices.length; i++) {
                indexBuffer.putInt(frontIndices[i]);
            }
            indexBuffer.rewind();

            //back you your code

            glClearColor(1,1,1,1);
            glShadeModel(GL_SMOOTH);

            while(!Display.isCloseRequested()) {
                glViewport(0, 0, Display.getWidth(), Display.getHeight());
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
                glMatrixMode(GL_PROJECTION);
                glLoadIdentity();
                glOrtho(0,Display.getWidth(), 0, Display.getHeight(), -1, 1);
                glMatrixMode(GL_MODELVIEW);
                glLoadIdentity();

                glEnableClientState(GL_VERTEX_ARRAY);
                glEnableClientState(GL_COLOR_ARRAY);

                glColorPointer(3, GL_FLOAT, 0, colourBuffer);
                glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);

                glDrawElements(GL_QUADS, 4, GL_UNSIGNED_INT, indexBuffer);
                Display.update();
                Display.sync(60);
            }
        } catch (LWJGLException e) {
            e.printStackTrace();
        }
    }
}

Which results in:

A: use tools like glTrace / glIntercept (to look at OpenGL call trace), gDebugger (to visualize textures, shaders, OGL state etc.)

A: There is a list of OpenGL debugging tools here : https://www.opengl.org/wiki/Debugging_Tools
Also your code is using the old fixed pipeline which is considered deprecated since OpenGL 3.3, so i would recommend either not putting the tag "opengl-3" on your questions, or using opengl 3.3 core context and learning the "modern" OpenGL (which is more powerful and more difficult to learn but makes you understand how the GPU works).


text:
Q: How was the equation derived? An image of the geometry and the equation in question:

The link of the snapshot provide the equation below
$\eqalignno{l_{{\rm m}}(x)&=4\cdot(x+y_{{\rm i}}+(x-x_{{\rm i}})\cdot\tan\varphi)\cr &=4\cdot\Bigg(x+y_{{\rm i}}+(x-x_{{\rm i}})\cdot{y_{0}-y_{{\rm i}}\over x_{{\rm o}}-x_{{\rm i}}}\Bigg)}$
The $4$ multiplier is used find the total value for $l_{{\rm m}}$, which is replicated for all four quadrants. At the boundary points ($x=x_i$ and $x=x_o$), the equation works.
The equation relates the behavior of $B(x)$ to the inverse of $l_{{\rm m}}$ (see linked image). How does $\tan\varphi$ achieve that behavior?


text:
Q: Ruby on Rails Array access My issue involves an array that is apparently not nil but when I try to access it, it is.
The array is returned from a find on an active record. I have confirmed it is in fact an array with the .class method
@show_times = Showing.find_showtimes(params[:id])
@show_times.inspect =>shows that the array is not empty and is a multidimensional array.
@show_times[0] =>is nil
@show_times[1] =>is nil
@show_times.first.inspect => NoMethodError (undefined method `first')

I am perplexed as to why this is..

A: It's not an array, it's an active record magic structure that mostly looks like an array.  I think you can do to_a on it to get a real array, but then a lot of the magic goes away.

A: find_showtimes is not a built-in finder - if it were, it would return either a single ActiveRecord object or an array of ActiveRecord objects - never a multidimensional array. So the first thing I'd do is have a look a the source of that method.
EDIT: Given your source code (in the comment) - you're actually getting a Hash, not an Array, back from your finder. See the docs for Enumerable's group_by. The Hash is mapping your theater objects to an array of showing objects. This is what you want to do:
Showing.find_showtimes(params[:id]).each do |theater, showtimes|
  puts "Theater #{theater} is showing the movie at #{showtimes.join(', ')}"
end

A: If you're in the console and you want to explore the @show_times object, you can use the keys method to see all the hash keys and then get to individual hash items (such as all the show times) like so:
@show_times[:theater_one]

Same thing will work in your model/view but using each/map/collect would be cleaner as pretty code goes.


text:
Q: Swiper slider custom prev/next navigation I'm building wordpress site with swiper slider (https://idangero.us/swiper/) listing portfolio items. What I need is next button that contains title of next slide. Is that possible? Something like this:
rough preesentation
This is code:
var swiperOptions = {
    loop: true,
    speed: 1000,
}

function portfolioSlider() {
    var portfolioSlider = new Swiper('.js-portfolio-slider', swiperOptions);
    $(document).on('click', '.js-portfolio-slider__next', function(e) {
        e.preventDefault();
        portfolioSlider.slideNext();
    });
}

portfolioSlider();

A: See the documentation here: https://idangero.us/swiper/api/#events
portfolioSlider.on('transitionEnd', function() {
   var nextTitle = $('.swiper-slide-next').find('.title');
   if (nextTitle.length > 0) {
      $('.js-portfolio-slider__next').text(nextTitle);
   }
})

Should do the trick. The 'swiper-slide-next' should be the class of the next slide in your markup

A: Use swiper.slides[index + 1].innerText to get the inner content
Please refer to
penvar swiper = new Swiper('.swiper-container', {
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});

console.log(swiper.slides[1].innerText) visit https://codepen.io/harmeet2harry/pen/qvQWyO


text:
Q: What does "local to a blueprint" mean? I'm having some trouble understanding the difference between Blueprint.errorhandler and Blueprint.app_errorhandler. According the API document(emphasis mine):

errorhandler(code_or_exception)
Registers an error handler that becomes active for this blueprint
  only. Please be aware that routing does not happen local to a
  blueprint so an error handler for 404 usually is not handled by a
  blueprint unless it is caused inside a view function. Another special
  case is the 500 internal server error which is always looked up from
  the application.

AFAIK, a blueprint object in Flask is "a set of operations which can be registered on an application, even multiple times".
My questions are:

*

*How can an error be local to a set of operations?

*How can a view function cause an error?

A: 'local' means that in relation to the routes a blueprint registers. Blueprint routes are always prefixed by the name you registered your blueprint with, so they are naturally grouped and in a URL path topology sense they have locality. 'nonlocal' then is any view not associated with the blueprint; they'll have a different prefix or no prefix at all.
View functions can raise exceptions, and specific exceptions (anything derived from HTTPException) have a HTTP error code associated with them. @blueprint.errorhandler() registers a handler for such exceptions or associated HTTP error codes.
What the documentation is stating is that errors raised during routing (such as the 404 NotFound error) do not have a view yet and therefor you can't route that error to a specific blueprint either.
Under the hood, when routing succeeds to find a view to handle the request, request.blueprint is set to the associated registered blueprint that corresponds to that view. If then an error occurs and an error handler needs to be found, the request.blueprint value lets Flask find 'local' error handlers.


text:
Q: Color of images dulled on mobile On our site http://eatplaygear.com/gear/tops (Joomla, using Virtuemart for the eCommerce)
The desktop version shows the correct colors for the product images.
But somehow on mobile these images are dulled.
I have tried to web-inspect using a Mac and iPhone to see if maybe the src is pointing to another version of the image. But it isn't, the path is the same as the desktop.
Also tried searching there have been previous issues with Joomla Virtuemart, but to no avail.
Any idea what the issue is and how to solve it?
EDIT:
desktop not virtuemart - http://phorge.com.sg/images/desktop-non-virtuemart.jpg
mobile(android) not virtumart - http://phorge.com.sg/images/mobile-non-virtuemart.png
notice how the colors match
desktop virtuemart - http://phorge.com.sg/images/desktop-virtuemart.jpg
mobile(android) virtuemart - http://phorge.com.sg/images/mobile-virtuemart.png
notice how the images on mobile dull out?

A: OK upon doing some trial and errors. apparently it had to do with the color profile when exporting the image. just make sure to use Save for Web if using Adobe softwares and strip the color profile