text:
Q: Sort list of numbers using the zsh shell in Mac OS X Using Mac OS X zsh shell, how can I ascending sort the following list of numbers? I have tried the command line sort (without any options) but the output is not accurate.
The below list of numbers is the output from the following command line: dscl . -list /Users UniqueID | awk '{ print $2 }'
Side Note: Pay attention to a couple of numbers from the list such as -2, 0, etc.
83
263
273
55
260
87
79
33
67
235
245
97
229
93
258
32
82
262
202
236
280
259
212
72
77
257
275
59
220
271
244
241
214
227
215
270
71
254
265
98
278
247
56
261
240
25
274
96
84
218
219
279
234
232
231
233
230
246
217
239
211
205
272
26
78
248
54
65
253
74
268
222
228
24
242
243
441
249
27
216
76
269
277
60
203
31
92
200
89
75
73
13
94
266
210
91
282
208
99
95
213
4
224
221
88
70
252
251
1
501
-2
0

A: From the manual page for the sort command:
 -n, --numeric-sort, --sort=numeric
         Sort fields numerically by arithmetic value.  Fields are supposed
         to have optional blanks in the beginning, an optional minus sign,
         zero or more digits (including decimal point and possible thou-
         sand separators).

    Note: For a descending order sort, add the -r option, e.g. : | sort -nr
Adding | sort -n to your command, and using the output in your question, will output e.g.:
-2
0
1
4
13
24
25
26
27
31
32
33
54
55
56
59
60
65
67
70
71
72
73
74
75
76
77
78
79
82
83
84
87
88
89
91
92
93
94
95
96
97
98
99
200
202
203
205
208
210
211
212
213
214
215
216
217
218
219
220
221
222
224
227
228
229
230
231
232
233
234
235
236
239
240
241
242
243
244
245
246
247
248
249
251
252
253
254
257
258
259
260
261
262
263
265
266
268
269
270
271
272
273
274
275
277
278
279
280
282
441
501

If you are new to using shell commands or the command line, many of them have helpful manuals (and some manuals are also spectacularly unhelpful) or built in help.
man sort
sort --help


text:
Q: Github workflow not getting the requirements.txt file while building docker image I have a github workflow that is building the docker image, installing dependencies using requirements.txt and pushing to AWS ECR. When I am checking it locally all is working fine but when github workflow is running it is not able to access the requirements.txt file and shows the following error
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

Below is my simple dockerfile
FROM amazon/aws-lambda-python:3.9
COPY . ${LAMBDA_TASK_ROOT}
RUN pip3 install scipy
RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"
CMD [ "api.handler" ]

Here is cicd yaml file.
name: Deploy to ECR

on:
  push:
    branches: [ metrics_handling ]

jobs:
  build:

    name: Build Image
    runs-on: ubuntu-latest

    steps:
    - name: Check Out Code
      uses: actions/checkout@v2

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: ${{ secrets.REGION }}

    - name: Build, Tag, and Push image to Amazon ECR
      id: tag
      run: |
        aws ecr get-login-password --region ${region}  | docker login --username AWS --password-stdin ${accountid}.dkr.ecr.${region}.amazonaws.com

        docker rmi --force ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:latest

        docker build --tag ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:latest -f API/Dockerfile . --no-cache

        docker push ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:latest

      env:
        accountid: ${{ secrets.ACCOUNTID}}
        region: ${{ secrets.REGION }}
        ecr_repository: ${{ secrets.ECR_REPOSITORY }}

Below is the structure of my directory. The requirements.txt file is inside API directory with all the related code that is needed to build and run the image.

A: Based upon the questions' comments, the Python requirements.txt file is located in the API directory. This command is is specifying the Dockerfile using a path in the API directory, but building the container in the current directory.
docker build --tag ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:latest -f API/Dockerfile . --no-cache

The correct approach is to build the container in the API directory:
docker build --tag ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:latest API --no-cache

Notice the change from . to API and removing the Dockerfile location -f API/Dockerfile

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenJFX : bundled version conflict with dependencies I have a project that uses Liberica JDK 13 which includes OpenJFX out-of-the-box, no external dependencies required. The most important feature to me is that Liberica provides x86 builds too.
However, I have to compile one of the project sub-modules with Java 11, because it contains some custom FX components I want to use in Scene Builder and Scene Builder unfortunately only supports Java 11 compiled classes and below.
Here is module-info:
module foo {

    requires java.logging;
    requires java.desktop;

    requires static javafx.controls;
    requires static javafx.fxml;

    exports foo;
}

And compiler settings:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <release>11</release>
    </configuration>
</plugin>

The first problem I don't understand is that if I use Java 11 compilation level then Maven complains that javafx modules not found:
[ERROR] module not found: javafx.controls
[ERROR] module not found: javafx.fxml

Well, why it doesn't complain about any other required modules, but only javafx.*? How's that possible? There is no such difference between JDK modules or...
As a workaround, I've tried to include OpenJFX as a Maven dependency:
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>11</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>11</version>
    <scope>provided</scope>
</dependency>

There're no compilation errors, but now Intellij complains:
Package `foo` reads package `javafx.scene.chart` from both `javafx.controls` and `javafx.controls`

because it reads javafx.controls from both JDK and Maven dependency.
Is any way to avoid this situation? I know that probably the simplest solution is to maintain problem module as a separate project, but this is exactly what I'm trying to avoid.


