text:
Q: Roulette program will not recognize correct guess. Why? The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep

funds = 50

### Straight Up number bet = 35:1
### Odd/Even payout = 1:1

class RouletteTable(object):

    def __init__(self, wallet):
        self.wallet = wallet

    def spin(self, bets):
        print "Spinning..."
        sleep(2)
        print "The winner is..."
        sleep(1)
        winner = 25 #randint(0, 36) #FOR TESTING
        print "Number ", winner
        if winner in bets == True:
            bets = True
            return bets

        else:
            print "You bet on: ", bets
            print "Better luck next time."
            bets = False
            return bets

    def game(self):

        while self.wallet >= 0:
            print "\n\nWelcome to Roulette."
            print "Test your luck, and place your bets!"
            print "Current funds: $", self.wallet
            print "\n(1)Place bet or (2)Exit"
            choice = raw_input("> ")

            if choice == "1":
                bets = []
                print '''\n\n\n
          __________
         [     0    ]
         [ 1][ 2][ 3]
         [ 4][ 5][ 6]
         [ 7][ 8][ 9]
         [10][11][12]
         [13][14][15]
         [16][17][18]
         [19][20][21]
         [22][23][24]
         [25][26][27]
         [28][29][30]
         [31][32][33]
         [34][35][36]
         [ODD] [EVEN]

        '''
                print "How much will you bet (per number)?"
                bet_amount = int(raw_input("> $"))
                print "Type a number to bet on, and press Enter."
                print "When finished choosing, just press Enter."
                while True:
                    print "Funds: $", self.wallet
                    print "Current Bets: ", bets
                    number_choice = raw_input("> ")
                    if number_choice != "":
                        bets.append(int(number_choice))
                        self.wallet -= bet_amount

                    else:
                        # start spin
                        self.spin(bets)
                        # payout for bets
                        if bets == True:
                            print "You win $", bet_amount*35
                            self.wallet += bet_amount*35

                        break

            if choice == "2":
                return self.wallet
                break

        if self.wallet == 0:
            print "You're out of money!\n"

roulette = RouletteTable(funds)
funds = roulette.game()

A: Your main error was this:
# start spin
self.spin(bets)
# payout for bets

It should read:
#start spin
bets = self.spin(bets)
# payount bets

the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep

funds = 50

### Straight Up number bet = 35:1
### Odd/Even payout = 1:1

class RouletteTable(object):

    def __init__(self, wallet):
        self.wallet = wallet

    def spin(self, bets):
        print "Spinning..."
        sleep(2)
        print "The winner is..."
        sleep(1)
        winner = 25 #randint(0, 36) #FOR TESTING
        print "Number ", winner
        if winner in bets:
            return True

        else:
            print "You bet on: ", bets
            print "Better luck next time."
            return False

    def game(self):

        while self.wallet >= 0:
            print "\n\nWelcome to Roulette."
            print "Test your luck, and place your bets!"
            print "Current funds: $", self.wallet
            print "\n(1)Place bet or (2)Exit"
            choice = raw_input("> ")

            if choice == "1":
                bets = []
                print '''\n\n\n
          __________
         [     0    ]
         [ 1][ 2][ 3]
         [ 4][ 5][ 6]
         [ 7][ 8][ 9]
         [10][11][12]
         [13][14][15]
         [16][17][18]
         [19][20][21]
         [22][23][24]
         [25][26][27]
         [28][29][30]
         [31][32][33]
         [34][35][36]
         [ODD] [EVEN]

        '''
                print "How much will you bet (per number)?"
                bet_amount = int(raw_input("> $"))
                print "Type a number to bet on, and press Enter."
                print "When finished choosing, just press Enter."
                while True:
                    print "Funds: $", self.wallet
                    print "Current Bets: ", bets
                    number_choice = raw_input("> ")
                    if number_choice != "":
                        bets.append(int(number_choice))
                        self.wallet -= bet_amount

                    else:
                        # start spin
                        did_win = self.spin(bets)
                        # payout for bets
                        if did_win == True:
                            ammount = bet_amount*35
                            self.wallet += ammount
                            print "You win $", ammount

                        break

            if choice == "2":
                return self.wallet
                break

        if self.wallet == 0:
            print "You're out of money!\n"

roulette = RouletteTable(funds)
funds = roulette.game()


text:
Q: LibreOffice commandline convert with template I have a little app to convert a HTML file to ODT, with the soffice command line. I want to add a template to conversion.
Is that possible?
I tried with -n template.ott (from man libreoffice) but not work. The template.ott is a simple template with an image on the header.

A: No according to the help it is not possible.
libreoffice --help
LibreOffice 4.2.7.2 420m0(Build:2)

Usage: soffice [options] [documents...]

Options:
--minimized    keep startup bitmap minimized.
--invisible    no startup screen, no default document and no UI.
--norestore    suppress restart/restore after fatal errors.
--quickstart   starts the quickstart service
--nologo       don't show startup screen.
--nolockcheck  don't check for remote instances using the installation
--nodefault    don't start with an empty document
--headless     like invisible but no userinteraction at all.
--help/-h/-?   show this message and exit.
--version      display the version information.
--writer       create new text document.
--calc         create new spreadsheet document.
--draw         create new drawing.
--impress      create new presentation.
--base         create new database.
--math         create new formula.
--global       create new global document.
--web          create new HTML document.
-o             open documents regardless whether they are templates or not.
-n             always open documents as new files (use as template).

--display <display>
      Specify X-Display to use in Unix/X11 versions.
-p <documents...>
      print the specified documents on the default printer.
--pt <printer> <documents...>
      print the specified documents on the specified printer.
--view <documents...>
      open the specified documents in viewer-(readonly-)mode.
--show <presentation>
      open the specified presentation and start it immediately
--accept=<accept-string>
      Specify an UNO connect-string to create an UNO acceptor through which
      other programs can connect to access the API
--unaccept=<accept-string>
      Close an acceptor that was created with --accept=<accept-string>
      Use --unnaccept=all to close all open acceptors
--infilter=<filter>
      Force an input filter type if possible
      Eg. --infilter="Calc Office Open XML"
--convert-to output_file_extension[:output_filter_name] [--outdir output_dir] files
      Batch convert files.
      If --outdir is not specified then current working dir is used as output_dir.
      Eg. --convert-to pdf *.doc
          --convert-to pdf:writer_pdf_Export --outdir /home/user *.doc
--print-to-file [-printer-name printer_name] [--outdir output_dir] files
      Batch print files to file.
      If --outdir is not specified then current working dir is used as output_dir.
      Eg. --print-to-file *.doc
          --print-to-file --printer-name nasty_lowres_printer --outdir /home/user *.doc
--pidfile file
      Store soffice.bin pid to file.

Remaining arguments will be treated as filenames or URLs of documents to open.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get count of user documents in Google Drive How can I get the list of all users and the number of Google Documents they have in Google Apps using Google Script?
Regards

A: If you're simply looking to list the users and the number of docs, you can use the reports API for Drive activity: https://developers.google.com/admin-sdk/reports/v1/reference/usage-ref-appendix-a/users-docs.
Getting all users uses a similar service, and is practically written for you: https://developers.google.com/apps-script/advanced/admin-sdk-directory.


text:
Q: Why does not Kubernetes pod graceful stop? I have encountered a problem that does not stop immediately even if I delete pod.
What should be fixed in order to terminate normally?
manifest file.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cmd-example
spec:
  replicas: 1
  selector:
    matchLabels:
      app: cmd-example
  template:
    metadata:
      labels:
        app: cmd-example
    spec:
      terminationGracePeriodSeconds: 30
      containers:
      - name: cmd-container
        image: alpine:3.8
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        command: ["/bin/sh"]
        args: ["-c", "while true; do exec sleep 100;done"]

Reproduction procedure

*

*create deployment.
$ kubectl apply -f deployments.yaml

*delete deployment.
kubectl delete-f 020-deployments.yaml
kubectl get po -woutput is.
cmd-example-5cccf79598-zpvmz   1/1       Running   0         2s
cmd-example-5cccf79598-zpvmz   1/1       Terminating   0         6s
cmd-example-5cccf79598-zpvmz   0/1       Terminating   0         37s
cmd-example-5cccf79598-zpvmz   0/1       Terminating   0         38s
cmd-example-5cccf79598-zpvmz   0/1       Terminating   0         38s

This should finish faster.
It took about 30 seconds to complete. Perhaps it is due to SIGKILL at the time of terminationGracePeriodSeconds 30s.
Why is not pod cleanup immediately with SIGTERM?
What should be fixed?
Environment
I confirmed it in the following environment.

*

*Docker for Mac:18.06.1-ce,Kubernetes :v1.10.3

*Docker for Windows:18.06.1-ce,Kubernetes :v1.10.3

*Google Kubernete Engine:1.11.2-gke.15

A: Cause of a problem
This shell is that it does not stop even if it accepts the signal of SIGTERM.
Solution
Using the trap command.
Changed place
    command: ["/bin/sh"]
    args: ["-c", "trap 'exit 0' 15;while true; do exec sleep 100 & wait $!; done"]

Result
after delete, pod was cleaned up as soon!
img-example-d68954677-mwsqp   1/1       Running   0         2s
img-example-d68954677-mwsqp   1/1       Terminating   0         8s
img-example-d68954677-mwsqp   0/1       Terminating   0         10s
img-example-d68954677-mwsqp   0/1       Terminating   0         11s
img-example-d68954677-mwsqp   0/1       Terminating   0         11s

A: Hiroki Matsumoto, the pod termination is behaving just like it was designed to behave.
As you can find in documentation section on Pods:

Because pods represent running processes on nodes in the cluster, it
  is important to allow those processes to gracefully terminate when
  they are no longer needed (vs being violently killed with a KILL
  signal and having no chance to clean up).

Long story short (based on official documentation)
1) When you run kubectl delete -f deployments.yaml you send a command with time of grace period (by default 30 seconds)
2) when you run kubectl get pods you can see it has terminating state
3) Kubelet sees this state and Pod starts to shutdown.
4) After the grace period is over, if there is any processes still running it is killed with SIGKILL
So to delete a pod immediately you have to lower the grace period to 0 and run a forced/immediate deletion:
kubectl delete -f deployments.yaml --grace-period=0 --force and this results in an instant deletion.

A: Your pod literally does nothing.  If you just want something where you can do occasional interactive debugging "inside the cluster", consider kubectl run to get a one-off interactive container
kubectl run --rm -it --name debug --image alpine:3.8

In terms of the command your pod spec is trying to run, rewriting it in shell script form:
#!/bin/sh
# Forever:
while true
do
  # Replace this shell with a process that sleeps for
  # 100 ms, then exits
  exec sleep 100
  # The shell no longer exists and you'll never get here
done