text:
Q: NullPointerException when trying to read from a text file I'm trying to read these names from a text file, but getting an error. Here's the relevant part of my main method, and the method in question:
public class Prog4
{
int mostVoteCount = 0;
int mostVotes = 0;
int mostVotesIndex = 0;
int fewestVoteCount = 0;
int fewestVotes = 0;
int fewestVotesIndex = 0;

String[] candidateArray;
int[] votesArray;

public static void main(String args[]) throws Exception
{
  //Scanner stdin = new Scanner(System.in);
  Scanner stdin = new Scanner(new File("test.txt"));
  int num_votes, num_candidates, election_num = 1;

  System.out.println("Welcome to Prog4!\n");
  Prog4 p4 = new Prog4();

  while (stdin.hasNextLine())
  {
     System.out.println("Results for election " + election_num);
     p4.read_candidates(stdin, p4.candidateArray);
     p4.read_votes(stdin, p4.votesArray);
     System.out.println("Total votes: " + p4.votesArray.length);

  }

 System.out.println("Done. Normal termination of Prog4.");
}

and the method in question:
public void read_candidates(Scanner stdin, String candidates[])
{
   int candidateCount = 0;
   candidateCount = (stdin.nextInt());

   for (int i = 0; i < candidateCount; i++)
      candidates[i] = (stdin.next());
}

Here's my test data used in the "test" text file:
4
Owen
Jack
Scott
Robbie
15 0 1 1 2 3 1 0 0 0 0 1 2 2 1 1
Is this the stack trace?
java.lang.NullPointerException

at Prog4.read_candidates(Prog4.java:75)

at Prog4.main(Prog4.java:35)

A: You're never instantiating your candidateArray and votesArray, so they are null when you pass them to the read_candidates method. I'm guessing it is failing on the line:
candidates[i] = (stdin.next());

You're basically attempting to do something with a null object (the candidates object in this case). At some point in your code you'll have to do something like candidateArray= new String[], and same thing for the votesArray, before you attempt to use them.

A: You need to initialize your array "candidates" before you do the assignment
public void read_candidates(Scanner stdin, String candidates[]) {

        int candidateCount = 0;
        candidateCount = (stdin.nextInt());
        candidates = new String[candidateCount]; // here initialize your array
        for (int i = 0; i < candidateCount && stdin.hasNext(); i++){
            String data = stdin.next();
            System.out.print(data  + " ");
            candidates[i] = data;
        }
    }

A: it can be an outfobound exaception so please be careful with the line candidateCount = (stdin.nextInt());
you may get exception here so calculate length correctly candidateCount = candidates.length;

A: Check the location of test.txt. Based the trace, your Scanner object being passed to read_candidates is null. Be sure that you can read the file from the specified location.


text:
Q: Suddenly getting exception "Word has encountered a problem" This code has worked for about a year. Now I'm suddenly getting the exception "Word has encountered a problem". I have verified I can manually open the Word file (fileName). When I inspect the Word Application object I see that the AnswerWizard property shows a COMException. The appropriate Word project reference seems to be fine.
var appWord = new Microsoft.Office.Interop.Word.Application();
var doc = new Document();
doc = appWord.Documents.Add(Template: fileName);
```

AnswerWizard exception:

=>'((Microsoft.Office.Interop.Word.ApplicationClass)appWord).AnswerWizard' threw an exception of type 'System.Runtime.InteropServices.COMException'

From the Event log, System:

The server-side authentication level policy does not allow the user SERA\EPBASVR$ SID (S-1-5-21-3869734172-4259265755-3048270987-18749) from address 192.168.40.204 to activate DCOM server. Please raise the activation authentication level at least to RPC_C_AUTHN_LEVEL_PKT_INTEGRITY in client application

Update: I have no idea why but this started working fine again after about two weeks on it's own. Maybe a MS update to Word?


text:
Q: SSH Permission denied (publickey) I have 2 EC2 instances (ip-172-30-0-196 and ip-172-30-0-194). But I can't do ssh from 194 to 196, and vice-versa. The ssh error from 194 is here.
Both hosts have the ssh files with the same permissions [2]. Why I can't do ssh between instances?
[2]
ubuntu@ip-172-30-0-196:~/Programs$ ls -altr ~/.ssh/
total 24
-rw-r--r-- 1 ubuntu ubuntu  404 Feb  2 17:41 id_rsa.pub
-rw------- 1 ubuntu ubuntu 1675 Feb  2 17:41 id_rsa
-rw-r--r-- 1 ubuntu ubuntu  444 Feb  2 18:22 known_hosts
-rw------- 1 ubuntu ubuntu  406 Feb  2 18:26 authorized_keys

A: There are a number of possible issues, including

*

*A firewall running on one or both boxes (iptables -vnL should list the
firewall rules, look to see if port 22 is allowed)

*Some kind of additional limiting is occurring - for example SELinux or
Apparmor.   (if cat /selinux/enabled = 1, you are running selinux, try
temporarily disabling it).   I've seen this on quite a few CentOS 6
installs.

*It could be a configuration option in /etc/ssh/sshd_config - for
example an "AllowUsers" directive may limit who can log in.
(BTW, your permissions look OK).


text:
Q: Requests.history Not printing python3 I'm a noob to python programming. I have a simple problem. Im using python3, in pyCharm 2017.2.1, I want to print out all request redirects. From what I have googled I seem to be doing it right. I get no errors and a response 200. What am I missing?
import requests
url='http://httpbin.org/html'
payload= {'url':'http://bing.com'}

req = requests.get(url, params=payload)
#print(req.text)
print("Response code: " + str(req.status_code))

if req.history:
    print ("Request was redirected")
    for resp in req.history:
        print (resp.status_code, resp.url)
        print ( "Final destination:")
        print(resp.status_code, resp.url)
    else:
        print("Request was not redirected")

for x in req.history:
    print(str(x.status_code) + ' : ' + x.url)

output:
Response code: 200

Process finished with exit code 0

A: I think you should use this url: http://httpbin.org/redirect-to,
the url you're using will not redirect your request. Also the else block is not executed because it applies to the for loop.
import requests

url='http://httpbin.org/redirect-to'
payload= {'url':'http://bing.com'}
req = requests.get(url, params=payload)

print("Response code: " + str(req.status_code))
if req.history:
    print ("Request was redirected")
    for resp in req.history:
        print("Final destination:")
        print(resp.status_code, resp.url)
else:
    print("Request was not redirected")

for x in req.history:
    print(str(x.status_code) + ' : ' + x.url)

Note that you can disable redirects if you set the allow_redirects parameter to False


text:
Q: Error on AWS deploy I'm working on a project that I haven't touched in about 4 months. Before everything on the deploy was working fine, but now I'm getting an error when trying to deploy an update eb deploy my-env-name.

Failed to pull Docker image amazon/aws-eb-python:3.4.2-onbuild-3.5.1:
  Pulling repository amazon/aws-eb-python time="2016-01-17T01:40:45Z"
  level="fatal" msg="Could not reach any registry endpoint" . Check
  snapshot logs for details. Hook
  /opt/elasticbeanstalk/hooks/appdeploy/pre/03build.sh failed. For more
  detail, check /var/log/eb-activity.log using console or EB CLI.

In the eb-activity log, it further states:

[CMD-AppDeploy/AppDeployStage0/AppDeployPreHook/03build.sh] : Activity
  execution failed, because: Pulling repository amazon/aws-eb-python

..before repeating what was shown in the UI.
The original was using a Preconfigured Docker 64bit Debian jessie v1.3.1 running Python 3.4. I've tried upgrading to the latest, which is version 2.0.6, but it never completes (don't need to get into specifics of that error, separate issue and I'd like to stay on 1.3.1 if possible). I've also tried upgrading to the latest 1.x but it has the same result of upgrading to 2.0.6.
Any ideas, or anything else I should be looking for clues?
EDIT: Here is the contents of my Dockerfile, which gets generated automatically
FROM amazon/aws-eb-python:3.4.2-onbuild-3.5.1
EXPOSE 8080

A: Your Dockerfile points out that you are using an image coming from the Docker Hub.
Your Elastic Beanstalk instance is running Preconfigured Docker 64bit Debian jessie v1.3.1 which is less than 1.6.
Unfortunately, the Docker Hub has deprecated versions earlier than 1.6 since 7 december 2015 : https://blog.docker.com/2015/10/docker-hub-deprecation-1-5/.
You should upgrade your EB/Docker instance to 1.6 minimum.


text:
Q: NodeJS Variable outside function scope For the life of me I cannot work this one out. Have look around and tried many many different ways of trying to get this to go. Currently have the following code.
var config = require("./config.js");
var cradle = require('cradle')
var MikroNode = require('mikronode');
var WebServer = require('./bin/www');
var Routers = "Hasnt changed";

var conndb = new(cradle.Connection)(config.couchdb.host);
var db = conndb.database(config.couchdb.db);

db.exists(function(err, exists){
  if (err) { console.log('error', err);}
  else if (exists) { console.log('Seems the Force is with you - Database Exists');}
  else { db.create(); }
});

db.temporaryView({
  map: function (doc){
    if (doc.type=='ConfigRouter') emit(doc.name, doc);
    }
    }, function (err, res){
        Routers = JSON.stringify(res);
    }
);

console.log(Routers);

As it stands it will respond with:
E:\Dev\MM>npm start

> MM@0.0.1 start E:\Dev\MM
> node ./Start.js

Hasnt changed
Seems the Force is with you - Database Exists

I am assuming it is an asynchronous call to the CouchDB and is not filling the result in time before it displays the result. How do I get around this issue?

A: You are right, the call is asynchronous so when console.log(Routers); is processed, Routers is "Hasnt changed".
One way of doing it would be to use promises thanks to the Q npm module:
var Q = require('q');

var deferred = Q.defer();
db.temporaryView({
  map: function (doc) {
    if (doc.type=='ConfigRouter') emit(doc.name, doc);
  }
}, function (err, res) {
  deferred.resolve(JSON.stringify(res));
});

deferred.promise
  .then(function (data) {
    Routers = data;
    console.log(Routers);
    // do some stuff...
  })
  .done();

Maybe it's possible to do something better without using Q.defer and adapting directly the callback:
https://github.com/kriskowal/q#adapting-node


text:
Q: Firebase App named '[DEFAULT]' already exists (app/duplicate-app) Hi I am trying to unit test while developing a simple web with AngularJS + Firebase, but I have a problem defining the spec and trying the test runner
myProject/test/spec/main.js :
describe('Controller: MainCtrl', function() {

var MainCtrl, scope

beforeEach(module('MainApp'));

beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
        $scope: scope
    })
}));

it('should....',function(){
    expect(true).toBe(true)
})
it('should2....',function(){
    expect(false).toBe(false)
})
});

result:
PhantomJS 2.1.1 (Mac OS X 0.0.0) Controller: MainCtrl should.... FAILED
Error: [$injector:modulerr] Failed to instantiate module MainApp due
to: Firebase: Firebase App named '[DEFAULT]' already exists
(app/duplicateapp).

However, defining the spec once is not a problem. For example:
it('should....',function(){
   expect(true).toBe(true)
})

I do not know why this is the reason I give a hint to me
Here is the project I am developing.
https://github.com/parkwookyun/firebase-angular-board

A: i only glanced at your github repo to see that there is more .js files than suggested in your question.
i had 2 separate .js files. both being included on the same html page that were both configuring and initializing the default app when it only needed to be done once for that page i believe. what worked for me was to comment out the second "initializeApp()" and i no longer got that error. try to look for the below in your .js and comment out or delete one of the initializations.

var config = {
      apiKey: "my api key",
      authDomain: "something.firebaseapp.com",
      databaseURL: "https://somesite.firebaseio.com",
      projectId: "myProjectId",
      storageBucket: "somesite.appspot.com",
      messagingSenderId: "someIntegers"
    };
//firebase.initializeApp(config);

A: This error occurs simply because you are trying to initialize firebase multiple times into your project.

A: if (!firebase.apps.length) {
   firebase.initializeApp({});
}else {
   firebase.app(); // if already initialized, use that one
}

Similar answer here

A: I had the same issue using firebase, and I realized that I was initializing the firebase twice, example:
function initializeFirebase(){
 var config = {
    apiKey: "myApiKey",
    authDomain: "myAuthDomain",
    databaseURL: "myDatabaseUrl",
    storageBucket: "myStorageBocket",
    messagingSenderId: "idhere"
   };
   //initialize firebase
   firebase.initializeApp(config);
}

In my case I was using react, And I was calling initializeFirebase() from two different components, but I've decided to call it from the parent component. And now I'm able to query my database, insert records, remove, etc.
Hope this helps someone

A: In my case, I was not explicitly calling initializeApp() more than once, so I was still confused after reading the main answers. Turns out that if you use Firebase hosting, then initialization is called automatically through SDK auto-configuration, i.e. when you have this line in index.html:<script src="/__/firebase/init.js"></script> you don't need to call initializeApp(config).
"When you deploy to Firebase or test your app locally, this script automatically configures the Firebase JavaScript SDK for the active Firebase project and initializes the SDK." SDK auto-configuration

A: I recently solved this issue in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
Scan through your code to make sure you only call initializeApp() once. This includes any js files that might be calling the method or duplicating the js file in your html file.

A: I have had the same problem
if you are using ES6 modules and you installed firebase by npm you can not put init  scrips into index.html
it is duplications of firebase dependancies

A: Check if project is in admin.apps. If it is, use if not initialize it. This will prevent the error from occurring.
const projectFbData = admin.apps.find((item) => item.name_ === projectId) || admin.initializeApp(config, projectId)


text:
Q: What's the use of the oauth_token_secret in Twitter OAuth? I followed the tutorial on https://dev.twitter.com/docs/auth/implementing-sign-twitter to use OAuth on my homepage. Everything worked and after the last step I have an oauth_token (after converting it to an access token) and an oauth_token_secret. Now I want to post a new status on twitter. So I did everything on this page https://dev.twitter.com/docs/auth/authorizing-request which is just a post request to /1/statuses/update.json. On that page nothing is said about the oauth_token_secret, so I haven't used it in my request and just have put the oauth_token in it. After submitting the post request twitter gives me the status code 401 Unauthorized. Why that? Do I have to use the oauth_token_secret somewhere?

A: The token secret is used to hash the signature base. Something like a password. You don't send the password, you use it to compute a secure hash of the thing the service sent to you.  You send that secure hash, then the service checks that secure hash against the request you sent. If they match, you're authorized.
The gory details are described in the OAuth spec, RFC 5849.
Twitter uses OAuth1.0a, but is mostly consistent with that spec.
here's the relevant bit:
https://www.rfc-editor.org/rfc/rfc5849#section-3.4.2


text:
Q: Java string only contains numbers, spaces, and the symbols +-() I have a Java string and it's only allowed to contain the numbers 0 to 9, spaces, and the symbols + - ( )
How do I test this?

A: This code checks if your string matches the regular expression pattern of any amount digits, +-() and spaces:
Pattern p = Pattern.compile("([0-9+-]*\\)*\\(*\\s*)+");
Matcher m = p.matcher(yourString);
boolean b = m.matches();
System.out.println(b);

The + indicates that you have at least one of these allowed symbols. If you want to allow empty strings as well, just change the + to a *.

A: try this regular expression:
[0-9.-\s+/()]+
With This sample Program


text:
Q: Sorting columns having lists with reference to each other in pandas Suppose my data frame is like:
   A             B           Date
[1,3,2]    ['a','b','c']     date1

I want to sort both the columns but with reference to each other. Like the output should be:
   A             B           Date
[1,2,3]    ['a','c','b']     date1

Now if these had been two lists only I would have sorted through zip method.
But as these are columns of data frame. I am not sure how to use apply method to sort these with reference to each other.
My dataframe as a whole is sorted on the basis of third column (date). Now for each such dates the other two columns have list, each having same number of values. I want to sort those lists on the basis of each other

A: If all cells have the same number of values, try this flattening and groupby approach:
df
           A          B
0  [1, 3, 2]  [a, b, c]
1  [4, 6, 5]  [d, f, e]  # added an extra row for demonstration

(df.apply(pd.Series.explode)
   .groupby(level=0)
   .apply(lambda x: x.sort_values('A'))
   .groupby(level=0)
   .agg(list))

           A          B
0  [1, 2, 3]  [a, c, b]
1  [4, 5, 6]  [d, e, f]

Obligatory disclaimer: Please don't use pandas to store lists in columns.

A: Similar to cs95's solution, but with sort_values and sort_index:
# sample data
df = pd.DataFrame({
    'A':[[1,3,2],[2,1]],
    'B':[['a','b','c'],['c','d']],
    'Date':['date1','date2']
})

df[['A','B']] = (df[['A','B']].apply(pd.Series.explode)
    .sort_values('A',kind='mergesort')
    .sort_index(kind='merge_sort')
    .groupby(level=0).agg(list)
)

Output:
           A          B   Date
0  [1, 2, 3]  [a, c, b]  date1
1     [1, 2]     [d, c]  date2


text:
Q: Can any finite distributive weighted lattice be realized by inclusion of groups? By theorem 2.1 here, any finite distributive lattice  $\mathcal{L}$ can be realized as an intermediate subgroups lattice.
A weighted lattice $(\mathcal{L},\tau)$ is a lattice $\mathcal{L}$ with a weight $\tau: \mathcal{L} \to  \mathbb{N}$ satisfying;
- $b \le b' \Rightarrow \frac{\tau(b')}{\tau(b)}\in \mathbb{N}$
- $\tau(l) = 1$ for $l$ the least element of $\mathcal{L}$.
Let $(H \subset G)$ be an inclusion of finite groups, then it realizes $(\mathcal{L}(H \subset G),\tau)$, with $\tau(K) = [K:H]$ and $\mathcal{L}(H \subset G)$ the lattice of intermediate subgroups $H \subseteq K \subseteq G $.
Question: Can any  finite distributive weighted lattice be realized by inclusion of groups?
Remark: It's obviously true for the lattice with two elements and any weight thanks to the inclusion $(S_{n-1} \subset S_{n})$.
I don't know if it's true for the lattice with three elements, weighted $(mn,n,1)$ or even just $(n^{2},n,1)$, but I have checked by GAP that it's true for $mn < 32$.

A: Let me hastily summarise my comments above: a subgroup inclusion chain of length 3 corresponds precisely to an imprimitive permutation group on a set of size $mn$ with a unique system of imprimitivity (and we require that the blocks in this system have size $m$).  The corresponding lattice will then be $(mn,n,1)$.
Such a group is given by $Sym(m) \wr Sym(n)$, although for particular $m$ and $n$ there are no doubt many others. This answers the specific question given by the OP.
As for generalizations: one naturally wonders how to deal with $(\ell mn, mn, n, 1)$. I think for this you can use $(Sym(\ell) \wr Sym(m)) \wr Sym(n)$, with similar iterations working for longer chains. Indeed one can probably generalize this construction even more so that given any intermediate subgroup lattice, you can stick a chain "on the top of it" by taking wreath products. This at least reduces the general question somewhat.


text:
Q: Getting a Reference to a GoogleMap in a fragment using Support Library v4 I'm trying to add Google Maps to a fragment using the v4 support lib, but I have some trouble using getMap() to reference it.
I'm adding the fragment like so (following the example at http://developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime) :
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (findViewById(R.id.fragment_container) != null) {

            if (savedInstanceState != null) {
                return;
            }

            MapFragmentClass mapFragmentClass= new MapFragmentClass ();
            mapFragmentClass.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, mapFragmentClass).commit();
        }
    }
}

And in the mapFragmentClass I'm trying to get the reference like this:
public class MapFragmentClass extends Fragment {

    public static  GoogleMap mMap;
    private static SupportMapFragment mapFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
        mMap = mapFragment.getMap();

        return inflater.inflate(R.layout.mapfragment, container, false);

}

or like this
@Override
public void  onResume(){
    super.onResume();
    mMap = mapFragment.getMap();

    Log.i("TestMap", "setCamera");
}

Both options come back with a null.. So basically I don't have a reference to the map when the Fragment is active. I even also tried getting a reference 10 seconds after the map was loaded, but alas..
Why won't it return a GoogleMap? The var mapFragment is always filled, from the moment I instantiate it in onCreateView, so if that's filled, I should be able to get a GoogleMap type back right then & there, correct?
I've tried loading in a GoogleMap a normal Activity, using a Fragement in the layout, and there, in onCreate, I can instantiate and reference it, no problem. The map seems to load in faster as well.
If anybody has any idea how to get this working, I'd be much obliged.
Edit: My mapfragment layout:
<?xml version="1.0" encoding="utf-8"?>

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"
          tools:layout="@layout/main"/>

A: In your FragmentTransaction in MainActivity you should add an instance of SupportMapFragment instead of MapFragmentClass.
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (findViewById(R.id.fragment_container) != null) {

            SupportMapFragment mapFragmentClass= new SupportMapFragment ();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, mapFragmentClass).commit();
            getSupportFragmentManager().executePendingTransactions();
            GoogleMap map = mapFragmentClass.getMap();
            // do what you need to do with the map
        }
    }
}

The way you were creating SupportMapFragment was just creating a new Fragment instance but since you didn't add it using a FragmentTransaction none of the lifecycle methods of the Fragment were being called.


text:
Q: C# Adding a List to a class I have a class that looks something like this:
public class Parent
{
    private string sFirst_name1;
    public string sParent1FirstName
    {
        get { return sFirst_name1; }
        set { sFirst_name1 = value; }
    }

    private string sLast_name1;
    public string sParent1LastName
    {
        get { return sLast_name1; }
        set { sLast_name1 = value; }
    }

    private List<int> lChild_ID;
    public List<int> lChildID
    {
        get { return lChild_ID; }
        set { lChild_ID = value; }
    }
public Parent(string sP1FN, string sP1LN, List<int> lCID)
    {
        lChild_ID= new List<int>();
        sFirst_name1 = sP1FN;
        sLast_name1 = sP1LN;
        lChild_ID = lCID;

    }

I create an instance of the class and add it to a List of type Parent with the line:
lParents.Add(new Parent(sParent1FNTemp, sParent1LNTemp,lParentChildIDTemp));

Where lParentChildIDTemp is just a null integer List.
Later on, I am trying to update the int list of the object at a specified index by saying:
lParents[iIndex].lChildID.Add(++iIDCounters);

And I get a null reference exception. I'm not too sure why, but I think it has something to do with my constructor for my class. The weird thing is, I have another class that does pretty much the same thing but it doesn't throw the exception. If anyone has any clues, I would be greatful.

A: Drop the List of int argument in the ctor and why not use auto props:
public class Parent
{
    public Parent(string sP1FN, string sP1LN)
    {
        LChildID = new List<int>();
        sFirst_name1 = sP1FN;
        sLast_name1 = sP1LN;
    }

    public List<int> LChildID { get; set; }

If you're not familiar with auto-implemented properties, see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
Plus, you could also overload the ctor:
    public Parent(string sP1FN, string sP1LN, List<int> lCID)
    {
        LChildID = lCID;
        sFirst_name1 = sP1FN;
        sLast_name1 = sP1LN;
    }

A: Give your property is null, you should make sure you are not access null values to call methods or properties. If you do that, you will get an NullReferenceException. Try this:
var childIds = lParents[iIndex].lChildID;
if (childIds != null)
{
    childIds.Add(++iIDCounters);
}

In your constructor, you could check the if the argument is null and define a default list int. If you for to set the argument, even if it is null, you will get null.
public Parent(string sP1FN, string sP1LN, List<int> lCID)
{
    sFirst_name1 = sP1FN;
    sLast_name1 = sP1LN;
    if (lCID == null)
    {
       lChild_ID = new List<int>();
    }
    else
    {
       lChild_ID = lCID;
    }
}

A: Since apparently you want to be able to pass in the lChildID during construction, change the constructor as so:
public Parent(string sP1FN, string sP1LN, List<int> lCID) {
    sFirst_name1 = sP1FN;
    sLast_name1 = sP1LN;
    lChild_ID = lCID ?? new List<int>();
}


text:
Q: Is the monogame content processors required for it to work on different platforms? Can I just use the xna content processor and import all the xnb files, or do I need to use the monogame content project thing and use their processors?

A: You most certainly can use the XNA content processor. That's what most people have been doing while waiting for the MonoGame team to implement their own content processors.
Alternately, you can use raw assets in place of the XNB files. Simply add them to the Content folder of your project and set them to Content / Copy if newer in the properties window. You also need to refer the the file with it's extension in code, e.g.
Content.Load<Texture2D>("MyTexture.png");

When doing this, I've also found you get better results if you set the blend state to BlendState.NonPremultiplied since the XNB files do this for you.
_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, null, null, null, null, viewMatrix * Matrix.CreateScale(screenScale));


text:
Q: Is stringA in StringB in MATLAB Is there a way to check if a string exists within another string in MATLAB. In python this is done easily with a in b. I do not want indexes or anything like that. I just want to check if its true or not. The answers that I find is "strcmp" or "strfind" and also regexp. regexp returns indexes. strcmp(a, b) does not seem to work. I have a string a = 'ac' and another string b = 'bc_gh_ac'. And want to check if a in b.
Best regards

A: The answer is indeed strfind.  You have to be careful with the order of the parameters which at first seems unusual - the pattern is the second argument, not the first.  The following code demonstrates:
a='ac';
b='bc_gh_ac';
strfind(b,a)

If you simply want to test whether the string is present or not then use the isempty function:
if ~isempty(strfind(b,a))
    disp('String is present');
end


text:
Q: How to deal with this kind of import cycle? I am quite new to Go and I fell on an import cycle that I'm not sure how I should solve. I have multiple class that implements a specific interface. I also have another class that will return the interface corresponding to the specific class id. Problem arrives when any specific class needs to use my other class. Here's an exemple:
package examplepkg

import otherpkg

type ExampleClass {}

func NewExampleClass() *ExampleClass {
    return &ExampleClass{}
}

func (ex *ExampleClass) ExampleMethod() { // Implements ExampleInterface
    var id int // Read from some external source
    theinterface := otherpkg.GetExampleInterface(id)
    theinterface.ExampleMethod()
}

And the function in another package:
package otherpkg

import examplepkg

func GetExampleInterface(id int) *ExampleInterface {
    switch id {
        case 3000: return examplepkg.NewExampleClass()
    }
}

If you need a bit of context, I'm reading some data from a source that I didn't create, which encapsulate some kind of data types using the ids. Example will be: id somedata id2 somedata2. And using the specific id, I can call the method to get the good type of data and the good size. They can be nested, that's why I'm using the same method ExampleMethod().
Can anyone help me to understand this problem clearly in Go?

A: You are creating a package  examplepkg which imports otherpkg, when the compiler reads this file, it will first try to solve the imports before actually running the code inside examplepkg.
Problem is your package otherpkg is importing examplepkg and like I said previously, it will first try to solve the imports. So, the compiler will go back to examplepkg and try to solve the import, but it will lead it again to otherpkg.
This results in the import cycle you are facing. One solution to this problem is to create a new package where you declare your type ExampleClass and declare func NewExampleClass. Then have examplepkg and otherpkg to import from this newly created package, breaking the import cycle you are facing right now.

A: Two ways to go about it:

*

*Create a new package which contains functions common to both, then import that package in both packages.

*Consider whether all these belong to the same package instead of two different packages.


text:
Q: Converting list of strings with decimal places to ints in python example_list = ['21.48678', '21.46552', '21.45145', '21.43822',
                '21.42734', '21.41222', '21.40132', '21.37679']

Im having a bit of trouble converting this list from strings to integers,  I would like to also have it as whole numbers.  Thanks :)

A: Simplest thing is
[int(float(x)) for x in your_list]

This will truncate all the numbers
If you want to round the numbers use this instead
[int(float(x)+.5) for x in your_list]

A: At first convert to float
>>> lst = ['21.48678', '21.46552', '21.45145', '21.43822', '21.42734', '21.41222', '21.40132', '21.37679']
>>> ints = [int(float(num)) for num in lst]
[21, 21, 21, 21, 21, 21, 21, 21]

A: foo = ['21.48678', '21.46552', '21.45145', '21.43822', '21.42734', '21.41222', '21.40132', '21.37679']

map(lambda x: int(float(x)), foo)

A: [int(round(float(i))) for i in example_list]

will convert items in the list to float, round them and then convert them to int.

A: new_list=[]
for each in example_list:
    Integer = int(each)
    new_list.append(Integer)
print new_list

This is easy for beginner to understand:D


text:
Q: calculate 'predicted class' raster in QGIS I have six raster layers that represent the probability of each pixel belonging to a specific vegetation type. I would like to use these to generate a new raster where the value of each pixel is the ID of the raster with the maximum value for the pixel, i.e. the most probable vegetation type of that pixel.
e.g. if at a given pixel raster1 = 0.5, raster2 = 0.2, raster3 = 0.1, raster4 =0.1, raster5=0.05 and raster6 = 0.05, then I would like that pixel in the new raster to be 1.
I can't work out how to do this either with the QGIS Raster Calculator (v2.18) or using an ifelse function with the SAGA Raster Calculator, but I am a bit of GIS newbie still.
In case it's relevant, Creating Maximum-Value Composite using QGIS? explains how to build a composite raster from maximum values but doesn't help me work out to extract the identity of the raster containing the maximum value.

A: Check out the SAGA Layer of extreme value tool
 (QGIS Processing Toolbox | SAGA | Raster analysis).


text:
Q: Interfacing of 8V hall effect sensor with microcontroller to measure RPM I am using a hall effect sensor for measuring the RPM of the engine. The output of this sensor needs to be fed into the ECU (for engine control) and Microcontroller (I am controlling a linear motor based on engine's RPM). The ECU is providing the hall effect sensor 8V supply, therefore the output of sensor will be either 0V (LOW) or ~8V (HIGH) but for my microcontroller digital input, I need 0-5V (I will measure the frequency of digital input using my microcontroller to get sense of RPM).
So basically I need to covert 0-~8V to 0-5V, what's the best method of doing this?

A: As the purpose of reading the signal at the microcontroller is to obtain the pulse rate, and not actual detailed waveforms, all that is needed is for the signal at the GPIO to be near zero for 0 Volt input, and reasonably higher than the GPIO's "High" threshold for ~8 Volt input.
The schematic below will provide a 0 to ~4.7 Volt signal that can be used for the GPIO. Feel free to use other combinations of R1 and R2 to tweak the desired voltage. The zener protects the GPIO against spikes from the ECU, if any.

simulate this circuit – Schematic created using CircuitLab

A: The simplest method you can use is with a single Schottky diode in a configuration like below:

simulate this circuit – Schematic created using CircuitLab
The mcu can have a wide supply range, the configuration will work with either 3.3v or 5v etc.
If the mcu doesn't have an internal pull-up you can use an external resistor pulling the input to Vcc.

*

*When the output of the hall sensor is 8v then the diode doesn't conduct (reverse biased) and the mcu input state is set by the pullup resistor to high (Vcc level).

*When the output of the hall sensor is 0v then the diode conducts and pulls the mcu input low to about 0.3v which represents low logic state.


text:
Q: get insights data of facebook page I want to get insights data of a facebook page. I have tried with graph api with this url:
https://graph.facebook.com/149279625121774/insights/?access_token=XXXX

but it gives empty data:
{    "data": [
          ],    "paging": {
      "previous": "https://graph.facebook.com/149279625121774/insights/...",
      "next": "https://graph.facebook.com/149279625121774/insights/..."
     }
}

'149279625121774' is the page id.
Is anybody help me for this.

A: UPDATED ANSWER:
Insights can be retrieved only as an array. To read Insights you need

*

*a generic access_token for the publicly available application_active_users metric

*a generic app access_token for all Insights for that app

*read_insights permissions for all apps, pages and domains owned by this user

For more details on which insights are available please review the FQL Insights table

Here are my comments:

*

*Most likely you don't have the read_insights permission.

*The user authenticated should be the owner/admin of the page!

*Remove the trailing slash /

A: I found the solution.
You must change the order of the scope parameter:
Try
email,read_insights,manage_pages

Instead of
email,manage_pages,read_insights


text:
Q: JBoss - implementing a application specific valve How can we configure a Valve for a particular web application in jboss AS 6?
Thanks,
Sivakumar.

A: I am not sure if there is an easy way to create valves in an application specific way. For most purposes you can use a servlet filter that can easily go into a .war archive.

A: Valves are usually configured in the Tomcat server.xml or context.xml file.
You can configure a context.xml specifically for your web application by creating a META-INF/context.xml file inside your WAR. Note that for it to work, you must not have a <Context> element for your application in the global Tomcat context.xml.
Then in your META-INF/context.xml just configure your specific Valve(s) for your application:
<Context path="/mycontext">
    <Valve className="com.example.MyValve" />
</Context>

Useful reference: http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context and http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Request_Filters


text:
Q: jQuery: How would I get a div to expand to a height and add text? I've got a homepage with a container-div below the nav that I'm attempting to expand to a set height and add specific text inside of the container-div.
On top of that I'm only wanting it to do this when I'm navigating from the home page only.
Any jQuery magic that would help me do this?
Thanks!
Here is the before at the home page

Here is the after at a different page that was clicked on on the home and loaded.

A: Have you tried something like:
window.onbeforeunload = function() {
    $('.container').css('height', '50px').text('Bye bye!');
}

You might also want to try nesting another element inside the container to prevent you manually specifying the container height. You could then minimize your JavaScript/CSS down to:
$('.container .child').show();

.child {
   height: 20px;
}

A: How about this?
$('#container-div').animate({
    height: '100px' // your target fixed height.
}, 'fast').html('specific text');

Where your container div has the ID container-div. If you don't want a transition, you can use .css().
$('#container-div').css('height', '100px').html('specific text');

A: This can be achieved with CSS3:
    Create a CSS3 animation:
/* Create predefined animation using keyframes */
@keyframes appear { 0% { height: 0px; } 100% { height: 100%; } }
@-o-keyframes appear { 0% { height: 0px; } 100% { height: 100%; } }
@-moz-keyframes appear { 0% { height: 0px; } 100% { height: 100%; } }
@-webkit-keyframes appear { 0% { height: 0px; } 100% { height: 100%; } }

/* will effect in children with less then 150px to slide to this height */
div { min-height: 150px; }
/* Div is larger then 150px? It will just animate to its required height */
div:hover > div {
  -webkit-animation: drop 1s 1 linear;
  -moz-animation: drop 1s 1 linear;
  -o-animation: drop 1s 1 linear;
  animation: drop 1s 1 linear;
  overflow-y: hidden;
}

Example working


text:
Q: How to conclude a vector is space-like? I'm working with the Lorenztian inner product and would like to show that if a vector $v$ is lightlike, so $\langle v,v\rangle =0,$ and if $\langle v,w\rangle =0,$ then either $w$ is spacelike or $w$ is proportional to $v.$
So far I have that since $\langle v,v\rangle =0,$ then
$$v_0^2 = v_1^2 +v_2^2 +v_3^3$$
and
since $\langle v,w\rangle =0,$ then
$$v_0w_0 = v_1w_1 + v_2w_2 + v_3w_3.$$
I think I can then conclude that since
\begin{align*}
v_0v_0 &= v_1v_1 +v_2v_2 +v_3v_3, \\
v_0w_0 &= v_1w_1 + v_2w_2 + v_3w_3
\end{align*}
then $v_0=w_0,v_1=w_1, v_2=w_2, v_3=w_3.$
Does this mean that $v$ and $w$ are proportional? I'm not sure how to conclude that $w^a$ could be also be spacelike from the supposition.

A: Hint: you can suppose that $v_2=v_3=0$ (by choosing an appropriate frame). Show then that $−w_0^2+w_1^2=0$, and conclude that $w$ is spacelike or lightlike.


text:
Q: website translation with .htaccess and friendly url I have a website called website.com/example/index.php with a directory called example inside root (root / example / index.php ). So far i have:
Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/example/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /example/$1.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

Now I want to add translation to my website in spanish. In index.php I call the english version via a href="?lang=en_US" and spanish via a href="?lang=es_ES" so in my browser url I get http://website.com/example/?lang=es_ES when switching to Spanish. My question is how do I make the url show: website.com/es/example/index or any page without having the physical directories en or es.

A: Change your first RewriteRule to:
RewriteRule ^(en|es)/(.+?)/?$ /example/$2.php?lang=$1 [L,QSA]

This is assuming all your URLs have en or es in them and that all your scripts in /example/ can accept the GET-variable lang. The $1 refers to the language and QSA means query string append so that if a user accesses /example/somepage?somevar=1, somevar still gets passed to $2.
Note that your second RewriteCond doesn't make sense since $1 is not defined yet.


text:
Q: Using shell command sending mail in Perl is not working I'm trying to send an email using Perl script, by using shell command. It is not giving any error and not sending email.
    #! /usr/bin/perl
        my $mail_command="echo hello | mail -s hi -r 'x@zz.com' 'y@zz.com'";
            print($mail_command);
            qx($mail_command);

When I print the message it shows like this.
    echo hello | mail -s hi -r 'x.com' 'y.com'

Can someone help me?

A: The issue is variable interpolation; however you still need quotes around your email addresses. Try the following:
#! /usr/bin/perl

my $mail_command=q(echo hello | mail -s hi -r 'x@zz.com' 'y@zz.com');
print($mail_command);
qx($mail_command);

q() acts like single quotes.

A: Please don't send mail using command-line programs like that. There are many good mail modules on CPAN. Please take a look at Email::Sender or Email::Stuffer.


text:
Q: How do you handle function parameters in svelte? I am trying to get the html5 spec for geolocation to work in svelte. I can't figure out how to get the showPosition function parameter to kick in.
Thanks in advance!
<script>

function getLocation() {
    console.log('This code runs when the button is clicked');
  if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
  }
}

function showPosition(position) {
    console.log('this code never runs');

    const lng = position.coords.longitude;
  const lat = position.coords.latitude;

  console.log(`longitude: ${ lng } | latitude: ${ lat }`);
}
</script>

<button on:click="{getLocation}">Try It</button>

A: You've got nothing Svelte specific in your JS, if it works out of Svelte, it should work here.
My guess is that the success callback that you're passing is not called because you're not getting success, but an error. For example, if you're denied access to your position the first time the browser asked for your domain (localhost:something presumably), then future requests are silently denied. And you get and error.
You should have a error callback too:
const onSuccess = console.log.bind(console, 'success')

const onError = console.error.bind(console, 'error')

const options = {
  // ...
}

navigator.geolocation.getCurrentPosition(onSuccess, onError, options)

See API docs (mdn) for details & available options.
With this code, in Svelte or not, you should see something happening in your browser's console.


text:
Q: Generating a Random Salt and use it in Bcrypt I am trying to generate a random salt to be used in hashing a password.
I am a bit new to password hashing, but form what I understand, when using BCrypt algorithm, you will get as a result a 60 characters long hashed string.
22 characters Out of these 60 characters should the salt value, which is prepended to the resulting hash.
I used a simple code to make sure that the randomly generated salt is the same one that is going to be prepended to the actual hash:
$salt = substr(strtr(base64_encode(openssl_random_pseudo_bytes(22)), '+', '.'), 0, 22);
echo "Salt Value is: ".$salt . "\n";

The output was: Salt Value is: XKFB8DHMiXaYTzRAHtRhX7
Then I encrypted a password using the same generated salt as follows:
$cost = 8;
$EncryptedPassword = password_hash($Password, PASSWORD_BCRYPT, ['cost' => $cost,'salt' => $salt]);
echo "Encrypted Password: " . $EncryptedPassword . "\n";

The output was not what I expected:
Encrypted format: $2y$10$XKFB8DHMiXaYTzRAHtRhXutlLLG8XIZjj5XGeyoUZobEtnkOn/M/S
Where the resulting salt is not exactly the one I used for hashing, i.e. that last character of the salt value is always different.
The randomly generated salt is: XKFB8DHMiXaYTzRAHtRhX7
The resulting salt value is: XKFB8DHMiXaYTzRAHtRhXu
My question is what could be the problem, and how could I get the same randomly generated salt value embedded in the password hashed string without getting it changed?

A: It is simpler and more secure to just use password_hash() and the companion password_verify() for PHP.
Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier.
No salt needs to be supplied and is best not to supply one, in PHP 7.x the salt option has been removed.
Example: password_hash("aPassword", PASSWORD_BCRYPT)


text:
Q: access the element of multidimensional array given the subscript array Given a multidimensional array A = MxMxMx...xM, where ndims(A)=n and the subscript array b=[a1, a2, ..., an]. How to get A(a1, a2, a3, ..., an)? I've tried A(b). It's not a correct way. And a correct way is to write a function to convert the subscript array to the index, saying i, and then we can use A(i) to get what I want. Is there an easier way?
Thanks

A: I think that, the easiest way would be through linear indexing, using, e.g. sub2ind function.
BasCell = num2cell(b);
i = sub2ind(size(A), BasCell{:});
A(i); % access ith element in A, using linear indexing


text:
Q: PHP redirect refresh I have a system where the user logs in and is immediately directed to a PHP page that runs some queries which it inputs into session variables. After the PHP has finished executing, it redirects the user to the main page. I would like to know how I can set it up, so that when the user refreshes the main page, it redirects them to the preceding page where the calculations can run again before the main page is displayed. I simply cannot have the two pages merged together. Does anyone know how I can accomplish this?
EDIT: PHP include is the closest to what I need, but the problem is that when I use AJAX to submit a form, the session variables in the first file update with new data from the database. Those variables need to stay static until an actual page refresh by the user. Does anyone know how I can include the form but make it invisible to Jquery?

A: You could store a value to the $_SESSION and every other load, forward to the other page.
// Start session
session_start();

// If the session variable is set...
if (isset($_SESSION['loadCount']) {

    // Increase the count
    $_SESSION['loadCount']++;

    // If it is even...
    if ($_SESSION['loadCount'] % 2) {

        // Reidrect
        header('Location: /calculate-again.php');
        die();

    }

} else {

    $_SESSION['loadCount'] = 1;
}

A: In the login form, make it submit to page_with_awesome_calculations_and_queries_to_session_variables.php. Assuming no input is sent in that page, make your calculations queries and sessions there, and then send a Location header to the new page.
header('Location: 'index.php');

This will cause the address bar in the browser to actually change to index.php, and a refresh will make the user stick there.
You should also secure your page_with_awesome_calculations_and_queries_to_session_variables.php to not allow access unless the correct $_POST variables are set.

A: Have mainpage.php receive one url parameter t which is the epoch timestamp.
Whenever calculation.php redirects to mainpage.php it will pass the epoch timestamp. If mainpage.php finds the epoch timestamp is older than five seconds, it will redirect back to calculation.php and exit.
mainpage.php
if (time() - $_GET['t'] > 5)
{
  header('Location: calculation.php');
  die();
}
else
{
  // proceed normally
}

calculation.php
// perform calculation
header('Location: calculation.php?t=' . time());

A: Add
<?
require 'calculations.php';

// Mainpage goes here
?>

to the top of the mainPage. This makes it an extension of the mainPage which is run before the main page is loaded.


text:
Q: Changing the math font in a presentation I am currently using the Metropolis theme (https://github.com/matze/mtheme) to make a presentation. Since I didn't have the custom font used by this theme, I have changed to a different sans serif, from the theme's preferences.
I would like to use the default serif font used by latex in math mode for either a small part of the presentation (let's say within a paragraph) or better for all the equations which I am going to put. I have tried different solutions - see similar questions - but it seems to be working only for the greek letters which I have used in my equations. The normal letters still have the non-default sans serif font which I have used in the presentation.
Is there any way possible to achieve this result?


text:
Q: How to iterate through JSON list in Python? This is my json data:

{
  "AccountRegion": "testaccount",
  "AssumeRole": "arn",
  "Policies": [
    "hello",
    "world"
  ],
  "Region": "usa"
},
{
  "AccountRegion": "testaccount-2",
  "AssumeRole": "arn",
  "Policies": "anotherpolicy",
  "Region": "usa"
}

I am not able figure out how to loop through the JSON. I would like to loop through the data and get policies for each member in the dataset. How can I accomplish this?

A: Try this.
arr = [{
      "AccountRegion": "testaccount",
      "AssumeRole": "arn",
      "Policies": [
        "hello",
        "world"
      ],
      "Region": "usa"
    },
    {
      "AccountRegion": "testaccount-2",
      "AssumeRole": "arn",
      "Policies": "anotherpolicy",
      "Region": "usa"
    }]

for x in range(0,len(arr)):
  print arr[x]['AccountRegion']

A: You can try this
import json
parsedJson = json.loads(data)
for i in parsedJson:
    print parsedJson["Policies"]


text:
Q: Por que no puedo insertar mas de 253 registros en mysql Hola amigos estoy intentando insertar varias registros al mismo tiempo pero al generar este script solo me permite insertar un máximo de 253, en donde envío por medio de POST la cantidad de 500, que puedo estar haciendo mal?
if(isset($_POST["id_ncf"]))
{
    $ncf_d="1";
    $ncf_h="500";

    for($i=$ncf_d;$i<$ncf_h;$i++) {
        mysql_query( "INSERT INTO ncf_inst (id_ncf,ncf_desde,ncf_hasta) VALUES ('$id','$i','$ncf_h')", $link) or die(mysql_error());
        mysql_select_db($database);
    }
    header("Location: prueba.php");
}

A: Hermanos muchas gracias , mi código esta bien, el error existía en la configuración de apache, por si le sirve a alguien , modifique el max_execution_time= 180, y listo lo inserto a la perfección,


text:
Q: if statment not working properly in android hello guys im newbie in android i want just to change the text view text if the caculate value between 18 or 25  i used if statment but there is no results
any idea sometimes if i removed one of the >its worked but only for biggest value
public class GB extends ActionBarActivity {
  ImageView im1;
  EditText mEditText1,mEditText2;
  TextView mTextView,m5;
  Button mButton;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_GB);
    im1 = (ImageView)findViewById(R.id.imageView1);
    mEditText1 = (EditText)findViewById(R.id.editText1);
    mEditText2 = (EditText)findViewById(R.id.editText2);
    mTextView = (TextView)findViewById(R.id.textView4);
    m5 = (TextView)findViewById(R.id.textView5);
    mButton = (Button)findViewById(R.id.button1);
    mButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        switch (v.getId()){
          case R.id.button1:
        }
        String word2 = mEditText2.getText().toString();
        String word = mEditText1.getText().toString();
        if (word.trim().equals("")){
          mEditText1.setError("Insert Hight");
        }
        else if (word2.trim().equals("")){
          mEditText2.setError("Insert Wight");
        } else{
          calculate();
        }
      }
    });
  }

  public void calculate(){
    Double value1 = Double.parseDouble(mEditText1.getText().toString());
    Double value2 = Double.parseDouble(mEditText2.getText().toString());
    Double calculatedValue = value1/(value2*value2)*10000;
    calculatedValue = Math.round(calculatedValue*10)/10.0d;
    mTextView.setText(calculatedValue.toString());
    if (mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18) {
      im1.setBackgroundResource(R.drawable.s1);
      m5.setText("low");
    } else if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25) {
      im1.setBackgroundResource(R.drawable.s3);
      m5.setText("Best");
    } else if (mTextView.getText().toString().trim().length() <25 && mTextView.getText().toString().trim().length() >100) {
      im1.setBackgroundResource(R.drawable.s3);
      m5.setText("over");
    }
  }
}

A: An integer value cannot be smaller than 18 and bigger than 25 at the same time.
Instead of
if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25)

Use this one if you want to check a value between 18 and 25.
if (mTextView.getText().toString().trim().length() > 18 && mTextView.getText().toString().trim().length() < 25)

A: If you want to check if a value is in an interval, you have to write it as follows:
if(myvalue > lowerbound && myvalue < upperbound )

The following code probably does what you want.
  public void calculate(){
    Double value1 = Double.parseDouble(mEditText1.getText().toString());
    Double value2 = Double.parseDouble(mEditText2.getText().toString());
    Double calculatedValue = value1/(value2*value2)*10000;
    calculatedValue = Math.round(calculatedValue*10)/10.0d;
    mTextView.setText(calculatedValue.toString());
    if (calculatedValue >= 10 && calculatedValue < 18) {
      im1.setBackgroundResource(R.drawable.s1);
      m5.setText("low");
    } else if (calculatedValue >= 18 && calculatedValue < 25) {
      im1.setBackgroundResource(R.drawable.s3);
      m5.setText("Best");
    } else if (calculatedValue >= 25 && calculatedValue < 100) {
      im1.setBackgroundResource(R.drawable.s3);
      m5.setText("over");
    }
  }

A: *

*Your  switch statement here is useless, You have already set click listener to button and again you are trying to check if it's the same button clicked.

*It would good if you check if the value entered is numeric.

*when you use if, else if and else - one and only one will be executed, which ever full fills the statement will be executed and rest of the code won't execute, say for instance have a look at the following:

   if( a > b){
     //show A is bigger than b;
     } else if ( a == b){
     // show A equals to b
    } else{
    // b > a
     }

Here,
 if (word.trim().equals("")){//if this conditions works, code won't go to test else if or else statement.
          mEditText1.setError("Insert Hight");
        }
        else if (word2.trim().equals("")){
          mEditText2.setError("Insert Wight");
        } else{
          calculate();
        }

*The way you are checking the values is wrong, the statement will be always false, as 1. you are testing if the value if < 10 and at the same time you are test if the value is > 18, one of which be false for sure.
if(mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18)


text:
Q: How to backup a flume master node config? I am using flume on a project and am looking for a way to backup the config for the master node. How would I go about doing this? I can't seem to find any info regarding backups on the user guide.
Also, I am looking to have multiple copies of the master node running so that if one fails a copy can take over. I am unaware of how to do this either - does anyone have any suggestions?

A: you need to change the zookeeper log dir in flume-conf.xml , the default is tmp dir which doesn't save the configuration between restarts.
see this thread
http://www.mail-archive.com/flume-user@incubator.apache.org/msg00173.html


text:
Q: User registration with CodeIgniter I'm trying to build a registration system with CodeIgniter. I have a controller called Register with the following code:
class Register extends CI_Controller {
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
        $this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
        $this->load->view('header');
        if(!$this->form_validation->run())
        {
            $this->load->view('register_form');
        }
        else
        {
            $this->load->view('register_done');
        }
        $this->load->view('footer');
    }
}

So far so good. If I go to the register page I get the registration form displayed. If I send the form and it passes the form validation checks, I get the success page, if the form has errors, I get the form back with some error messages.
Now what I want to do is the database stuff. I have some idea of how I can get the POST values from the registration form into my database, but no clue how I can check if a username or email already exists, and if so, display that error on the registration form. Here's my registration form view:
<?php $this->load->helper('form'); ?>
<?php echo form_open('register'); ?>

Account information

                Choose a username
                <input type="text" name="username" value="<?php echo set_value('username'); ?>" />
                The name you'd like to be known by
                <?php echo form_error('username'); ?>

                Pick a password
                <input type="password" name="password" />
                The best passwords are random and more than 6 characters long
                <?php echo form_error('password'); ?>

                Enter your valid email address
                <input type="text" name="email" value="<?php echo set_value('email'); ?>" />
                We'll send you an activation email
                <?php echo form_error('email'); ?>

About you

                Who's your favorite artist?
                <input type="text" name="artist" value="<?php echo set_value('artist'); ?>" />
                Don't put Lady GaGa.
                <?php echo form_error('artist'); ?>

Security question

                Enter the letters you see in the image
                <?php $this->load->helper('captcha');
                $cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
                $data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
                $query = $this->db->insert_string('captcha', $data);
                $this->db->query($query);
                echo $cap['image']; ?>
                <input type="text" name="captcha" />
                <?php echo form_error('captcha'); ?>

                <input type="submit" value="Register" />

<?php echo form_close(); ?>

As you can see, I'm taking advantage of the form_error() function of CI to display form errors right under the field, and I would like the "username already exists" error to also be displayed under the username field.
Can anyone provide some help? Even a nudge in the right direction?
Thanks!

A: I would strongly urge you to think about using another library that already does this very well: TankAuth. TankAuth is easily modifiable and offers email confirmation, very secure password hashing, a solid database schema, and very clean code.
There's no reason to reinvent the wheel, especially when it comes to something that's very hard to get right like user authentication.
EDIT:
For example, here's everything TankAuth provides security-wise that you'd have to code yourself (if you cared about security) - how much time would that take?
Using phpass library for password hashing (instead of unsafe md5).
Counting login attempt for bruteforce preventing (optional). Failed login attempts determined by IP and by username.
Logging last login IP-address and time (optional).
CAPTCHA for registration and repetitive login attempt (optional).
Unactivated accounts and forgotten password requests auto-expire.

A: You need to create a model for your controller.
Your model would look like this:
class Register_model extends CI_Model {
    function register_user()
    {
        $data['username'] = $this->input->post('username');
        $data['password'] = sha1($this->input->post('password'));
        ... (your other post data) ...
        $this->db->insert('users', $data);
    }
}

In your controller you will call the model this way:
$this->load->model('Register_model');

and the method goes here:
else
{
    $this->Register_model->register_user();
    $this->load->view('register_done');
}

If you want to check if the username is available, you simply put SELECT query on the first lines of the register_user() method (function).

A: To do the check you should have functions in your model that can look up those types of things for you:
class Model{
    function getUserByEmail($email);
    function getUserByUsername($username);
    ...
}

Then in your controller you can call these methods
...
$result = $model->getUserByEmail($_POST['email']); // You'll need to sanitize your POST
if(count($result) > 0){
    // Sent error about email already existing and flag to not insert/update user
}
...

A: The easiest solution in CodeIgniter is to use a callback function as one of the rules in your form validation.
I've used this method myself to check the username and e-mail.
Here's the docs for it.

A:
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {

    parent::__construct();

    $this->load->helper('form');

    // Load session library
    $this->load->library('session');

    // Load database
    $this->load->model('User_model');

}

public function index()
    {

        $this->load->view('index');

    }
    public function project()
    {
          $this->data['posts'] = $this->User_model->getPosts(); // calling Post model method getPosts()
            $this->load->view('tables', $this->data);

            // $this->load->aview('project');
    }

    public function get_project()
    {
        $this->User_model->get_project($data);
    }
    public  function signin()
    {

        $data = array(
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password')
        );
        $this->User_model->signin($data);
    }

    public function logout()
    {
        $this->session->unset_userdata($_SESSION['email']);
        // $this->session->sess_destroy();
        redirect('User');
    }
    public function signup()
    {

     $data = array(
            'name' => $this->input->post('name'),
            'phone' => $this->input->post('phone'),
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password')
        );

     if($this->User_model->signup($data))
     {

        echo "no insert";
     }
     else
     {

        $this->load->view('index', $data);
     }

}
}

A: <?php

Class User_model extends CI_Model {

    function __construct() {
    parent::__construct();
    $this->load->library('session');

    }

    public function signup($data)
    {

        $this->db->insert('user_signup',$data);

    }

    public function getPosts()
     {
              $this->db->select("*");
              $this->db->from('user_data');
              $query = $this->db->get();
              return $query->result();
    }

    public function signin($data)
    {
            $this->db->where('email',$data['email']);
            $this->db->where('password',$data['password']);
            $query=$this->db->get('user_signup');
            if($query->num_rows()==1){

                $_SESSION['email'] = $data['email'];

                $this->load->view('popup',$data);

                return true;
    }
    else{
            echo "no";
            return false;
    }
    }

}


text:
Q: How to create process as user with arguments Tried to create a process as a user with portablechrome.exe but I could not handle it with arguments.
How can I open an HTML file with arguments?
Such as portablechrome.exe sample.html --kiosk
I'm using system service like this:
string url = @System.AppDomain.CurrentDomain.BaseDirectory + "updater.html ";
string kioskMode = url + " --kiosk --incognito --disable-pinch --overscroll-history-navigation=0 ";

StartProcessAsCurrentUser("C:\\Chrome\\PortableChrome.exe", kioskMode);

And my wrapper for StartProcessAsUser:
public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
{
    appPath = appPath + " " + cmdLine;
    var hUserToken = IntPtr.Zero;
    var startInfo = new STARTUPINFO();
    var procInfo = new PROCESS_INFORMATION();
    var pEnv = IntPtr.Zero;
    int iResultOfCreateProcessAsUser;

    startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));

    try
    {
        if (!GetSessionUserToken(ref hUserToken))
        {
            throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
        }

        uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
        startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
        startInfo.lpDesktop = "winsta0\\default";

        if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
        {
            throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
        }

        if (!CreateProcessAsUser(hUserToken,
            appPath, // Application Name
            cmdLine, // Command Line
            IntPtr.Zero,
            IntPtr.Zero,
            false,
            dwCreationFlags,
            pEnv,
            workDir, // Working directory
            ref startInfo,
            out procInfo))
        {
            iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
            throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.  Error Code -" + iResultOfCreateProcessAsUser);
        }

After I call this function, kiosk mode Incognito Chrome opens but not my html file. Just a blank page.
So how can I open a html file with arguments?

A: Remove the
appPath = appPath + " " + cmdLine;

and replace to CreateProcessAsUser the cmlLine parameter with
$@"""{appPath}"" {cmdLine}"

We had the same problem and get a lot of time to figure it out
Working Example
    static void Main()
    {
        var url = @"Test.html";
        var kioskMode = url + " --kiosk --incognito --disable-pinch --overscroll-history-navigation=0 ";

        StartProcessAsCurrentUser(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", kioskMode);
    }

    public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
    {
        var hUserToken = IntPtr.Zero;
        var startInfo = new STARTUPINFO();
        var procInfo = new PROCESS_INFORMATION();
        var pEnv = IntPtr.Zero;

        startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));
        hUserToken = WindowsIdentity.GetCurrent().Token; //get current user token

        var dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint) (visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
        startInfo.wShowWindow = (short) (visible ? SW.SW_SHOW : SW.SW_HIDE);
        startInfo.lpDesktop = "winsta0\\default";

        if (!CreateEnvironmentBlock(out pEnv, hUserToken, 0))
        {
            throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
        }

        if (!CreateProcessAsUser(hUserToken,
            appPath, // Application Name
            $@"""{appPath}"" {cmdLine}", // Command Line
            IntPtr.Zero,
            IntPtr.Zero,
            false,
            dwCreationFlags,
            pEnv,
            workDir, // Working directory
            ref startInfo,
            out procInfo))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        return true;
    }

    private const int CREATE_NO_WINDOW = 0x08000000;
    private const int CREATE_NEW_CONSOLE = 0x00000010;
    private const int CREATE_UNICODE_ENVIRONMENT = 0x400;

    [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, int bInherit);

    [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
    public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, uint dwCreationFlags,
        IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public int cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }

    public enum SW
    {
        SW_HIDE = 0,
        SW_SHOWNORMAL = 1,
        SW_NORMAL = 1,
        SW_SHOWMINIMIZED = 2,
        SW_SHOWMAXIMIZED = 3, // these two enum members actually have the same value
        SW_MAXIMIZE = 3, // assigned to them This is not an error
        SW_SHOWNOACTIVATE = 4,
        SW_SHOW = 5,
        SW_MINIMIZE = 6,
        SW_SHOWMINNOACTIVE = 7,
        SW_SHOWNA = 8,
        SW_RESTORE = 9,
        SW_SHOWDEFAULT = 10,
        SW_FORCEMINIMIZE = 11,
        SW_MAX = 12
    }


text:
Q: On recovering a bounded operator from a bi-linear form Let $\mathcal{H}$ be real Hilbert space, $b(\cdot,\cdot)$ is a bi-linear form on $\mathcal{H}$ and satisfies
\begin{equation}
\begin{split}
\sup_{||v||=1}\sup_{||u||=1}b(u,v)\leq C_0\cdots(1)\\
\inf_{||v||=1}\sup_{||u||=1}b(u,v)\geq C_1\cdots(2)\\
\inf_{||u||=1}\sup_{||v||=1}b(u,v)\geq C_2\cdots(3)
\end{split}
\end{equation}
where $C_0,C_1,C_2$ are positive constants, then the problem asks to show that there exists a unique bounded linear operator $B\in\mathcal{L}(\mathcal{H})$ such that $b(u,v)=(u,Bv)$ and $B$ have bounded inverse.
[Observation]
The construction of $B$ is straightforward from (1) and Riesz Representation theorem, the problem is to show that $B$ thus defined is both injective and surjective. The injective part can be shown quite easily while the sujective part was still under consideration. I was wondering if there is some $\delta>0$ such that (2),(3) implies
$$|b(u,u)|\geq \delta ||u||^2$$
then we can solve the problem by simply applying Lax-Milgram theorem, but it does not come to me very quickly....

A: As you said, (1) gives you the existence of $B$. Now you can look at (2), but written as
$$
C_1\leq\inf_{\|v\|=1}\sup_{\|u\|=1}\langle u,Bv\rangle=\inf_{\|v\|=1}\|Bv\|.
$$
So $\|Bv\|\geq C_1$ for all $v$ with $\|v\|=1$, from where we deduce that
$$
\|Bv\|\geq C_1\,\|v\|
$$
for all nonzero $v$. This implies that $B$ is injective, and that its inverse (if it exists) is bounded.
Now (3) gives you the same information that (2) but for $B^*$. So $B^*$ is injective, which means that
$$
\overline{\mbox{ran}(B)}=\ker(B^*)^\perp=\{0\}^\perp=\mathcal H.
$$
So the range of $B$ is dense, and we can define $B^{-1}$ on it. As $B^{-1}$ is bounded by (2), it can be extended to all of $\mathcal H$, and this shows that the range of $B$ was closed to start with. So $B$ is invertible.


text:
Q: Basic Windsor Constructor Injection I am new to Windsor and am trying to implement the most basic constructor injection. Apparently the API has changed so much over the recent versions that the documentation that is for the current version seems to assume you already know how to do it, and the documentation for the old versions is outdated.
I have a simple test component:
public class ConstructorInjectedComponent
{
    public IMyComponent Component { get; set; }

    public ConstructorInjectedComponent(IMyComponent component)
    {
        Component = component;
    }
}

There is a simple implementation of IMyComponent:
public class AMyComponent : IMyComponent
{
    public string Name { get; set; }

    public AMyComponent()
    {
        Name = Guid.NewGuid().ToString("N");
    }
}

And I want to somehow register my types with Windsor such that I can get back an instance of ConstructorInjectedComponent that contains an instance of its dependency: IMyComponent.
I've register AMyComponent like so:
_container.Register(Component.For(typeof(AMyComponent)));

I've register ConstructorInjectedComponent like this:
_container.Register(Component.For(typeof(ConstructorInjectedComponent)));

and tried to resolve it with
_container.Resolve(typeof(ConstructorInjectedComponent));

But that fails with "can't create component ConstructorInjectedComponent because it has dependencies which need to be satisfied.
so I try to pass in an IDictionary of dependencies for the ConstructorInjectedComponent ... and this is where the documentation fails me.
I have no idea how to define that dictionary. I can find no documentation which explains it. I've tried this:
var d = new Dictionary<string, string>() {{"IMyComponent", "AMyComponent"}};
_container.Register(Component.For(typeof(ConstructorInjectedComponent))
                    .DependsOn(dependencies));

But that fails with the same "has dependencies that need to be resolved" error.
What am I doing wrong?

A: First it's crucial to make sure you understand the basic concepts, namely what a component is, what a service is, and what a dependency is.
The documentation about it is quite good.
The documentation about how to use registration API should help you get going.
The tl;dr asnwer is: since ConstructorInjectedComponent depends on IMyComponent make sure you register AMyComponent to expose  IMyComponent as a service.
_container.Register(Component.For<IMyComponent>().ImplementedBy<AMyComponent>());


text:
Q: securing laravel api in angular I have this auth.interceptor.ts
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler } from "@angular/common/http";
import { TokenService } from "../shared/token.service";

@Injectable()

export class AuthInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const accessToken = this.tokenService.getToken();
        req = req.clone({
            setHeaders: {
                Authorization: "Bearer " + accessToken
            }
        });
        return next.handle(req);
    }
}

it is called in app.module.ts and other module.ts file
import { AuthInterceptor } from './shared/auth.interceptor';

  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],

but i can access all the laravel apis without token

Calling api:

this.http.post(this.baseUrl+'api/auth/load-data', formData).subscribe(result  => {
  this.lists=result;
  },(error) => {
});

I want to secure my laravel api

A: have you uesed laravel passport?
with that package you can secure your laravel apis

A: You should use the passport package in order to secure your APIs, this is the doc from the Laravel website:
https://laravel.com/docs/8.x/passport
I think its straight forward


text:
Q: How can I capture all images within  using regex? I've been struggling with this due to my lacking REGEX experience. I need to extract the pattern of all img tags in html which occur inside p tags. i.e:

Hello  World

Crazy  Town

Should return:

I have this regex so far which captures the img pattern:
)>

However it captures all imgs, where as I need only those that appear within a p tags, but do NOT want the p tag to be included in the result.
Many thanks

A: If your programming language or tool supports capturing groups with regex, then you can use
]*>[^<]*(?:<[^>]*>[^<]*)*?(]*>)[^<]*(?:<[^>]*>[^<]*)*?
 to capture just the img tags within p tags.
Using Python as an example:
import re
html = '''
Hello  World

Crazy  Town
'''
print(re.findall(r'
]*>[^<]*(?:<[^>]*>[^<]*)*?(]*>)[^<]*(?:<[^>]*>[^<]*)*?
', html, re.IGNORECASE | re.DOTALL))

This outputs:
['', '']

A: Try

.*(]*>).*<\/p>
Use the inner group () for capture

A: You can't. HTML is a context-free language and regular expressions can only denote regular languages.
Edit: You can probably one image tag but if you're expecting a dynamic amount of tags, you can't do it with one regular expression.

A: Instead of parsing html with a regex which is not advisable you might use a DOMParser.

let parser = new DOMParser();
let html = `
Hello  World

Crazy  Town
`;
let doc = parser.parseFromString(html, "text/html");
let imgs = doc.querySelectorAll("p img");
imgs.forEach((img) => {
  console.log(img.outerHTML)
});


text:
Q: Automorphisms of the unit disk I ran into a bit of a hurdle as I was reading a proof in Newman Bak's Complex Analysis regarding the form of automorphisms of the unit disk.
The proof begins by showing that $g(z)=\frac{z-\alpha}{1-\bar{\alpha}z}$ is an automorphism of the unit disk. This is the part I'm having a bit of trouble with.
By previous work, we have proved that $|g(z)|=1$ for $|z|=1.$ "Since $g(\alpha)=0$, it follows that g is indeed an automorphism of the unit disk." (Newman Bak, 183).
Here is my attempt to fill in the gaps:
If $f(z)=\frac{az+b}{cz+d}$, where $ad-bc\not=0$, then f is a bilinear transformation and is therefore conformal and globally 1-to-1.
In order to show that g is bilinear, we need to show that $1-\alpha\bar\alpha\not=0.$ Suppose by contradiction that $1-\alpha\bar\alpha=0.$ Then $|\alpha| = 1$. However, since we know that $|g(z)|=1$ for $|z|=1,\ g(\alpha)=1$. This is a contradiction since $g(\alpha)=0.$
Likewise, since $|\alpha|\not=1$, $C(\alpha; 1)$ does not pass through the origin. Thus, we know that our bilinear map g sends circles to circles (i.e., it does not send circles to lines). We conclude that g is an automorphism of the unit disk.
Does this seem correct?


text:
Q: Usage of "to" vs "from" While writing a cover letter, I wrote a following a sentence.
"I am confident that I possess the pertinent skills to successfully complete this course and am one opportunity away to making a significant contribution to the community in upcoming years."
Is it correct?
or should have I written the following?
"I am confident that I possess the pertinent skills to successfully complete this course and am one opportunity away from making a significant contribution to the community in upcoming years."
Which one of the above is correct?

A: You have two choices.  You can say either

I am one opportunity away from making a significant contribution

or you can say

I am close to making a significant contribution

Similar to the first sentence is:

The bullet came within a hair of hitting the aorta.


text:
Q: Pandas - sort columns in correlation table I am running a pearson correlation on my data set (from Excel) and this is the order the results come out as:

What I was wondering is if it is possible to get the n_hhld_trip as my first column as it is my dependent variable.
Below is my code that I have so far but not sure how to make it reflect the changes I want. I tried moving the variables in the pivot table command but that didn't do it:
zone_sum_mean_combo = pd.pivot_table(
    read_excel,
    index=['Zone'],
    aggfunc={'Household ID': np.mean, 'dwtype': np.mean, 'n_hhld_trip': np.sum,
             'expf': np.mean, 'n_emp_ft': np.sum, 'n_emp_home': np.sum,
             'n_emp_pt': np.sum, 'n_lic': np.sum, 'n_pers': np.sum,
             'n_student': np.sum, 'n_veh': np.sum}
)

index_reset = zone_sum_mean_combo.reset_index()
print(index_reset)

pearson_correlation = index_reset.corr(method='pearson')
print(pearson_correlation)

A: Sometimes it can be easier to hardcode the column order after everything is done:
df = df[["my_first_column", "my_second_column"]]

In your case, I think it's easier to just manipulate them:
columns = list(df.columns)
columns.remove("n_hhld_trip")
columns.insert(0, "n_hhld_trip")
df = df[columns]

A: Try to set_index and reset_index:
df.set_index('n_hhld_trip', append=True).reset_index(level=-1)


text:
Q: MFMailComposerViewController via UIActivityViewController error I'm trying to open a mail composer via UIActivityViewController on iOS8. (So, there's no my own code for this procedure) The result on device is continues error logging (the messages continue to be logged even after I close mail and quit to different UI controller)
AX Exchange error: Error Domain=Accessibility Code=0 "Remote service does not respond to _accessibilityMachPort" UserInfo=0x14fd1b60 {NSLocalizedDescription=Remote service does not respond to _accessibilityMachPort}
On a simulator the MFMailComposeViewController just dismisses right after I present it with error:
viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "The operation couldn't be completed. (_UIViewServiceInterfaceErrorDomain error 3.)" UserInfo=0x7b6eb4b0 {Message=Service Connection Interrupted}
P.S.  I have xcode 6 and testing on iOS 8.0.2 iPhone 5s. Am I doing something wrong? Thanks in advance for your replies!

A: I came across same problem in my product and after doing some debugging, I narrowed down that it's the combination of presented ViewController and custom keyboard. That means my application was showing this error message only when I navigated to any presented ViewController (like mail composer) and a custom keyboard was activated.
During further hit-and-try, I was able to get rid of this error message by removing MonkeyTalk library, which was being used for automated testing.
I am not sure if same scenario applies to you, but I am sure that some library is conflicting with some keyboard and that's resulting in error message.
P.S. in my case my application was being freezed by those error messages.


text:
Q: Can we have two different authentication styles and still achieve a SSO Can we have two different authentication styles and still achieve a SSO?
My current application (Green) is authenticating using SAML against our AD.
My new cloud application (light blue) is using authentication using AAD using OpenID Connect
The AD is synchronised using AAD Connect to allow pass through authentication.


text:
Q: What to do when last_pts > current_pts using ffmpeg libs (C++) Im having some hard time figuring out where to find about this..
Im building a simple recorder to learn about this video compression universe and Im facing some weird behaviors..
Before all I need to explain the scenario...
Its very simple... everytime I call av_read_frame( input_context, input_packet )  I save the pts into the last_pts variable...
So...
Whats bothering me is the fact that about 10% of my calls to av_read_frame I get
input_packet.pts > last_pts
Resulting in a error message from the encoder when I try to do it...
Having it in mind I decided to just drop those frames when it happens....
I think it is not a good idea to just drop frames because if I get them, its needed somehow...
So... what to do when last_pts > current_pts ?
I will paste my test code that Im using capturing the video from webcam and saving to mp4 file with libx264 encoder
#include <QCoreApplication>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/avutil.h>
#include <libavdevice/avdevice.h>
}

#include <QTime>
#include <QThread>
#include <QDebug>

#define SM_DEBUG

static const double max_fps = 30;
static const double min_loop_duration = 1000 / max_fps;
static const double max_duration = 5; // in seconds

static void sleep_if_needed(const int &elapsed) {
    int sleep_duration = min_loop_duration - elapsed;

    if (sleep_duration > 0)  {
        QThread::msleep(sleep_duration);
    }
}

#ifdef SM_DEBUG
static void log_packet(const AVPacket *pkt,
                       const AVRational &time_base,
                       int is_input=0)
{

    qDebug() << ((is_input) ? QString(">>") : QString("<<"))  << "Size:" << QString::number(pkt->size) <<
        "pts:" << QString::number(pkt->pts) <<
        "pts_time:" << QString::number(av_q2d(time_base) * pkt->pts) <<
        "dts:" << QString::number(pkt->dts) <<
        "dts_time:" << QString::number(av_q2d(time_base) * pkt->dts);
}
#endif

int main()
{
    int input_w, input_h, output_w = 640, output_h = 480;

    av_register_all();
    avdevice_register_all();
    avcodec_register_all();
#ifdef SM_DEBUG
    av_log_set_level(AV_LOG_DEBUG);
#else
    av_log_set_level(AV_LOG_ERROR);
#endif

    AVFormatContext *ic;
    AVFormatContext *oc;

    AVInputFormat *ifmt;

    AVDictionary *opts = 0;

    AVCodecContext* dec_ctx;
    AVCodecContext* enc_ctx;
    AVCodec *dec;
    AVCodec *enc;

    AVStream* ist;
    AVStream* ost;

    ifmt = av_find_input_format("v4l2");

    av_dict_set(&opts, "tune", "zerolatency", AV_DICT_APPEND);
    ic = avformat_alloc_context();

    ic->flags |= AVFMT_FLAG_NONBLOCK;

    avformat_open_input(&ic, "/dev/video0", ifmt, &opts);

    avformat_find_stream_info(ic, NULL);

    av_dump_format(ic, 0, ic->filename, 0);

    AVFrame *frame;
    AVFrame *tmp_frame;

    ist = ic->streams[0];

    dec_ctx =  ist->codec;

    input_w = dec_ctx->width;
    input_h = dec_ctx->height;

    dec_ctx->flags |= CODEC_FLAG_LOW_DELAY;
    dec = avcodec_find_decoder(dec_ctx->codec_id);

    av_format_set_video_codec(ic, dec);
    avcodec_open2(dec_ctx, dec, NULL);

    // output

    avformat_alloc_output_context2(&oc, NULL, "MP4", "/home/poste9/grava.mp4");

    enc = avcodec_find_encoder(AV_CODEC_ID_H264);
    ost = avformat_new_stream(oc, enc);
    enc_ctx = ost->codec;

    enc_ctx->codec_id = AV_CODEC_ID_H264;
    enc_ctx->width = output_w;
    enc_ctx->height = output_h;

    ost->time_base.num = ist->time_base.num;
    ost->time_base.den = ist->time_base.den;

    enc_ctx->time_base = ost->time_base;

    enc_ctx->gop_size = 250;
    enc_ctx->keyint_min = 25;
    enc_ctx->qmax = 51;
    enc_ctx->qmin = 30;
    enc_ctx->pix_fmt = AV_PIX_FMT_YUV422P;
    enc_ctx->max_b_frames = 6;
    enc_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
    enc_ctx->flags |= CODEC_FLAG_LOW_DELAY;

    avcodec_open2(enc_ctx, enc, NULL);

    avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,
               &oc->interrupt_callback, NULL);

    av_dump_format(oc, 0, oc->filename, 1);

    avformat_write_header(oc, NULL);

    struct SwsContext *sws_ctx;

    sws_ctx = sws_getContext(input_w, input_h,
                             dec_ctx->pix_fmt,
                             output_w, output_h, enc_ctx->pix_fmt,
                             SWS_BICUBIC, NULL, NULL, NULL);

    frame = av_frame_alloc();
    tmp_frame = av_frame_alloc();

    frame->format = enc_ctx->pix_fmt;
    frame->width = output_w;
    frame->height = output_h;
    frame->pts = AV_NOPTS_VALUE;

    av_frame_get_buffer(frame, 32);
    av_frame_make_writable(frame);

    int got_picture=0;
    int got_packet=0;

    double recording_duration = 0;

    QTime timer;

    AVPacket pkt_out;

    av_init_packet(&pkt_out);

    timer.start();

    bool started_recording = false;

    int64_t start_time = 0;

    int64_t last_pts = INT64_MIN;

    while(1) {
        timer.restart();
        AVPacket pkt_in;

        av_read_frame(ic, &pkt_in);

        if (pkt_in.size == 0) {
            sleep_if_needed(timer.elapsed());
            continue;
        }

        avcodec_decode_video2(dec_ctx, tmp_frame, &got_picture, &pkt_in);

#ifdef SM_DEBUG
        log_packet(&pkt_in, ist->time_base, 1);
#endif

        if (!started_recording) {

            start_time = pkt_in.dts;
            started_recording = true;
        }

        if (pkt_in.pts < last_pts) {

            sleep_if_needed(timer.elapsed());

            continue;
        }

        last_pts = pkt_in.pts;

        frame->pts = (pkt_in.dts - start_time);

        if (!got_picture) {

            av_free_packet(&pkt_in);

            sleep_if_needed(timer.elapsed());

            continue;
        } else {
            sws_scale(sws_ctx, tmp_frame->data, tmp_frame->linesize,
              0, input_h, frame->data, frame->linesize);

            av_free_packet(&pkt_in);
        }

        av_init_packet(&pkt_out);

        avcodec_encode_video2(enc_ctx, &pkt_out, frame, &got_packet);

        if (got_packet) {

            if (pkt_out.pts < pkt_out.dts) {
                pkt_out.dts = pkt_out.pts;
            }

            pkt_out.stream_index = 0;

            recording_duration = pkt_out.pts * av_q2d(ost->time_base);
#ifdef SM_DEBUG
            log_packet(&pkt_out, ost->time_base, 0);
#endif

            av_interleaved_write_frame(oc, &pkt_out);

            av_free_packet(&pkt_out);
        }

        if (recording_duration >= max_duration) {

            break;

        } else {

            sleep_if_needed(timer.elapsed());
        }
    }

    av_write_trailer(oc);

    av_dict_free(&opts);

    av_frame_free(&frame);
    av_frame_free(&tmp_frame);

    sws_freeContext(sws_ctx);

    avcodec_close(dec_ctx);
    avcodec_close(enc_ctx);

    avio_close(oc->pb);
    avformat_free_context(oc);

    avformat_close_input(&ic);

    return 0;
}

A: These frames are B frames. B frames are saved to the stream in decoding order, not presentation order. If you look at the DTS it will probablly look ok. it is the job of the decoder to reorder frames into presentation order after they are decoded.
EDIT. to fix your code, use the PTS from the decoded frame, not the packet.