I'm not clear what the pod is trying to do, but it at least won't exit if you remove the exec.  (It will still sit in an idle loop forever.)


text:
Q: Convexity of multi-valued functions Consider multi-valued function $F=(F_1,\cdots,F_d)$ where each $F_j$ is a multi-variate function mapping from $R^d$ to $R$. So $F$ is a function mapping from $R^d$ to $R^d$. Suppose each $F_j$ has simple forms such that their derivatives can be easily calculated
I'm wondering whether there are simple rules to verify that $F$ is convex, meaning that $F$ maps convex sets to convex sets. When $F$ is single valued then one can verify the positive semi-definiteness of its Hessian but for multi-valued $F$ I don't know whether there's a simple rule. for example,

*

*If $F(x)=\exp(Ax+b)$ where $\exp$ means element-wise exponentials. Is $F([0,1]^2)$ convex?

*If $F(x,y)=(e^{-ax}/(1+e^{-ax}+e^{-by}), e^{-by}/(1+e^{-ax}+e^{-by})$ for some $a,b>0$, is $F([0,1]^2)$ convex?


text:
Q: How to get elements with the different value of the same attribute in javascript or jquery? I need to find elements with the different value of the same attribute...
This works-> $data.find("div[data-alpha='1']");
But i need something like this-> $data.find('div[data-alpha='1']' + 'div[data-alpha='2']' ....
So i want to find all elements which have the ,,data-alpha" atribute 1 or 2.
Anyone have an idea how to do that?
Thanks for all answers! Cheers!

A: Use the multiple-selector[docs].
$data.find("div[data-alpha='1'], div[data-alpha='2']")

This allows you to accumulate the results of different selectors by joining the selectors with a comma into a single selector.

A: Try the add() method (http://api.jquery.com/add/).

A: If you want to find all elements with the data-alpha attribute use
$data.find([data-alpha])

If you need elements with specific values, use:
$data.find([data-alpha=x],[data-alpha=y])


text:
Q: Access C++ ASCII Codes via Windows Terminal Where could I find a complete list of ASCII codes that are compatible with C++? I want to use the Windows terminal to do so, as I know there is a way to do so with Linux (showkey -a).
https://linux.die.net/man/1/showkey gives more information for the Linux command, but I'm looking for a line or two that works for Windows.

A: Windows does not have a built-in program like showkey on Linux.

Since you're asking on a question tagged c++ I thought I would write a quick c++ program that does what you're asking:
#include <conio.h>
#include <iostream>

int main()
{
    int c;
    while ((c = _getch()) && (c != 3))
    std::cout << "Keycode: " << c << std::endl;
}

This will only compile for Windows because conio.h is a Windows header. You can exit with Ctrl+Pause/Break.
Edit: I made the program only 3 lines and added support for exiting with Ctrl+C.


text:
Q: How to copy pf status between different systems I need to copy a pf-status of a report. But the programs I want to copy from one to another are in different systems.
Is there any way like download - upload pf-status or something like that ?
Thanks.

A: What you want to do is to transport the program from one system to the other one. Mainly it depends on your authorizations in both systems and on the settings of landscape, but in case you are authorized and the systems are both in the same transport domain, you can do the following (I do that kind of stuff every day):
On source system

*

*start transaction SE09

*create Transport of copies, specify proper target system

*include your report there; the entry will be R3TR PROG <name of your program>

*release Transport of copies

On target system

*

*start transaction STMS

*go to the list of systems (little icon with Truck)

*pick the target system there

*you get the list of the transports ready for import

*click refresh and your transport should show at the bottom of the list

*point a cursor on it and trigger the transport

*if everything goes right, your entire report is now in target system

A: You could try SAPLink. It does require that you install SAPLink on both ABAP systems, but after that transferring objects from one to the other is much simpler.
The other option would be to enlist the help of a Basis person, create a transport and have them import it to the target system. But generally, that is not likely to happen.


text:
Q: Vector cross product properties? I have a 3x3 symmetric matrix
$$C=AB^T+BA^T,$$
where both $A$ and $B$ are 3x1 vectors.
How may I prove
$$C(A\times B)=0?$$
I believe the key is the properties of vector cross product.

A: Hint.  For any $3\times1$ vectors $u,v$ we have
$$\def\v#1{{\bf#1}}
  \v u^T\v v=\v u\cdot\v v\ .$$
In particular,
$$B^T(A\times B)=B\cdot(A\times B)\ .$$
There is a very important fact that you should know about this kind of expression involving both the dot and cross products.
Comment.  My first equation is not correct, strictly speaking, since the LHS is a matrix and the RHS is a scalar.  However, there is no important difference between a $1\times1$ matrix and a scalar.


text:
Q: Second Scraper - If Statement I am working on my second Python scraper and keep running into the same problem.  I would like to scrape the website shown in the code below.  I would like to be ability to input parcel numbers and see if their Property Use Code matches.  However, I am not sure if my scraper if finding the correct row in the table. Also, not sure how to use the if statement if the use code is not the 3730.
Any help would be appreciated.
from bs4 import BeautifulSoup
import requests
parcel = input("Parcel Number: ")
web = "https://mcassessor.maricopa.gov/mcs.php?q="
web_page = web+parcel
web_header={'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_13_2)AppleWebKit/537.36(KHTML,likeGecko)Chrome/63.0.3239.132Safari/537.36'}
response=requests.get(web_page,headers=web_header,timeout=100)
soup=BeautifulSoup(response.content,'html.parser')
table=soup.find("td", class_="Property Use Code" )
first_row=table.find_all("td")[1]
if first_row is '3730':
    print (parcel)
else:
   print ('N/A')

A: There's no td with class "Property Use Code" in the html you're looking at - that is the text of a td. If you want to find that row, you can use
td = soup.find('td', text="Property Use Code")

and then, to get the next td in that row, you can use:
otherTd = td.find_next_sibling()

or, of you want them all:
otherTds = td.find_next_siblings()

It's not clear to me what you want to do with the values of these tds, but you'll want to use the text attribute to access them: your first_row is '3730' will always be False, because first_row is a bs4.element.Tag object here and '3730' is a str. You can, however, get useful information from otherTd.text == '3730'.


text:
Q: vue.js - How to split array of objects into multiple div columns Here is my vue layout:
<template lang="pug">
  .row
    .col-4(v-for="article in articles") // need to render 1-3 items here
      | {{ article.name }}
  .row
    .col-4(v-for="article in articles") // need to render 4-6 items here
      | {{ article.name }}
</template>

The Goal is:

article[0].name

article[1].name

article[2].name

article[3].name

article[4].name

article[5].name

In Python based Micro Framework like Flask and Jinja, it's possible to do in this way:
{% for article_row in articles | batch(3, ' ') %}

    {% for article in article_row %}

{{ article }}

    {% endfor %}

{% endfor %}

So, is there a way to do like above in vue.js?

A: a combination of v-for="(article,i) in articles" and v-if="i>=0 && i<3"

A: I would use helper groups array to render groups of articles in rows:
<template lang="pug">
  .container
    .row(v-for="(group, i) in articleGroups")
      .col-4(v-for="article in articles.slice(i * itemsPerRow, (i + 1) * itemsPerRow)")
        | {{ article.name }}
</template>

Demo: https://codesandbox.io/s/rj60o8l5p

A: I'd use a computed property to chunk them up. If you have lodash available you can do:
computed: {
  chunked () {
    return _.chunk(this.articles, 3)
  },
},

You can find the logic for chunking all over the place if you don't have lodash around this will work.
function chunk (arr, len) {

  const chunks = []
  const i = 0
  const n = arr.length

  while (i < n) {
    chunks.push(arr.slice(i, i += len))
  }

  return chunks
}

Then, you can do:

    {{ article.name }}

A: Using .reduce you can break your array into groups of X.
<template>

        <template v-for="group in groupedArticles">

                    {{ article.title }}

        </template>

</template>

A: The simpler way to use lodash.chunk() function in your code is:
<template lang="pug">
  .row(v-for="column in articles")
    .col-4(v-for="article in column")
      | {{ article.name }}
</template>

Refer here for a detailed explanation of lodash.chunk() function: https://dustinpfister.github.io/2017/09/13/lodash-chunk/


text:
Q: NextJS Site Still Broken On Gh-Pages With basePath and assetPrefix I built a website with next.js that works locally (code: https://github.com/xpress-smoke-shop/website).
I am now trying to deploy a static html version of the site to the domain: https://xpress-smoke-shop.github.io/website/
I can clone the repo and run these commands:
nvm use
yarn install
yarn build
yarn export
yarn deploy-gh

And I have changed the next.config.js file to reflect the repository that I'm using:
/* eslint-disable import/no-extraneous-dependencies */
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  poweredByHeader: false,
  trailingSlash: true,
  basePath: '/website',
  assetPrefix: '/website/',
  reactStrictMode: true,
});

But my deployed site still looks wrong and has all these file-not-found errors...

How do I get this to deploy properly??


text:
Q: Probability that all roots of a polynomial are real Consider a random polynomial $p(t) = \sum_{i=0}^n a_i t^i$ where $a_0, … , a_n$ are i.i.d. distributed $\sim U[0; 1]$. What is the probability, that all its roots are real.
That probability is neither $0$ nor $1$, since both the set of all polynomials with distinct real roots and the set with distinct, but not all real roots are open, and the probability that our polynomial has repeated roots is $0$.
Alternatively, the set of all polynomials wis complex roots can be characterised as the one of all polynomials divided by $x^2 + bx + c$ for some $b, c \in \mathbb{R}$ such that $b^2 < 4c$. However, this alternative characterisation does not seem to be helpful in calculating the probability.
For $n\in \{0; 1\}$ the probability of all real roots is trivially $1$.
For $n=2$ it is $$P(a_1^2 > 4a_0a_2) = 1 - 2E[\sqrt{a_0a_2}] = 1 - 2E[\sqrt{a_0}]E[\sqrt{a_2}] = 1-2(\int_0^1 \sqrt{x}{dx})^2 = 1 - 2(\frac{2}{3})^2 = \frac{1}{9}$$


text:
Q: Adding protorpc url variables Is there a way to add a variable in the protorpc service path? Similar to webapp2 url templates.

A: I think you are looking for a resource container:
from https://developers.google.com/appengine/docs/python/endpoints/getstarted/backend/write_api_post
ID_RESOURCE = endpoints.ResourceContainer:

MULTIPLY_METHOD_RESOURCE = endpoints.ResourceContainer(
        Greeting,
        times=messages.IntegerField(2, variant=messages.Variant.INT32,
                                    required=True))

@endpoints.method(MULTIPLY_METHOD_RESOURCE, Greeting,
                  path='hellogreeting/{times}', http_method='POST',
                  name='greetings.multiply')
def greetings_multiply(self, request):
    return Greeting(message=request.message * request.times)


text:
Q: Clever bounty reputation hack I say "hack" in the most favorable light. It's a clever idea and theoretically beneficial.
I noticed that an old question of mine suddenly started getting a lot of renewed attention. The question had been answered, with an answer accepted. But another user added a well reasoned and insightful answer to the list. He also opened a +100 bounty on that question.
The resulting increased attention quickly got his answer quite a lot of up-votes. Well more than the 100 points he had spent on the bounty. Therefore, he gets a net rep profit out of the transaction.
So here's the hack:

*

*Find an interesting question

*Research and provide a very good answer

*Open up a bounty on that question to attract attention and votes to your new answer

*Profit!!!

2 and 3 may be out of order--I didn't see the timing of it. But either way, assuming he gets more than 10 votes, he still gets increased rep out of the deal.
I don't think this is necessarily bad for SO - it does generate some useful discussion and insightful answers. Plus you can increase your own rep very rapidly by making your answers highly visible, and therefore frequently voted upon.
However, it does slightly change the meaning and purpose of bounties away from starting a discussion and toward self-promotion. Still, interesting.

A: So, you make an old question tons better with an awesome answer and pay 100 reputation for the privilege. I am not following where the Stack Overflow community are losing out.

Note: we added a few more checks and balances

*

*If you are placing a bounty on a question you answered, your minimum spend is 100

*If you are placing a repeat bounty on a question, your minimum spend doubles till it reaches 500

A: I do this on some questions where I put a lot of effort into them, it attracts attention and I'm not sure if it's considered ethical or not, but I like upvotes for an answer I spent a lot of time on.
At the end of the day nothing bad comes of it, and the SO community has another really good answer.

A: Maybe said user just wanted to make sure their (possibly more correct?) answer got adequate awareness compared to other answers? It's their reputation after all, so maybe they want to challenge the community to find an even better answer?

A: I have refined the hack:

*

*Find an interesting question

*Research

*Open up a bounty on that question to attract attention and votes to your new answer

*Provide a very good answer

*Profit!!!

That almost doubles the ROI. Almost - as +100 bounty draws more attention than +50 one.


text:
Q: very quick issue about php in assigning variable i have this quick issue
i want to add a number 1 before the $_POST[];
$fileName = "1"'.$_POST['name'].'"";

what am i doing wrong? because it's not giving me any result! Thanks!
ps.i know the question is dumb...

A: You can use
$fileName = "1" . $_POST['name'];

Or
$fileName = "1 {$_POST['name']}";

A: Try like this...
$fileName = "1".$_POST['name'];

A: Use either of the following:
$fileName = '1' . $_POST['name'];

or
$fileName = "1" . $_POST['name'];

or
$fileName = "1{$_POST['name']}";


text:
Q: Can I create host-specific users in Postgres? (ex: postgres@localhost) My Question
Can I set permissions on a user (ex: postgres) such that that user is only allowed to login from TCP localhost, but not the Internet?
Trusted Sockets vs Passwords for Remotes
I get that you can initialize postgres to allow local users to login without a password, and remote hosts to login with a password:
initdb \
            -D "$POSTGRES_DATA_DIR/" \
            --username postgres --pwfile "$PWFILE" \
            --auth-local=trust --auth-host=password

Intranet vs Internet
For any system that's connecting across the internet I want to use a user that has a very, very strong (non-memorable) random 128-bit string.
For local and intranet access, however, I'd prefer to be able to have a username and password that I can remember (and type).
Can I do this... or do I just have to set up one user per system that's allowed to connect, with a .pgpass on each?
(I don't want to share keys in plaintext files between computers)

A: You haven't provide any info about your PostgreSQL version, I assume you're using PostgreSQL 12.

Can I set permissions on a user (ex: postgres) such that that user is only allowed to login from TCP localhost, but not the Internet?

Yes, use pg_hba.conf. You may want to load this first via hba_file runtime configuration.

For local and intranet access, however, I'd prefer to be able to have a username and password that I can remember (and type).

If you want to add a local-only user protected with a password, add
local <database_name> <local-only_user_name> scram-sha-256

in your pg_hba.conf.
You probably want to create the user first via CREATE ROLE:
CREATE ROLE username LOGIN ENCRYPTED PASSWORD 'insert-your-password-here';

You may also want to check host and hostssl record entry to add to your pg_hba.conf to configure your intranet and internet based authentication.
Check linked documentations for more info.


text:
Q: Why on iPad, self.clearsContextBeforeDrawing = NO; won't make the drawRect not clear itself before drawing I have a TestView inherited from UIView, and everything is drawn on the screen using its drawRect method.
But if I don't want drawRect to clear the view before drawing, I used
self.clearsContextBeforeDrawing = NO;
self.opaque = NO;   // also added because the doc says the rect
                    //   passed to drawRect will be filled with
                    //   background color first if it is set to YES

in the initWithFrame method.
The drawRect method is invoked by using
[self.view setNeedsDisplay];

in the ViewController event handler. (for touchesMoved events)
But still, everything is cleared before anything is drawn?  How to make it work?

A: I think this answers your question. From the answer:

You cannot prevent the contents from being erased by doing the following:
[self setClearsContextBeforeDrawing: NO];
This is merely a hint to the graphics engine that there is no point in having it pre-clear the view for you, since you will likely need to re-draw the whole area anyway. It may prevent your view from being automatically erased, but you cannot depend on it.


text:
Q: Docker build for Mattermost, /bin/sh dnf not found I've got a CentOS 8 install, and I'm trying to use a docker container to run Mattermost to set up a local node for my family to use. I've been searching a lot online, but my google-fu appears to be weak as I can't get answers that address my issue.
I've downloaded docker, and docker compose using the following guide, again tailoring it to Centos - https://docs.mattermost.com/install/prod-docker.htm I've successfully run the "Hello World" container.
I'm using this guide and trying to tailor the Mattermost container install - https://wiki.archlinux.org/index.php/Ma ... ith_Docker
I've edited the ~/mattermost-docker/db/Dockerfile to remove references to apk, and put in yum and then dnf, and tried to execute with SUDO in the script and using SU account to run the script. Latest Dockerfile:
FROM postgres:9.4-alpine

ENV DEFAULT_TIMEZONE UTC

# Install some packages to use WAL
RUN echo "azure<5.0.0" > pip-constraints.txt
RUN dnf install -y \
      build-base \
      curl \
      libc6-compat \
      libffi-dev \
      linux-headers \
      python-dev \
      py-pip \
      py-cryptography \
      pv \
      libressl-dev \
    && pip install --upgrade pip \
    && pip --no-cache-dir install -c pip-constraints.txt 'wal-e<1.0.0' envdir \
    && rm -rf /tmp/* /var/tmp/* \
    && dnf clean all

# Add wale script
COPY setup-wale.sh /docker-entrypoint-initdb.d/

#Healthcheck to make sure container is ready
HEALTHCHECK CMD pg_isready -U $POSTGRES_USER -d $POSTGRES_DB || exit 1

# Add and configure entrypoint and command
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["postgres"]

VOLUME ["/var/run/postgresql", "/usr/share/postgresql/", "/var/lib/postgresql/data", "/tmp", "/etc/wal-e.d/env"]

However it still fails on: docker-compose build
Error -
Building db
Step 1/10 : FROM postgres:9.4-alpine
 ---> 4e66908aa630
Step 2/10 : ENV DEFAULT_TIMEZONE UTC
 ---> Using cache
 ---> 03d176f9f783
Step 3/10 : RUN echo "azure<5.0.0" > pip-constraints.txt
 ---> Using cache
 ---> 35dbc995f705
Step 4/10 : RUN sudo dnf install -y       build-base       curl       libc6-compat       libffi-dev       linux-headers       python-dev       py-pip       py-cryptography       pv       libressl-dev     && pip install --upgrade pip     && pip --no-cache-dir install -c pip-constraints.txt 'wal-e<1.0.0' envdir     && rm -rf /tmp/* /var/tmp/*     && dnf clean all
 ---> Running in 4b89205fdca3

/bin/sh: dnf: not found

ERROR:Service 'db' failed to build : The command '/bin/sh -c sudo dnf install -y       build-base       curl       libc6-compat       libffi-dev       linux-headers       python-dev       py-pip       py-cryptography       pv       libressl-dev     && pip install --upgrade pip     && pip --no-cache-dir install -c pip-constraints.txt 'wal-e<1.0.0' envdir     && rm -rf /tmp/* /var/tmp/*     && dnf clean all' returned a non-zero code: 127````

Confirmed dnf, and yum are present in /bin and /usr/bin, confirmed /bin/sh -> /bin/bash. I'm not even sure what question I should be asking, so I'd appreciate some assistance in figuring out how I can get this container stood up.

Thanks.


text:
Q: php ini class cannot see whats going wrong im trying to create a php class that will transform an ini in to an array ie:
example.ini...
[helloworld]
testing=1234

the array should look like:
array {
    "helloworld" = array {
        "testing" = "1234"
    }
}

my code fo far is this:
<?php
    require_once "UseFullFunctions.inc.php";

    class INI {
        protected $Keys = array();
        protected $Values = array();

        public function __construct($FileName) {
            if (!file_exists($FileName)){
                throwException('File not found',$FileName);
            }
            $File = fopen($FileName, 'r');
            $isIn = "";
            while (($line = fgets($File)) !== false) {
                if(!startswith($line,'#')){  // checks if the line is a comment
                    if(startswith($line,'[')){
                        $isIn = trim($line,'[]');
                        $this->Keys[$isIn] = '';
                        $this->Values[$isIn] = array();
                    } else {
                        if ($isIn != ""){
                            $vars = explode("=",$line);
                            $this->Values[$isIn][$vars[0]] = $vars[1];
                        }
                    }
                }
            }
            var_dump($this->Values);
            if (!feof($File)) {
                echo "Error: unexpected fgets() fail\n";
            }
            fclose($File);
        }
        public function getValues() {
            return $this->Values;
        }
    }
?>

the other functions(starts with, throwexception) ive already tested and work fine but it still returns a blank array i think its stuffing up just after it checks if the line is a comment but it doesnt come up with an error messages so i cant be sure
just incase here is my starts with code:
function throwException($message = null,$code = null) {
    throw new Exception($message,$code);
}

function startsWith($haystack, $needle)
{
    return !strncmp($haystack, $needle, strlen($needle));
}

A: Take a look at parse_ini_file
http://uk3.php.net/parse_ini_file


text:
Q: Does a variety contain a cartesian product of two curves? We are given an affine variety $V\subset \mathbb{A}^n\times\mathbb{A}^n$, and wish to know if it contains a product of the form $C_1\times C_2$, where $C_1$ and $C_2$ are two curves in $\mathbb{A}^n$. First, is there an algorithm to decide this? Second, is it true that if $V$ is of degree $d$ and does contain a product of the form $C_1\times C_2$, then $V$ contains a product of the form $C_1\times C_2$ with $\deg C_1,\deg C_2\leq f(d,n)$, for some function $f$?

A: Yes, there is such an algorithm. There is an effectively computable constant $N$ such that if $V$ contains a product $S\times T$ where $S,T$ are $N$-point sets, then $V$ contains product of two curves. It is actually true even in the semialgebraic setting. The result is Theorem 1.9 from http://arxiv.org/abs/1207.0705
[ Apologies for answering my own question with a reference to my own paper. When I asked the question, I did not know the answer. ]


text:
Q: how to split a vector to sub-vector based on the first part of the split Suppose I have a vector of length 10. Suppose further that I want to split this vector to two sub-vectors. This is fine. However, Suppose that the second sub-vector is based on the first sub-vector. For example,
let Par <- c(0.6,0.5,0.7,0.4,0.6,0.9,0.2). Then, suppose that I would like to split it into two sub-vectors i.e.,
par1 <- Par[1:5] and I would like the second sub-vector to be the last two values of Par. So, I can use par2 <- Par[5:7]. That is fine. However, Suppose that I want to do it automatically. That is if par1 is a vector of n values of Par then par2 is a vector of the remaining values.  For example, if I have length(parnew1) = 5 and length(parnew2=3) then, I would like to have like this:
par1 <– Par[1:length(parnew1)]
and
par2 <- Par[?:length(parnew2)] I put ? here because I do not know how to start here. I would like to start from where the par1 ends.
Any help, please?

A: You can include operations inside the indexing in R. For example, if you set your length of parnew1 you can create parnew1 and parnew2 like this. Note the difference between the variable defined as length_parnew1 and the function call length(Par).
Par <- c(0.6,0.5,0.7,0.4,0.6,0.9,0.2)
length_parnew1 <- 5
parnew1 <- Par[1:length_parnew1]
parnew1
#> [1] 0.6 0.5 0.7 0.4 0.6
parnew2 <- Par[(length_parnew1 + 1):length(Par)]
parnew2
#> [1] 0.9 0.2

Created on 2018-03-01 by the reprex package (v0.2.0).


text:
Q: Google email offline access using react native expo app I am creating one app using react native expo,  which allow end user to login by their google account , and then applicaton try to save the access_token so that server based applicatin can use this to send the email on their behalf ,
But when using google sing in , i am not getting refresh token and not able to send the email ,
Here is code example which i am using
I tried below method to get the access request
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
    clientId: "XXXXXXX",
      androidClientId:"XXXXXXX",
      iosClientId:"XXXXXXX"
  });
  const [initializing, setInitializing] = useState(true);
  const [user, setUser] = useState();
  const sendNotification=useNotification()
  //console.log(sendNotification)
  useEffect(() => {
    if (response?.type === "success") {
      const { id_token } = response.params;
      const auth = getAuth();
      const credential = GoogleAuthProvider.credential(id_token);
      signInWithCredential(auth, credential);
      let decoded = jwt_decode(id_token);
      socialLogin(decoded)
    }
  }, [response]);

And on server using this code to sending email
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
// Replace with the code you received from Google
const code = 'XXXXXXX';
//const code="XXXXXXX"
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.getToken(code).then(({ tokens }) => {
  console.log('first')
  const tokenPath = path.join(__dirname, 'token.json');
  fs.writeFileSync(tokenPath, JSON.stringify(tokens));
  console.log('Access token and refresh token stored to token.json');
}).catch(err=>console.log(err));

A: async function signInWithGoogleAsync() {
  try {
    const result = await Google.logInAsync({
      androidClientId: YOUR_CLIENT_ID_HERE,
      scopes: ["profile", "email"],
    });
    if (result.type === "success") {
      onSignIn(result);
      return result.accessToken;
    } else {
      return { cancelled: true };
    }
  } catch (e) {
    return { error: true };
  }
}

A: Well, I tried to create an application with Google login. To use the Google Sign-In method in a React Native Expo app, you will need to perform the following steps:

*

*Set up a project in the Google Cloud Console and obtain a configuration file for your app.

*Install the expo-google-sign-in package in your React Native app.

*Import the GoogleSignIn object from the expo-google-sign-in package and use the initAsync method to initialize the Google Sign-In process.

*Use the GoogleSignIn.askForPlayServicesAsync method to check if the device has the required Google Play Services installed.

*Use the GoogleSignIn.signInAsync method to prompt the user to sign in with their Google account.

*Once the user has signed in, you can use the accessToken and refreshToken properties of the returned object to make authorized requests to the Google APIs.

The code lines for the above steps are:
import { GoogleSignIn } from 'expo-google-sign-in';

// Initialize the Google Sign-In process

await GoogleSignIn.initAsync({
  // Your config. values
});

// Check if the device has the required Google Play Services installed

const isPlayServicesAvailable = await GoogleSignIn.askForPlayServicesAsync();
if (!isPlayServicesAvailable) {
  console.error('Google Play services are not available on this device.');
  return;
}

// Prompt the user to sign in with their Google account

const { accessToken, refreshToken } = await GoogleSignIn.signInAsync();


text:
Q: Google Drive SDK Push Notifications - watch changes on all files? The recently launched Push Notifications service is very cool and looks as a big improvement over polling that was previously necessary.
I am wondering though how to enable watching of all files in shared folder on Drive. We are working on Drive monitoring tool, that keeps list of all changes and enables reporting for whole enterprise Drive folders.
I am aware that I can use the notifications about new objects in Changes feed. Unfortunately, you are not able to detect the what has changed from Changes resource.
When watching File resources, you can receive notifications that say what has been changed about the file (parents, permissions, metadata etc.). This is great, however it seems that is not possible to register Push Notification handler for all files in Drive. The docs says you always need to provide fileId. That would mean to make watch requests for millions of files in our scenario (not mentioning renewing the Push API channels each now and then).
Do you know of any more suitable way than using Changes notifications and detect what has been changed manually (which is quite a lot of API calls and rather slow to do).

A: Long story short, no.
Push Notification for now only supports watching on Files and Changes. As you might know, folders in Google Drive is File with special mimeType. That is, you can watch on a specific folder by making Files.Watch() request to a folder. However, it will only tell you changes in its direct children, not recursively, which is probably not what you wanted.
The best approach you could take is to make copy of all file's metadata to your application and compare it when any changes happened. I know this is not very efficient, but for now, this is the only way you could achieve this goal.
And if you ask me if the feature you want will be created, not likely. Push notifications is not only for Drive API. It is designed for all Google API to watch on any API resource and detect their changes. Basically, when you make Files.Watch() request, it keeps copy of the result of Files.get() and let you know when anything changed. That is the reason why Files.watch has a lot more useful details. For Changes, it tells you whenever there is changes in Changes.list(). Thus, it cannot tell you anything better than what Changes resource can currently do. From its design, I don't think the feature you want will be added to Drive API.


text:
Q: Custom iOS keyboard: how to adjust the keyboard frame based on different iPads Here's the issue:
So I'm building a custom iOS keyboard on iPad and naturally, I want it to work on multiple iPads. I have it set it up so that the UIView is made in an XIB and instantiated in my InputViewController. Right now, it's set to the frame that is specified in my XIB. I want the keyboard to be in the lower 3rd of my screen, covering the width of the screen so there's no overflow.
I've tried adjusting the frame in viewDidLoad() in my InputViewController, in awakeFromNib(), in viewDidLayoutSubviews(), and in viewWillAppear(), but when I've tried those, only a black screen appears.
Here's my code (the view is bibleKeyboardView)
class KeyboardViewController: UIInputViewController {

    // A property to hold reference to a BibleKeyboardView object
    var bibleKeyboardView: BibleKeyboardView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // An instance of BibleKeyboardView is added to the controller's root inputView
        let nib = UINib(nibName: "BibleKeyboardView", bundle: nil)
        let objects = nib.instantiate(withOwner: nil, options: nil)
        bibleKeyboardView = (objects.first as! BibleKeyboardView)
        guard let inputView = inputView else { return }
        inputView.addSubview(bibleKeyboardView)

        // controls visibility of the globe key
        bibleKeyboardView.setNextKeyboardVisible(needsInputModeSwitchKey)

        // adds automatic handle switching to glove key
        bibleKeyboardView.nextKeyboardBtn.addTarget(self,
                                                    action:
                                                    #selector(handleInputModeList(from:with:)),
                                                       for: .allTouchEvents)

        bibleKeyboardView.delegate = self

        let screenBounds = UIScreen.main.bounds
        let screenWidth = screenBounds.width
        let screenHeight = screenBounds.height

        // This is the part that was causing my blank screen
        bibleKeyboardView.frame = CGRect(x: 0, y: screenHeight * 0.67, width: screenWidth, height: screenHeight * 0.33)
}

Here's a pic of my keyboard view if that's helpful

Here's a pic of the keyboard when I try to assign bibleKeyboardView.frame

Any help would be much appreciated! This has got me stumped for the past few days.


text:
Q: SimpleSAMLPHP NoState error i have two simplesamlphp servers set up, they are both on the same physical server but separated by virtualhost. they are currently at the domains.
id.saml.domain.com <- Identity provider
sp.saml.domain.com <- Service provider
I also have a third site, the webs application that i actually intend to implement single sign on at. we'll call that
test.domain.com/webapplication
i have the service provider and the identity provider talking to each other using example-auth. i can go to the service provider, click 'test authentication sources', get sent to the identity server, and then get a login prompt, enter the example credentials, click submit, and get sent back to the service provider.
at this point, everything looks good.
my problem is, when i try to implement the service provider in the website.
i have the following login code in place to call the service provider code
    $lib = "/ltsites/saml/service/lib";
    $sp = "default-sp";  // Name of SP defined in config/authsources.php

    try {
        // Autoload simplesamlphp classes.
        if(!file_exists("{$lib}/_autoload.php")) {
            throw(new Exception("simpleSAMLphp lib loader file does not exist: ".
            "{$lib}/_autoload.php"));
        }

        include_once("{$lib}/_autoload.php");
        $as = new SimpleSAML_Auth_Simple($sp);

        // Take the user to IdP and authenticate.
        $as->requireAuth();
        $valid_saml_session = $as->isAuthenticated();

    } catch (Exception $e) {
        // SimpleSAMLphp is not configured correctly.
        throw(new Exception("SSO authentication failed: ". $e->getMessage()));
        return;
    }

    if (!$valid_saml_session) {
        // Not valid session. Redirect a user to Identity Provider
        try {
            $as = new SimpleSAML_Auth_Simple($sp);
            $as->requireAuth();
        } catch (Exception $e) {
            // SimpleSAMLphp is not configured correctly.
            throw(new Exception("SSO authentication failed: ". $e->getMessage()));
            return;
        }
    }

    // At this point, the user is authenticated by the Identity Provider, and has access
    // to the attributes received with SAML assertion.
    $attributes = $as->getAttributes();

it does forward me all the way to the identity server and asks for credentials. but upon returning to the service provider i get the error
State information lost
SimpleSAML_Error_NoState: NOSTATE

i found this wiki page https://code.google.com/p/simplesamlphp/wiki/LostState, but nothing i did after reading it (like changing the 'session.cookie.domain' in config\config.php, which just sent the pages into an infinite refresh loop) worked
does anyone have any ideas? did i set it up incorrectly? i'm thinking maybe the web application itself has to be the service provider? i.e. test.domain.com/webapplication/simplesaml/ so that the two are on the same domain?

A: You can try change the session store.type in config.php. You can do it in the service provider or identity provider. Some way that the two have different session storages. Works for me.


text:
Q: IF condition not working in stored procedure I want to run a stored procedure provided it meets an IF condition but this condition keeps failing. Its always returning false. From my database, @count_log is supposed to return 0. If I hard-code @count_log to be equal to 0, it works. This is my code below. Please what could be the problem?
CREATE DEFINER=`root`@`localhost` PROCEDURE `approve`(IN `userID` INT, IN `logID` INT, OUT `res` INT)
BEGIN
    DECLARE count_log INT;
    declare exit handler for sqlexception
    BEGIN
        -- ERROR
        rollback;
    END;

    declare exit handler for sqlwarning
    BEGIN
        -- warning -
        rollback;
    END;
        SET @count_log = (SELECT COUNT(*) FROM Logs WHERE logId = logID);
        -- Confirm has not been treated --

        IF(@count_log = 0) THEN

        START transaction;
            -- Update table

        COMMIT;
        SELECT FOUND_ROWS() INTO res;
       END IF;

    END

If

A:
... WHERE logId = logID

That's true for every row, so as long as there is any record in Logs, (SELECT COUNT(*) FROM Logs WHERE logId = logID) will return a value lager than 0.
You supposedly mean to compare the column of the table with the passed parameter of the same name. Try to qualify one of them with the table name. As the parameter takes precedence that will mean the qualified one resolves to the table column, the other to the parameter.
(SELECT COUNT(*) FROM Logs WHERE Logs.logId = logID)

Or rename the parameter.
See "C.1 Restrictions on Stored Programs" for more information about the precedence:

*

*A routine parameter takes precedence over a table column.

A: Your parameter name is in conflict with the parameter name (as @sticky_bit describes).  Simply use better naming conventions:
CREATE DEFINER=`root`@`localhost` PROCEDURE `approve`(
    IN in_userID INT,
    IN in_logID INT,
    OUT out_res INT
)
BEGIN
    DECLARE v_count_log INT;
    . . .
    SELECT v_count_log := COUNT(*)
    FROM Logs l
    WHERE l.logId = in_logID;

    . . .
END;


text:
Q: Dúvida sobre contexMenuStrip
É o seguinte, eu preciso adicionar essas ferramentas, exatamente como mostra na imagem.
Preciso só de um empurrão, sobre como começar.

Inserir texto
Inserir Imagem
Excluir (botão)

CODE
namespace frmLoginRPG
{
    public partial class frmMenuPrincipal : Form
    {
        private readonly Button[] _todosBotoes;
        public frmMenuPrincipal()
        {

            InitializeComponent();
            //Passo 1

            _todosBotoes = _mainPanel.Controls.OfType<Button>().ToArray();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            //Passo 2.1
            var controles = _todosBotoes.Where(btnRifts => (btnRifts.Tag as String ?? btnRifts.Text).ContainsIgnoreCase(txtBuscarJogo.Text)).ToArray();
            //Passo 2.2
            _mainPanel.Controls.Clear();
            //Passo 2.3
            _mainPanel.Controls.AddRange(controles);
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void btnAdicionar_Click(object sender, EventArgs e)
        {

            Button button = new Button(); //criando botão
            button.Size = _todosBotoes[0].Size; //criando botão, puxando o tamanho dos outros botões
            button.BackColor = Color.AliceBlue; //definindo cor do botão
            _mainPanel.Controls.Add(button); //Adicionando botão no _mainPanel
            button.ContextMenuStrip = this.contextMenuStrip1; //Adicionando contextMenuStrip assim que o Botão for criado.

            MessageBox.Show("                  CRIADO        ");

        }
    }

}
namespace MyMethod
{
    public static class MyExtensions
    {
        public static bool ContainsIgnoreCase(this string source, string search)
        {
            return source.IndexOf(search, StringComparison.CurrentCultureIgnoreCase) >= 0;
        }
    }
}
`

A: Você cria um contextMenu e define ele na propriedade do Button, no evento do click você saberá de qual button veio o click pelo sender:
    private void inserirTextoToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string name = ((Button)sender).Name;
        MessageBox.Show("Você clicou para inserir no botão: " + name);
    }

    private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string name = ((Button)sender).Name;
        MessageBox.Show("Você clicou para excluir o botão: " + name);
    }


text:
Q: query a set of elements, but in a particular order I have a bunch of <div> elements, each of which has a name. I would like to query the <div> elements using jQuery, but I want them to come by alphabetical order with respect to name. The usual code
$("div").doStuff()

doesn't return the elements in any special order.

A: I don't see any way to do this other than getting the list of elements into a normal JS array, sorting that array by name, putting them back into a jQuery object then calling your final operation on them in that sorted order.
function compareNameAlpha(a, b) {
   var n1 = a.getAttribute("name");
   var n2 = b.getAttribute("name");

   if (n1 < n2) return(-1);
   if (n1 == n2) return(0);
   return(1);
}

var elArray = $("div").toArray().sort(compareNameAlpha);
$(elArray).doStuff();

or done all in one line:
$($("div").toArray().sort(compareNameAlpha)).doStuff();

Working demo here: http://jsfiddle.net/jfriend00/qeLfX/

Edit: There appears to be an even simpler way to do this as jQuery supports .sort() directly (though it is marked in the jQuery source as for internal use only).  You can do this:
$("div").sort(compareNameAlpha).each(doStuff);

And see that version here http://jsfiddle.net/jfriend00/hJhhf/

A: $($("div").get().sort(function(a,b){
    if($(a).attr("name") === $(b).attr("name"))
        return 0;
    return $(a).attr("name") < $(b).attr("name") ? -1 : 1;
})).each(function(){ $(this).doStuff(); });

A: The following code is untested, but I think you could do something along the lines of the following:
$($("div").get().sort(sortFn)).each(doStuff);

where sortFn is a proper argument to Array.sort that sorts elements by name attributes.


text:
Q: how to derive values from foreign key field? django model.py
class Authors(models.Model):
  name = models.CharField(max_length=50)

class Books(models.Model):
  date_pub = models.DateField()
  name = models.CharField(max_length=50)
  author = models.ForeignKey('Authors')

I need to derive the names of authors from a foreign key, but the Books.objects.all().values_list('author', 'name') command infers the id from the Authors model. how to derive author names from the Books model

A: You can use:
Books.objects.all().values_list('author__name')

It is mentioned clearly in Django documentation: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#values-list


text:
Q: PhpStorm autocompletion / dialogs disappear in Awesome WM / Xmonad When trying to autocomplete code or open up the dropdown menu's the window / dialogs will appear for a short time and then get hidden behind the main editor window.
The problem is related to java window handling in tiling window managers such as AwesomeWM.
To solve this see the answer below.

A: You need to edit the VM options so window hinting can be done correctly.
I installed PHPStorm under /opt/phpstorm (linux)
Edit:
bin/phpstorm.vmoptions
bin/phpstorm64.vmoptions

Append the following line:
    -Dide.expansion.hints.enabled=false

Restart phpstorm and the problem should be fixed.
ref: http://code.google.com/p/xmonad/issues/detail?id=560


text:
Q: PHP random key verification I am making an AJAX request to a script called return.php that will look like this:
http://www.example.com/return.php?type=3&filter=2

This occurs when a browsing user hits a button on example.com
I want additional security measures so that this can only be requested by a user browsing my site. No direct type ins, etc.
So I was thinking to send some type of randomly generated key along with the request. What methodology would I use to verify at return.php that a correct key has been sent?
Can I generate a key and store it in a session variable that is then accessible in return.php?
pseudo code:
 if ($random_key_sent == what it should){
      //go ahead and execute code
    }
else{
     //sorry can't help
    }

And Ultimately my request would look something like:
http://www.example.com/return.php?type=3&filter=2&key=8fu5jtugy489kgvuri09984ufjlgi (or whatever the key would be)

Bottom line I am looking for a way to generate some type of added security so that return.php is only being used when it should be, along the similar lines of using API keys etc.

A: If you are worried about "direct type-ins" but still need to use GET requests, you can check the request headers in PHP to only allow Ajax requests using $_SERVER['HTTP_X_REQUESTED_WITH'].
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Do what you need to do
} else {
    die("Ajax Only");
}

(Modified from David Walsh)

A: You're looking for cross-site request forgery (CSRF or XSRF) protection.
Typically, you generate and save an anti-CSRF token in the user's session data, and put it in a hidden form field (using either GET or POST), or for normal links you place the token in a query parameter. On the server side, you check that the anti-CSRF token matches the one in the user's session data.
Some suggest that you can achieve the same level of security by simply checking the HTTP referer header. That can work, but is less reliable since people can block the referer for privacy reasons.

A: Unless you're going to have a list of preset keys that your PHP code checks against and the browser can receive to then send in the URL, it would be impractical to check the key for a specific value. You could just check if the $_GET["key"] array value is set:
if(isset($_GET["key"])){
    // go ahead and execute code
}else{
    // sorry can't help
}

Alternatively, you may want to consider requiring the browser to set some POST data which is sent along with the request to the webpage, but cannot be typed into the address bar. Then just use $_POST["key"} rather than $_GET["key"] to verify.


text:
Q: How can I reset my Button count to 0 in Xamarin forms? I have created a button to count the number of maximum clicked and How can I create another button to reset it to 0 after clicking?
Secondly I want all my buttons to be in Circle shape and Horizontally left and right.
This is the example of my page:
CountPage.xaml
<StackLayout Spacing="10">
                                    <Label Text="0" x:Name="labelCount"
                                           HorizontalOptions="Center"
                                           VerticalOptions="CenterAndExpand" />
                                    <Button Text="Count" Clicked="Increment"/>
                                </StackLayout>

CountPage.xaml.cs
int labelValue = 0;
        public CountPage()
        {
            InitializeComponent();
        }

        private void Increment(object sender, EventArgs e)
        {
            labelValue++;
            labelCount.Text = labelValue.ToString();
        }

A: For the circle buttons, I recommend reading this doc
Now let's go to the coding part
First, let's add another button
<StackLayout Spacing="10">
  <Label Text="0" x:Name="labelCount" ... />
  <Button Text="Count" Clicked="Increment"/>
  <Button Text="Reset counter" Clicked="Reset"/>
</StackLayout>

Now in the code behind you will have to add
private void Reset(object sender, EventArgs e)
{
   labelValue=0;
   labelCount.Text = labelValue.ToString(); //this will be 0
}

So it's just using the same variable and the name of the other button.


text:
Q: download pdf with knitr in shiny in R I try to create button for downloading with knitr package.
I have found some example which works a bit but I'm not able to change the name of the pdf. moreover it causes errors then.
enter image description here
second problem is that when I download the file , it is not a .pdf extension and I have to choose program to open it when I try to open. How can I download file as .pdf in default?
here are my codes (example from the internet):
server.R
library(knitr)

shinyServer(function(input, output) {
output$myreport = downloadHandler(

filename = "adads.pdf",

content = function(file) {
  out = knit2pdf('input.Rnw', clean = TRUE )
  file.rename(out, file) # move pdf to file for downloading
},

contentType = 'application/pdf'
 )
 })

ui.R
library(shiny)

shinyUI(basicPage(
 textInput('firstname', 'First name', value = 'Jimmy'),
 textInput('lastname', 'Last name', value = 'John'),
 downloadButton('myreport')
))

and  input.Rnw file
 \documentclass{article}

 \begin{document}

 <<names>>=
 input$firstname
 input$lastname
    @

 \end{document}


text:
Q: Ubuntu fail on boot after Windows 10 update (20H2) I'm using a dual-boot os (Windows 10 and Ubuntu), after I update the Windows to the latest update 20H2  the GRUB isn't showing on reboot else display these errors
Malformed security header
Failed to read header: Invalid Parameter
Failed to load images: Invalid Parameter
start_img() returned Invalid Parameter

then the Windows 10 start.
I found some similar problems HERE.
Has anyone encountered this issue before?

A: I had a similiar issue with my dual boot setup:

*

*W10 on one SSD

*ArchLinux on another SSD

*UEFI GRUB on Linux disk

*Mobo booting from the UEFI/Linux disk
although in my case the update failed (and for like the n-th time already, drives me crazy tbh...)

After the failed update GRUB went down. I would only get a black screen with GRUB letters on it.
My fix was all about recreating GRUB as you would do when installing Linux to get the dual-boot in the first place.

*

*boot the system from a live-USB instance

*mount all the partitions in correct mount-points (not sure if that step was necessary though, probably not...)

*reinstall GRUB with grub-install in the way applicable to your setup (UEFI vs BIOS)

*reconfigure GRUB with grub-mkconfig

grub-mkconfig succesfully located both Linux and Windows and generated correct entries.
After that I exited the live-USB system, rebooted and everything was back and working.


text:
Q: Почему после автозаполнения input регулярка выдает неверное значение? Что-то никак не могу понять, что не так.
Есть поле input куда вводится сумма. После того как ввели значение сумма у меня преобразовывается вот так
const newVal = value.Amount.toString().replace(/\s/, '').replace(/,/g, '.');

В дальнейшем как в работу вступает валидатор, который проверяет по регулярке, условие, регулярка вот такая:
/^(\d+\.|\d*[1-9])\d*$/.test(newVal)

При вводе "руками" скажем числа 111,00 значение преобразовывается в 111.00 и все ок, это больше нуля, регулярка отдает true. Но если ввести значение в поле через автокомплит, то тогда тест регулярки отдаст false и тогда валидатор сработает и скажет, что число 111,00 должно быть больше нуля. Что не так делаю?
Замечу, что мне в value.Amount приходит строка. Поэтому мне без разницы когда приводить значение к точке.


text:
Q: Can Apache Tika (or any JVM library) produce ordered extract data referencing images, as well as text, e.g. from a PDF? Basically, I want to be able to create a set of 'slides' based on extracts from documents such as PDFs or Word docs, programmatically.
For this, I need to know [roughly] where in the text any embed images were originally placed, as such, simply dumping the image resources out to disk wouldn't help*.
I'm a Java dev, so I don't fear the code ;-)
*unless of course there are references within the [Tika] extract output, at the appropriate position(s) or line(s).


text:
Q: How do I read a single letter from a file when the letter has a space on either side? (C) I'm currently working on an assignment in my Intro to C class. The assignment has us using fgets to read a single line from a file, then strcpy and strtok to take individual elements from that line and store them into different arrays. The file is a list of comic book character info, so we would store the character's first name into an array, last name in a different array, age into a different array, etc. Here is an example of one line from the file:
Romanoff , Natasha ; F Black Widow 1964 Marvel 52 Avengers 1975 green Human Auburn 170 59

I've had success storing the last and first names using strtok to stop at the punctuation separating the names. I'm running into a problem with the next bit, however, which is storing the character's sex (in this case, "F") into an array for gender. Since there is no punctuation or numbers between it and the next bit of info, I'm not sure how to proceed.
Initially, I tried reading the character from the file in the same way that I did the other items, using a space " " as the delimiter in strtok:
strcpy(gender[count], strtok(NULL, " "));

When I do this, I receive the following error:
warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]

I'm thinking that strtok is picking up on the space immediately following the ";" and stopping there before even getting to "F" and copying that to gender[count]. But I don't know how to skip over that space so that the "F" is successfully copied.


text:
Q: Is the output of the libjpeg always RGB (or luminance for monochrome images)? I use he libjpeg to manipulate jpeg images.
My question is simple :
Is the output of the libjpeg always RGB (or luminance for monochrome images) ?
I'm not an expert with the color spaces...
Thanks !

A: Strictly speaking, JPEG is always YCbCr (YUV), so that's the output. You may apply other colorspaces, but typically only RGB or (less commonly) CMYK are supported, and the underlying data in the file will remain YCbCr. Grayscale simply leaves the second two channels out and only encodes Y.


text:
Q: Max-turn hamiltonian path in square grids Given an $n \times n$ square grid graph, what is the maximum number of turns a Hamiltonian path can take?

A: Answer to OP's question (proof follows):
For Hamitlonian paths: if $n$ is even max turns=$n^2-n$
if $n$ is odd max turns equals $n^2-n-1$
The minimum number of turns on an Hamiltonian path on an $n \times n$ lattice is $2n-2$ which can be constructed at least two non-isomorphic ways (rows or spiral) for each graph. The maximum number of turns Hamiltonian path onin a $2 \times n$ lattice is also $2n-2$
To maximize the number of turns, if $n$ is even then you can consider the graph to be a collection of $n \times 2$ graphs each of which can have a maximum of $2n-2$ turns in them starting from an outside corner on each side the $-2$ factor comes from the fact that in order to turn the corner you must have one vertex that does not turn, for an outside $2 \times n$ you lose one going into the corner and one from the starting/ending vertex. For the interior $2 \times n$'s you must have one "straight vertex coming in and one coming out.
$2n-2 \times (n/2)$seperate rectangles gives a formula of $n^2-n$ for even $n$.
If $n$ is odd, it is not so simple to construct a path because the rows do not divide evenly by $2$. The cases for constrcution of a maximal turning path are different if $n$ is 1 or 3 mod $4$.
If $n=1$ mod $4$ you begin again at a corner in the first row you again have $2n-2$ turning vertices in the first $2\times n$ rectangle. You then continue down the side of the graph (a $2\times (n-2)$ rectangle) and collect  $2n-4-1$ more turning vertices. Repeat on the bottom of the graph. Continue towards the starting corner now you have a $2 \times (n-4)$ rectangle that yields $2n-8-1$ turning vertices. Continue on towards the center every two new directions you turn the rectangle get smaller and there are $4$ fewer vertices. When you reach the center (where the path ends) you gain only 1 turn for the final $3$ vertices.
Putting it all together there are $n-2$ turns in the first rectangle, $1$ turn for the center and the spiral which contains $n-7+4$ rectangles in sets of two beginning with $2n-5$ turns and adding $4$ less for every set. $2n-2+1+[(n-3)(\frac{2n+5-5}{2})]=n^2-n-1$
If $n=3$ mod $4$ then you can proceed as above but the actual center vertex of the graph is contained in the last rectangle before the end of the paththe last $3$ vertices and their $1$ turn remains the same but the path is off-centered in the graph. The formula for the vertices remains the same $2n-2$ for the first rectangle $n-5$ rectangles at an average of $n$ turns per spiral rectangle and one for the last turn of the path still sums to $n^2-n-1$ for all odd $n$.
Answer to question asked in comments.
For Hamiltonian Cycles
If $n$ is odd there is no hamiltonian cycle on a $n \times n$ grid. This can be proved from the contrapositive of theorem 3.16 on page 214 of "Graphs and Digraphs" by Chartrand. By numbering the vertices of an odd $n \times n$ grid from left to right top to bottom from $1,2,3...n^2$ Select the set of vertices $S$ as all the even numbered vertices. Then $|S|=\frac{n^2-1}{2}$ and there are $\frac{n^2+1}{2}$ disconnected components so the graph cannot be hamiltonian.
If $n$ is even you can construct a "spiral" cycle like the spirals for the odd paths given above. I haven't found a closed form expression yet that deals with the center of the cycle. $(\frac{3n^2}{4}+\frac{3n}{2}-12)+C$ where $C$ is the number of turns at the center of the graph is a good description of the maximum number of turns in a hamiltonian cycle on a $n \times n$ grid.


text:
Q: PhoneGap 1.9 Barcode Scanner iOS issue All,
Has anyone a working example of the Barcode scanner for iOS that works?  I have downloaded the plugins and deployed the example it to my iphone 4 with 5.01ver of OS.  it loads i hit the "Scan Something" button and nothing happens, no errors just nothing.  I know this version is with 1.5 of Cordova.  However i followed the example and instructions in the plugin in a 1.9 version and it is doing the same thing.  I have double checked the plist and it all matches the example's plist and the instructions. I did put a console.log in the barcodescanner.js file in the "scan" function and it never gets there or at least it never displays it in the output window.  any ideas?  I see someone else posted the exact same question for 1.8.1 but no one answered him...
thanks
tim

A: I just installed on a vanilla 1.9.0 with the directions exactly as they appear at https://github.com/phonegap/phonegap-plugins/tree/master/iOS/BarcodeScanner and it opens the scanner for me.
At the moment I can't get it to recognise that it has scanned a barcode though.
Is there something in your document/device ready function that is crashing before it registers the on click event for the scan button? Like hitting a url that isn't in your whitelist or something like that.
Further to that can you edit your code that calls the scan function?


text:
Q: Why am I getting an error here in my code?     def menu():
    print("[1], Enter this option to play against another human: ")
    print("[2], Enter this option to play against the computer: ")
    print("[0], Exit the program")

menu()
option = int(input("Enter your option: "))

def option1():
    global sPlayerName1
    sPlayerName1 = input("\nPlayer 1 enter your name:\n")
    print("Hello", sPlayerName1)
    global sPlayerName2
    sPlayerName2 = input("\nPlayer 2 enter your name:\n")
    print("Hello", sPlayerName2)

def option2():
    print("So you want to plat against the computer huh? Good luck!")

def numofgames():
    global iGames
    iGames = int(input("\nHow many games would you like to play? Best of 3 or best of 5?: \n\n"))

def playerchoice():
    global iPlayerChoice1
    iPlayerChoice1 = int(input(sPlayerName1, "\n,\nWhat do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors? \n\n"))
    global iPlayerChoice2
    iPlayerChoice2 = int(input(sPlayerName2, "\n,\nWhat do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors?"))

while True:
    if option == 1:
        option1()
        break
    elif option == 2:
        #option2()
        break
    elif option == 0:
        print("\n------------------------------------------------")
        print("\nGoodbye!")
        break
    else:
        print("Invalid Option.")

while True:
    numofgames()
    if iGames == 3:
        playerchoice()

playerchoice()

while True:
    print(sPlayerName1, " chooses: \n")
    if sPlayerName1 == 0:
        print(rock)
    elif sPlayerName1 == 1:
        print(paper)
    elif sPlayerName1 == 2:
        print(scissors)

# Player 2 conditional statement and outputs choice

    print(sPlayerName2, " chooses: \n")
    if sPlayerName2 == 0:
        print(rock)
    elif sPlayerName2 == 1:
        print(paper)
    elif sPlayerName2 == 2:
        print(scissors)

I am stumped on why this error is coming up, here is my code
this is the error i run into on line  63   iPlayerChoice1 = int(input(sPlayerName1, "\n,\nWhat do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors? \n\n"))
TypeError: input expected at most 1 argument, got 2enter code here
Do I have to create a seperate function for player two for it to be able to read the inputs?


text:
Q: how to hide list when user select item from list? could you please tell me how to hide list when user select item from list .Actually when user type anything on text field it show a list , when user select any row from the list it set value on text field .But that time I need to hide my list .So I take one boolean variable  $scope.islisthide=false; using that value I need to hide or show list .Please press "a" than select value from list .I already use ng-show but how to add condition in that .

{{station.stationName+"-("+station.stationCode+")"}}

$scope.rowclick = function(station) {
    $scope.SEARCH.stationCode=station.stationCode;
    //  $scope.$apply();
}

here is my code
http://codepen.io/anon/pen/zGYPWj

A: Just use a flag to indicate whether a selection has been made. Here's an example:
http://codepen.io/anon/pen/RPwjvN
I am using a flag called selected


text:
Q: Scala Play 2.0. Compilation error: IO error while decoding I downloaded multi-module Scala project from GitHub (https://github.com/henrikengstrom/roygbiv), and one of the module is Play 2.0 module. So I can run whole application using SBT's run command on each module, and all works fine. But when I add to Play 2.0 template (index.scala.html) non-English characters  and press F5 in browser I get compilation error:

IO error while decoding
  C:\Users...\web\target\scala-2.9.1\src_managed\main\views\html\index.template.scala
  with UTF-8 Please try specifying another one using the -encoding
  option

Play 2.0 module I run also using SBT's run command, not using Play console.
I checked source file encoding - it is UTF-8. Also tried UTF-8 without BOM.
Where can be problem?

A: You could try to startup SBT with forced encoding to UTF-8. I read in this post that for some people it helped to start SBT with the following option:
JAVA_TOOL_OPTIONS='-Dfile.encoding=UTF8'

Then one of the first lines of SBT should display:
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8

A: Your problem seems to be this: your intermediate scala files are not encoded correctly.
Here is the process:
Play takes your template file (foo.scala.html) and translates this into Scala: target/scala-2.10/src_managed/main/views/html/foo.template.scala. This then gets compiled by sbt to .class files and run by play.
When sbt creates these intermediate files, it creates them with the default encoding (in my case a Windows machine so UTF-8 without BOM - your machine may differ). Importantly, this encoding sticks around, so even if I change the encoding of the original template file (foo.scala.html to UTF-16), the encoding of the .scala file is still the same (UTF-8 without BOM in my case). However, the file no longer compiles because the file can't be read because the scala compiler is expecting ITF-8.
The 'correct' solution is to always use UTF-8, and in fact this was the solution recommended for play 1.x see Play documentation Internationalization. Here is the equivalent for play 2. You can also use normal internationalization messages files.
So, if you specify
JAVA_TOOL_OPTIONS='-Dfile.encoding=UTF8' sbt

as suggested by Bjorn, then this will tell sbt that all files that it reads and writes will be in UTF8. You can also specify the file encoding for the scala compiler in your Build.scala:
val main = play.Project(appName, appVersion, appDependencies).settings(
  scalacOptions ++= Seq("-encoding", "UTF-8")
  // Add your own project settings here
)

This tells the scala compiler that all files that it reads (i.e. the foo.template.scala) are encoded in UTF-8. If you set this to your default encoding, this may work as well.
Your best bet is to do an sbt clean, ensuring that the offending files have disappeared, and restarting with the JAVA_TOOL_OPTION as suggested above. However, you'll have to ensure that all of your builds take this into account (jenkins, other developers etc).

A: The following works fine for me. Encoded in utf-8 default by eclipse(scala-ide)
@(message: String)

@main("Welcome to Play 2.1") {

Ελληνικά

        @message

     @for(p<-message) {

     @p

      }

}

A: What editor are you using to save these files? There might be a possibility that your characters are double encoded and thus stored incorrectly as UTF-8. Eg. characters encoded in iso-8859-1 are encoded again as UTF-8.

A: I was having this problem and figured out that it was being caused by some characters of my native language I had in the comments (ã). I removed those and the error disappeared.


text:
Q: VMware Workstation guest, can't get above 1176x885 I have an Ubuntu 9.04 (I know, it's old) guest installed on VMware Workstation 12, with the latest VMware Tools and everything. The VM has 3840 MB of RAM and 64 GiB of SCSI HDD.
My problem is that the guest autofit feature only allows a resolution up to 1176x885 (if I resize the window manually, it automatically gets back to that, and if it's maximized it stays at that resolution). Even if the height is smaller, the maximum width is still 1176, and vice-versa. The VMware docs says that this happens on vSphere and other products, and that it means that there isn't enough video RAM, but the settings show that "up to 768 MB will be used", and it shows that for every other Ubuntu VM I have and they all work perfectly. The video/display settings for the VM are the default untouched ones. How can I make that VM work correctly?

A: As even reinstalling Ubuntu didn't change anything, I thought something was wrong with the VM itself. So I kept my fresh (VMware Tools installed) new Ubuntu 9.04 VMDK, and created another VM with the same specs (RAM, CPU, HDD) and BAM! it worked. So I opened both in WinMerge and compared them, and apart from the standard useless lines, I noticed one that I never heard about:
svga.guestBackedPrimaryAware = "TRUE"

It was present in the old (non-working VM) and not in the new one. Effectively, after removing it from the old VM everything worked correctly. I typed it on Google and found some topics on here about Grub that didn't want to use max resolution and stuff like that, topics that I didn't even see in the results before.

A: I had the same problem on Ubuntu 20.10. The issue was that while switching kernel packages in order to remove linux-firmware (who needs firmware on a VM?) I had also uninstalled linux-modules-extra-5.8.0-50-generic. The solution was
sudo apt install "linux-modules-extra-$(uname -r)"

and a reboot.


text:
Q: Concatenate Data in Nested JSON file to CSV I get a JSON file with Server info in it and I'm trying to concatenate the output into one output.
Here is the output I get:

Server Name
Operating System
Service
IPs

DC01
Windows Server 2016
Domain Controller
10.2.0.4

WEB01
Windows Server 2016
Web Server
10.3.0.100

WEB01
Windows Server 2016
Web Server
10.3.0.101

Here is the output I need:

Server Name
Operating System
Service
IPs

DC01
Windows Server 2016
Domain Controller
10.2.0.4

WEB01
Windows Server 2016
Web Server
10.3.0.100, 10.3.0.101

Here is my JSON File:
[
  {
      "Server Name": "DC01",
      "Operating System": "Windows Server 2016",
      "Service": "Domain Controller",
      "IPs": [
     {
        "IP": "10.2.0.4"
     }
   ]
 },
 {
      "Server Name": "WEB01",
      "Operating System": "Windows Server 2016",
      "Service": "Web Server",
       "IPs": [
       {
          "IP": "10.3.0.100"
       },
       {
          "IP": "10.3.0.101"
       }
    ]
  }
]

Here is the PowerShell:
$JsonFile = "C:\Tmp\Servers-JSON.json"
$OutputJson = "C:\Tmp\Servers-CSV.csv"
$Servers = @()
((Get-Content -Path $JsonFile) | ConvertFrom-Json) | ForEach-Object {
$sname = $_."Server Name"
$os = $_."Operating System"
$Service = $_.Service
    $Servers += $_.IPs | ForEach-Object {
        [pscustomobject] @{
        "Server Name" = $sname
        "Operating System" = $os
        "Service" = $Service
        "IP" = $_.IP -join ','
            }
        }
}
$Servers | Export-Csv $OutputJson -NoTypeInformation

A: A simplified example:
@'
[
  {
      "Server Name": "DC01",
      "Operating System": "Windows Server 2016",
      "Service": "Domain Controller",
      "IPs": [
     {
        "IP": "10.2.0.4"
     }
   ]
 },
 {
      "Server Name": "WEB01",
      "Operating System": "Windows Server 2016",
      "Service": "Web Server",
       "IPs": [
       {
          "IP": "10.3.0.100"
       },
       {
          "IP": "10.3.0.101"
       }
    ]
  }
]
'@ | ConvertFrom-Json |
  ForEach-Object {
    $_.IPs = $_.IPs.IP -join ', '
    $_ # Output the modified object.
  } |
      ConvertTo-Csv  # Replace this with your Export-Csv call

The above yields:
"Server Name","Operating System","Service","IPs"
"DC01","Windows Server 2016","Domain Controller","10.2.0.4"
"WEB01","Windows Server 2016","Web Server","10.3.0.100, 10.3.0.101"

*

*Since you're not changing the names and number of properties, you can directly modify each input object that ConvertFrom-Json parses your JSON into.

*$_.IPs.Ip uses member-access enumeration to extract all IP addresses contained in the array of objects stored in $_.IPs, which are then joined with ', ' to form a single string and assigned back to the .IPs property.


text:
Q: How to install clang (11) without xcode? My brother gave me ssh access to his macbook (uname -a says 19.6.0). I'd like to compile a few simple c files with clang (specifically clang and not gcc). I grabbed the clang 11 mac binary from the official site and move all the folders into /usr/local/. which clang gives me /usr/local/bin/clang. If I do clang main.c it just hangs. Even clang --version hangs
How do I properly install this? There's no xcode or developers tools on it

A: Homebrew walks you through this command line install.

*

*https://brew.sh/
Basically, call xcode-select --install and have your brother click OK one time to approve the installation.


text:
Q: How to raise a matrix to a vector of powers in matlab without for loop? I have a 2x2 matrix that I want to multiply by itself 10 times while storing the result after each multiplication. This can easily be done with a for loop but I would like to vectorize it an eliminate the for loop. My approach was to have my 2x2 matrix a and raise it to a vector b with elements 1:10. The answer should be a 2x2x10 matrix that replicates typing
a^b(1)
a^b(2)
.
.
.
a^b(10)

To clarify I'm not doing this element wise I need actual matrix multiplication, and prefer not to use a for loop. Thanks for any help you can give me.

A: here is the code for you. I use the cellfun to do this and I have comments after each line of the code. It can compute and store from fisrt - nth order of the self-multiplication of an arbitrary matrix m. If you have any question, feel free to ask.
function m_powerCell = power_store(m, n) %m is your input matrix, n is the highest power you want to reach

  n_mat = [1:n]; %set a vector for indexing each power result in cell

  n_cell = mat2cell(n_mat,1,ones(1,n)); %set a cell for each of the power

  m_powerCell = cellfun(@(x)power(m, x), n_cell, 'uni', 0);  %compute the power of the matrix

end

%this code will return a cell to you, each element is a matrix, you can
%read each of the matrix by m_powerCell{x}, x represents the xth order


text:
Q: AttributeError: 'BoxesView' object has no attribute 'object_list' Trying to add a form to my homepage view and getting this error when I submit the form. Here's my code:
views.py
class BoxesView(ListView, FormMixin):
    template_name = 'polls.html'
    form_class = UserRegistrationForm

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = User.objects.create_user(username=username, password=password)
            user.save()
            return redirect('/')
        return self.form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super(BoxesView, self).get_context_data()

        context['form'] = self.get_form()
        question_list = Question.objects.all().order_by('-date')
        choice = Choice.objects.all()
        context['question_list'] = question_list
        context['choice'] = choice

        q_list = []
        returned_list = []

        for i in question_list:
            q_list.append(i)

        for a, b in CATEGORY_CHOICES:
            name = resolve(self.request.path_info).url_name
            if b == name:
                category = a

        search = self.request.GET.get('search')
        posts = Post.objects.all().filter(category=category).order_by('-date')
        if search:
            posts = posts.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )
        else:
            posts = Post.objects.all().filter(category=category).order_by('-date')

        context['posts'] = posts

        total = 0
        for post in posts:
            returned_list.append(post)
            total += 1
            if total == 4:
                total = 0
                for i in q_list:
                    returned_list.append(i)
                    q_list.remove(i)
                    break

        search = self.request.GET.get('search')
        posts = Post.objects.all().filter(category=category).order_by('-date')
        if search:
            posts = posts.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )
        else:
            posts = Post.objects.all().filter(category=category).order_by('-date')

        context['posts'] = posts

        return context

    def get_queryset(self):
        pass

forms.py
class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [
            'username',
            'password',
        ]

base.html
<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
    <div class="registerBox">
        {{ form.username }}
        {{ form.password }}
        <input type="submit" value="register"/>
    </div>
</form>

My traceback is pointing me to these lines: return self.form_invalid(form) & context = super(BoxesView, self).get_context_data(). Hopefully this can give you an indication of what the problem is but i've been unable to work it out.Any idea?

A: I manage a solution, if you don't have the user_list variable in your class you have to put it in, but it's better overriding the constructor, but tou neetd to put the model variable in your class.
class BoxesView(ListView, FormMixin):
    template_name = 'polls.html'
    form_class = UserRegistrationForm
    model = YourModel

    def __init__(self, *args, **kwargs):
        super(BoxesView, self).__init__(*args, **kwargs)
        self.object_list = self.get_queryset()

It's usefull :P

A: If you are using ListView, either you should specify a model attribute with
class BoxesView(ListView, FormMixin):
    template_name = 'polls.html'
    model = yourModel

or you should specify queryset in get_queryset method.
def get_queryset(self):
    qs = yourModel.objects.all()
    return qs

Note that queryset is accessed in templates by the default name object_list.
Also rather than creating objects using forms in ListView, try only to list objects in ListView. Use CreateView to create objects. Your ListView may look like the below.
class BoxesView(ListView):
    template_name = 'polls.html'
    model = yourModel
    paginate_by = 20

Refer to this link for more details
Also from your question it seems like you are trying to iterate over Post objects which are passed to template as context data. Note that Overriding def get_context_data(self) is to provide extra context variables, not queryset and ListView always expect model or get_queryset(self) to be defined in your class inherited from ListView. If what you are trying to do is to create a ListView for Post objects, try setting model=Post in your class.


text:
Q: Does LaTeX have to reprocess included files that haven't changed? I have included several .tex files (they do not contain the header code like documentclass, begin and end document, etc). When I include the file using \include everything works. But if I recompile the code I still takes a while even though most of the includes(or even all) have not changed.
My basic method to deal with this is to comment out the includes I do not want compiled but I see no reason why they can't be "precompiled" and reused each time unless the .tex file changed.

A: There is no existing way to do this. The only way is using \include and \includeonly (or \excludeonly) and simply skip certain chapters.
However, it would be possible to produce PDFs from \include files and include these using \includepdf if the files didn't changed. I already wrote code like this for other applications: standalone can compile it's own document in the background to get access to the resulting PDF, see Shell escape after PDF is finished and closed? and especially Can one TeX file output to multiple PDF files? (both by Ulrike Fischer). File changes could be checked using my filemod package: Can (La)TeX compare the time stamps of two external files?.
So a new package could redefine \include to produce PDFs only if the .tex file changed. Handling changes in sub-files and images are more difficult. Then the document is assembled using pdfpages. However, a major drawback is that all PDF annotations like hyperlinks will be gone, because pdftex doesn't support them in included PDF files. Therefore this should only be used as a form of draft mode.

An alternative but similar approach would be to have a script or Makefile which checks for file changes and compiles the document for every chapter by using:
pdflatex -jobname "chapt1" "\includeonly{chapter1}\input{main}"

Then you can view the PDFs directly. It is also possible to have a main PDF which bookmarks point to other PDFs (holding the chapters), so you can browse through the whole document. This also allows hyperlinks etc. in the chapter PDFs.

A: I don't think that this approach can lead to result that are applicable to a wide range of documents.
You're starting from a false assumption, in my opinion: the fact that a .tex file isn't changed doesn't mean that its typeset version will stay the same, for a number of reasons.

*

*Cross-references in it may not resolve correctly when other files are changed.

*A call of \today might produce a different date.

*A change in a previous .tex file may produce different chapter or section numbering.

*A change in a previous .tex file may produce different page numbers.

*Most importantly, a change in the definition of a command in the root file might modify drastically the output even if no numbering has changed.
Would your process take care of all this? Documents where such constraints are not relevant are better managed as separate complete TeX documents to be merged with an external utility such as pdftk. Of course one can write a Lua script that wraps compilation of such documents and does the merge.

A: TeX works in a linear fashion with an input file, and while there are methods to split up in input (ultimately based on the \input primitive), these are for the author's convenience only. TeX still processes all of the input in a linear manner: once a file is \input it is as though the material was all in one big file.
At the same time, it is possible for changes in one part of a document to affect another (for example, altering the set up of the running headers or page numbering). So it is not possible to simply say 'I can skip this input'. Writing the output is also a linear process: there is no direct link between individual .tex files and parts of the .dvi or .pdf in a way that would allow TeX to take 'old' pages and 'recycle' them.
The LaTeX \include mechanism does have features to help with larger documents. Using \includeonly it is possible to compile only part of a document, while retaining cross-references and so on. This however works by entirely skipping the files which are not included, so you do not get the complete version of your document.
There are also methods to precompile the preamble of a document into a custom format, and then only retypeset the document body. See for example mylatexformat.

A: Here is the way I do this:
I have a master document which inputs my preamble and includes all my chapters as TEX files.
While I am in draft mode, I comment the chapters that I do not want to compile. I commented also the table-of-contents as well as the table of figure.


text:
Q: Simple object creation with DIY-DI? I recently ran across this great article by Chad Parry entitled "DIY-DI" or "Do-It-Yourself Dependency Injection".  I'm in a position where I'm not yet ready to use a IoC framework, but I want to head in that direction.  It seems like DIY-DI is a good first step.
However, after reading the article, I'm still a little confused about object creation.  Here's a simple example:

Using manual constructor dependency injection (not DIY-DI), this is how one must construct a Hotel object:
PowerGrid powerGrid;           // only one in the entire application
WaterSupply waterSupply;   // only one in the entire application

Staff staff;
Rooms rooms;
Hotel hotel(staff, rooms, powerGrid, waterSupply);

Creating all of these dependency objects makes it difficult to construct the Hotel object in isolation, which means that writing unit tests for Hotel will be difficult.
Does using DIY-DI make it easier?
What advantage does DIY-DI provide over manual constructor dependency injection?

A: There's no difference between what you call DIY-DI and manual constructor injection.
If it's too difficult creating a Hotel instance you can do two things:

*

*Make sure that the dependencies are expressed as either interfaces or abstract base classes. This lets you test the Hotel class in isolation by providing Test Doubles such as dynamic mocks or similar instead of concrete classes.

*If there are too many dependencies, then refactor to aggregate services.

As an application grows in complexity, so does the task of managing the lifetimes of all dependencies. While it's technically possible to manually compose an entire application, this is exactly the point where a DI Container can be extremely helpful.

A: Hint for

Creating all of these dependency objects makes it difficult to construct the Hotel object in isolation

As I can see, there should be no dependencies from blue objects to red objects. Objects with different lifetimes should not depend on each other. See also: http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/


text:
Q: Particular targets of high angular resolution infrared telescopes I work in the field of infrared interferometry, specifically instrumentation.
As such, I need to be aware of the science goals of such an instrument. Is there a quick list of important and contemporary targets that such an instrument of high angular resolution would be pointed at?
(By "high", I mean objects that subtend a small angle on the sky.)

A: Searching Google Scolar for "Particular Targets of High Angular Resolution Infrared Telescopes"
gives good citations.

A: The most obvious targets are protostar disks (T Tauri, Serpens FIRS 1), the Milky Way's central black hole Sgr A*, and nearby large stars (Betelgeuse).
The MPIfR interferometry group web page has an impressive sample


text:
Q: Postpone an sql transaction I would like to trigger an SQL transaction (database query) after a specific time (e.g. 5 days) from an event (e.g. a user clicked a button) in my website running on php server.

A: You need a cronjob that checks for pending tasks on a table where you store the event setting a datetime that states when it has to be executed.