text:
Q: Can't convert object of type java.lang.Long to type com.example.or.dancers.Info I am trying to insert info to a Firebase Database , and I am Getting the above error.
Full stacktrace:
04-16 02:42:14.218 6214-6214/com.example.or.dancers E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.or.dancers, PID: 6214
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.or.dancers.Info
  at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
  at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
  at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
  at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
  at com.example.or.dancers.Settings$1.onDataChange(Settings.java:187)
  at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
  at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
  at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:158)
  at android.app.ActivityThread.main(ActivityThread.java:7229)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

My Object Model:
package com.example.or.dancers;

public class Info {

public String key;
public String infoName;
public int data;

public Info() {
}

public Info(String key, String name, int data) {
    this.key = key;
    this.infoName = name;
    this.data = data;
}
}

the retrieveData function:
public void retrieveData() {

    database.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot data : dataSnapshot.getChildren()) {
                Info d = data.getValue(Info.class);

                if(d.key.equals(info.key)){
                    info =d;
                    return;
                }

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

}//retrieveData function.

I stuck at this , and because of that I cant move on.
Any help would be appreciated.
get value:
 public Object getValue() {
    return this.zzbXv.zzUY().getValue();
}

public Object getValue(boolean var1) {
    return this.zzbXv.zzUY().getValue(var1);
}

public <T> T getValue(Class<T> var1) {
    Object var2 = this.zzbXv.zzUY().getValue();
    return zzbqi.zza(var2, var1);
}

public <T> T getValue(GenericTypeIndicator<T> var1) {
    Object var2 = this.zzbXv.zzUY().getValue();
    return zzbqi.zza(var2, var1);
}

A: I think that you should debug to find what values did you pass to your Info object. Because of this error related to convert Long to Info:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.or.dancers.Info


text:
Q: Profesionally looking graphs from gnuplot I understand this is going to be fairly subjective, but I am looking for example scripts to generate "professionally looking" graphs from gnuplot. I am plotting 3-5 price processes from a data file (all having same domain and same range of values), and I am looking for a set of tweaks to make the output look better, so that I can include it in a report or publication. Unfortunately I am rather disabled visually, so I am not able to define what I am really after - but the point is that the default plot generated by Mathematica looks kind of nice, and a default one from gnuplot resembles the 90-ties. I would be grateful for complete examples (preferably in vector format).

A: I find that the epslatex terminal in gnuplot creates good results. It requires having a latex distribution around, but the results are really good. Try starting your file with something like
set terminal epslatex standalone header '\usepackage{color}'
set output 'image.tex'

After this you could use regular plotting commands - gnuplot will typeset everything using Computer Modern fonts, and save the resulting image into image.tex which you can compile into dvi and then convert to ps/pdf as you wish.
Shameless plug: I've written a shell script to automate the whole process for me. The script takes the Gnuplot script and outputs a png file, sampled from the ps at 300 dpi, which seems to be sufficient for academic journals. Of course, you could skip the conversion to png and just keep the ps/pdf image, but my images tended to have huge number of datapoints which made pdfs large (tens of MBs), making them unsuitable for submitting for publication.
Here's the link to the script: http://bitbucket.org/mbudisic/cl-goodies/src/tip/figlatex
When I wrote it, I didn't know how to use grep properly, so I wrote my own regexp python script, which figlatex depends on, but you could replace that if you wished.
http://bitbucket.org/mbudisic/cl-goodies/src/tip/regexp
Hope this helped.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Password encrypting error in JSP I coded for encrypt user entered password and compare that password in database encrypted password.
I have successfully used this code in Java program but in this JSP page it show an exception.
code:
<%
String CONN_STRING = "jdbc:mysql://localhost/pmsdb";
String USERNAME = "dbuser";
String PASSWORD = "dbpassword";

Connection conn=null;
PreparedStatement pst=null;
ResultSet rs =null;

 //variables to encrypt
    byte [] input ;
byte [] keyBytes = "12345678".getBytes();
byte [] ivBytes ="input123".getBytes();

SecretKeySpec key = new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText;
int ctLength=0;

Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
    String user = request.getParameter("Username");
    session.putValue("Username",user);
    String pwd = request.getParameter("Password");

    //checking with pwd encryptd in db
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
      input = pwd.getBytes();
      key = new SecretKeySpec(keyBytes, "DES");
      ivSpec = new IvParameterSpec(ivBytes);
      cipher = Cipher.getInstance("DES/CTR/NoPadding","BC");

      cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
      cipherText = new byte[cipher.getOutputSize(input.length)];

      ctLength+=cipher.update(input, 0, input.length, cipherText, 0);

      ctLength+= cipher.doFinal(cipherText, ctLength);
      String epwd = new String(cipherText);

    String sql = "select * from websupplierinfo where username=? and password=?";
    pst = conn.prepareStatement(sql);
    pst.setString(1,user);
    pst.setString(2,epwd);
    rs = pst.executeQuery();
    if(rs.next()){
        if(rs.getString("password").equals(epwd)){
            //wantto go to supplier home page
            response.sendRedirect("supplierpg-status.jsp");
        }else{
        %>
        <script language="JavaScript">
            alert("Incorrect Login Details.. Try again");
        </script>
        <%
        }
    }
    %>

exception:

How can I fix this;


text:
Q: Nested ng-include makes AngularJS load infinitely I have a Rails 4 App with such an assets filetree:
- Assets
- - Javascripts
- - - ng-controllers
- - - - parrotsController.coffee
- - - ng-views
- - - - partials
- - - - - _parrots_index.html.slim
- - - - - _parrots_index_paginator.html.slim
- - - - home.html.slim
- - - app.coffee
- - - routes_config.coffee

routes_config.coffee:
...
    $routeProvider
      .when '/',
        templateUrl: 'ng-views/home.html',
        controller: 'ParrotsController as vm' # Modern 'as' syntax
                                              # 'vm' goes for ViewModel
      .otherwise
        redirectTo: '/'
...

home.html.slim:
...
  div ng-include="'ng-views/partials/_parrots_index.html'"
...

_parrots_index.html.slim:
...
  tr ng-include="'ng-views/partials/_parrots_index_paginator.html.slim'"
...

_parrots_index_paginator.html.slim:
td
  | Some content, no models here

So, if I do not ng-include _parrots_index_paginator.html.slim within _parrots_index.html.slim but just insert its code, it works fine (even if it's inserted twice).
However, leaving everything as in the code listed above leads to infinite assets loading. Why?
My Gemfile:
gem 'jquery-rails'
gem 'angularjs-rails', git: 'https://github.com/ScoutRFP/angularjs-rails' # <- Better fork
gem 'angular-rails-templates'
gem 'angular_rails_csrf'

application.coffee:
#= require jquery
#= require jquery_ujs
#= require bootstrap-sprockets
#= require angular
#= require angular-resource
#= require angular-route
#= require angular-animate
#= require angular-rails-templates
#= require angular-bootstrap/ui-bootstrap-tpls.min
#= require angular-loading-bar

#= require_tree .

Thanks for any help and let me know if you need more code.

A: In your example of _parrots_index.html.slim, you have:
...
tr ng-include="'ng-views/partials/_parrots_index_paginator.html.slim'"
...

Shouldn't that be including the HTML file (not .slim)?


text:
Q: How to pass data from node js to html.? How can I simply pass a variable from node js to html and display it in the page?
What is the simple mechanism.
I am trying to develop a simple to-do list using node js

A: There are two approaches here you can use to view data from node( server side ) to html:
1- You could create a file in node which return data in json, then from JQuery you could do an ajax call this page and replace parts of the HTML with it.
   Sample code in node js:
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
    var readable = fs.createReadStream(usersFilePath);
    readable.pipe(res);
});

Ajax call:
$.get( "/users", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

2- You could use express with Jade ( I recommend
    http://expressjs.com/ )
Here is my blog on how to get started with node.js Click Here
I created a starter kit for nodejs If you are interested Click Here

A: Establish a route and use res.send method to respond with html content. The html content can use es2015 templates to include a variable in response. So it would look like:
const name = 'pradeep';
res.send(`hello ${name}`);

A: Try this, it may help you.
The Following function will bind your dynamic data to html
function doDataBinding(data, databindings){
for(var prop in databindings)
    if( databindings.hasOwnProperty(prop) )
        data = data.split('${'+prop+'}').join(databindings[prop]);
return data;

}
Sample request to verify dynamic data binding is as follows
app.use('/*', function(req, res){
//sample binding data
var dataToBind = { 'msg' : 'You\'ve been logged out successfully.' , 'error' : 'The username and password that you entered don\'t match.' };
res.writeHead(200, {
        "Content-Type": "text/html"
});
fs.readFile( __dirname + '/login.html', 'utf8' ,function(err, data) {
    if (err) throw err;
    data = doDataBinding(data,dataToBind);
    res.write(data);
    res.end();
});

});
Try with login.html which is having ${msg} and ${error} data bindings.


text:
Q: Record Video in Android with a watermark I am creating an application to take a video from the front camera and add a logo and save it.
I read about FFmpeg and have used it Linux. Is there any simple ways present to do the same.
I have already coded the application.I am trying to add a Frame to the video while taking/saving.

A: You can use the ffmpeg library in Android also.
Often the easiest way is to use one of the well supported wrapper libraries - this one is a good example:

*

*https://github.com/WritingMinds/ffmpeg-android-java
The wrappers basically wrap an interface around there command line ffmpeg tool, which has the advantage that you can use the same syntax, and leverage the support and Q&A on the web around it.
The disadvantage is that the command line tool was not originally designed to be used this way, but if you use a well supported wrapper you will likely find a lot of the problems have been ironed out.


text:
Q: Finding force exerted on a turbine blade by water flow I am trying to find the maximum theoretical rotational power of a turbine from the following quantities:  $\omega$, $r$, $\gamma$, $I$, and $t$.
This is in an experimental setting, not an assignment, so I am not sure if I am missing any necessary quantities.
My problem: I know that $P=\tau\omega$, but I am having trouble finding torque in this scenario. More specifically, I have $r$, but I do not know how to go about finding $F$. I have $\gamma$, which is the angle between the turbine blade and the water inflow vector. I would use this once I find $F$. The only forces on the rotating bodies are water inflow and centripetal force. I did some research and found that centripetal force would be negligible in this case as the blades are rigid bodies.
I have velocity and mass flow rate, although I cannot find a formula to find impact force on a water turbine blade, $F$.
Any guidance as to how to find $F$ would be greatly appreciated.
I know that once I find the power of a single blade, I can calculate the rotational power of the turbine.


text:
Q: How to reduce EAR file size of ADF 12c Im deploying an ADF Web Application for GlassFish. (https://blogs.oracle.com/shay/entry/deploying_oracle_adf_applications_to) My application runs on Glassfish but the generated EAR is too big (100 Mbs), the application only have two jsf pages. Exploring the .war i have see that JDeveloper exports a lot of ADF Internal libraries.
Do you know if is it possible to reduce this size of the EAR?
Thanks
Alex

A: If you are using ADF you need the ADF libraries - that's why your EAR is big.
It however won't grow at the same rate if you add more pages etc.
On WebLogic we use shared libraries for all the ADF libraries - which results in smaller EAR files.


text:
Q: Download mongodb compass and Install Using the Terminal I follow the commands based on this link
    https://docs.mongodb.com/compass/master/install/
1. Download the package:
mongodb-compass_1.15.1_amd64.deb

2. Install Compass:
sudo dpkg -i mongodb-compass_1.15.1_amd64.deb;

(Reading database ... 195489 files and directories currently installed.)
Preparing to unpack mongodb-compass_1.15.1_amd64.deb ...
Unpacking mongodb-compass (1.15.1-1) ...
dpkg: dependency problems prevent configuration of mongodb-compass:
 mongodb-compass depends on libgconf-2-4; however:
  Package libgconf-2-4 is not installed.

dpkg: error processing package mongodb-compass (--install):
 dependency problems - leaving unconfigured
Processing triggers for desktop-file-utils (0.23-1ubuntu3.18.04.2) ...
Processing triggers for gnome-menus (3.13.3-11ubuntu1.1) ...
Processing triggers for mime-support (3.60ubuntu1) ...
Errors were encountered while processing:
 mongodb-compass

"How to fix 'Installation' error in Ubuntu" can anyone help my problem?

A: Use sudo apt install -f and then sudo dpkg -i <your file.deb>

A: If you check you log you will see this error:

dpkg: dependency problems prevent configuration of mongodb-compass:
mongodb-compass depends on libgconf-2-4; however:   Package
libgconf-2-4 is not installed.

So install libgconf-2-4.
apt-get install libgconf-2-4

A: In case there are multiple missing packages
sudo apt install ...
will be tedious. After running
sudo dpkg -i <package-name>
and getting dependency problems error you can run
sudo apt --fix-broken install
which will install all missing dependencies and after that running
sudo dpkg -i <package-name>
will install your needed package.

A: Run the following commands:-
sudo apt --fix-broken install
sudo apt-get install libgconf-2-4
sudo dpkg -i <<your deb package name .deb>>

A: *

*First of all, you need to fix broken installs by running the flowing command
sudo apt --fix-broken install

*After that, install libgconf-2-4
sudo apt-get install libgconf-2-4

*then install your .deb package with the following command
sudo dpkg -i <<package_file.deb>>


text:
Q: jsonwebtoken not decoding jwt in nodejs express I am generating a JWT using IdentityServer4. This is being sent to a SPA using angular. The SPA can decode the token and get the claims e.g. Role.
const tokenPayload = jwt_decode(token);
return tokenPayload.role === expectedRole;

That same token is being sent to an API in NodeJS. I tried to decode the JWT using jsonwebtoken but I cannot get it to decode it.
const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
console.log('Reading token: ' + token);
const decoded = jwt.verify(token, 'supersecret',
{
    typ:"JWT",
    algorithms: ["RS256"],
    issuer: 'http://localhost:5500',
audience: 'adApi' }
        );
    console.log('Decoded token: ' + decoded);

I keep getting errors:
"Error: error:0906D06C:PEM routines:PEM_read_bio:no start line"
I understand the documentation says I should be using a PEM file instead of 'supersecret'.
Question: Why is it that "jwt_decode" can decode the token so easily? How do I generate the PEM file.
This is the configuration info I am using. Let me remind you that this is ASPNET Core Identity using IdentityServer4.
using IdentityServer4;
using IdentityServer4.Models;
using System.Collections.Generic;

namespace XYZ.Identity
{
    public class IdentityServerConfig
    {
        // scopes define the resources in your system
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new[]
                        {
                            new ApiResource
                            {
                                Name = "adApi",
                                DisplayName = "adApi Resource",
                                Description = "XYZ Admin API",
                                ApiSecrets = { new Secret("supersecret".Sha256()) },
                                Scopes = { new Scope("adApi") },
                                UserClaims = {
                                    "name", "role"
                                }
                            }
                        };

        }

        public static IEnumerable<Client> GetClients()
        {
            // client credentials client
            return new List<Client>
            {
                new Client
                {
                    ClientId = "apiclientid",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    ClientSecrets =
                    {
                        new Secret("supersecret".Sha256())
                    },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "adApi"
                    }
                }
            };
        }
    }
}

Thank you in advance!

A: jwt_decode just decodes the token without verifying the signature.  There is no need to verify signatures in the frontend, since you never have anything secret there without the backend already verifying authorization.
To try out a signed token with a symmetric signature secret, you need to change the algorithm from RS256 to a symmetric one, like HS256 (for verify you can add it to the array of allowed algorithms).

A: Ok. I was able to understand what happened.

*

*In the IdentityServer4 implementation for ASP.NET Core there is an "implicit" RSA key/cert being created. The AddDeveloperSigningCredential() in the following code causes the tempkey.rsa file to be created.
services.AddIdentityServer()
.AddDeveloperSigningCredential()
//.AddSigningCredential(new X509Certificate2(Path.Combine(".", "certs", "IdentityServer4Auth.pfx")))
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
.AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
.AddInMemoryClients(IdentityServerConfig.GetClients())
.AddAspNetIdentity();
This file is used by IdentityServer4 to sign the tokens.

*In order to verify the token, that is to check if the token has not been tampered with, you need the public key to be generated. For that, you can open the rsa file which is in JSON format and using this tool you can generate the PEM content which is the public key.

*I saved the file in my NodeJS server and used the following code to verify and then decode.
const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
console.log('Reading token: ' + token + "==");
// verify a token asymmetric
var cert = fs.readFileSync('public-key.pem');  // get public key
jwt.verify(token, cert, function(err, decoded) {
    if(err)
        //Error logic
    //verify token expire date
    console.log(decoded) // bar
});
var decoded = jwt.decode(token);
var userId = decoded.name;
The trick was to understand that the RSA file was being generated and the the pulic key gad to be generated separately. This might be obvious once you've done it but for new people in the certificates world it might be that obvious.

A: According to the answer above, I did the experiment, and I couldn't reply directly to the above answer, because I was not enough, so I had to reply directly.
I write code according to the identityserver4 demo example, the use of.AddDeveloperSigningCredential (), so I see tempkey.rsa in the identityserver4 server project, I use Notepad to open, and copy the Modulus data, and then use the https:// superdry.apphb.com/tools/online-rsa-key-converter tool to generate the PEM file, then I use the following code in express middleware. PEM file, I just generated PEM files. Then I successfully verified the token issued by identityserver4
Var cert = fs.readFileSync ('demo2.pem');
Jwt.verify (token, Cert, function (err, decoded) {
If (ERR) {
Console.log (ERR);
}else{
Console.log (decoded);
//Error logic //verify token expire date} console.log (decoded / bar)
});

But there are a few questions here
1, we should not take the modules data to generate PEM, and then copied to the nodejs project, because it is not the best solution, if we modify the idrv4 server key, we must rebuild the PEM file, and then copied to the server corresponding to the nodejs, it was stupid. I checked some information, you can see the secret key encryption to http://localhost:5000/.well-known/openid-configuration/jwks through this address, but there is a huge bug, that I see in the browser open the contents of the above are as follows
{
Keys: [
{
Kty: "RSA",
Use: "sig",
Kid: "4df1e1f19d477d97efeffe3548418c60",
E: "AQAB",
N: "**XXXX**",
Alg: "RS256"
}
]
}

But the modules data in the tempkey.rsa file I opened with my notepad was
XXXX==
Because in fact the data of modules should be the same as the data shown on the above n, but through
 access to N data, even than the data inside modules, less == the 2 character, when I was in front of PEM documents generated by this thing to pit miserable.
2, so we still need to get nodejs's API to start up, get the key inside http://localhost:5000/.well-known/openid-configuration/jwks, and then generate PEM files to verify token signature. But to pay attention to the absence of government. But if your idrv4 uses other encryption methods, such as x509 and so on, the key will not be the value of n. It may be something else. I haven't studied it clearly yet.
and last i found npm package jwk-to-pem
you can get keys from http://localhost:5000/.well-known/openid-configuration/jwks
var jwt = require('jsonwebtoken');
var fs = require('file-system');
var jwkToPem = require('jwk-to-pem');

var pem = jwkToPem(jwk);
console.log(pem);

// verify a token asymmetric
jwt.verify(token, pem, function(err, decoded) {
    if(err){
        console.log(err);
    }else{
        console.log(decoded);
    } //Error logic //verify token expire date console.log(decoded) // bar
});


text:
Q: regex for files of a particular file extension that exclude one particular word I want to exclude file paths that have capsize anywhere in the path in node or javascript but I am failing to get the syntax right.

const re = /.*((?!capsize).*)\.css\.ts/;

console.log(re.test('src/packages/graph.css.ts')) // should be true

console.log(re.test('packages/vanilla-extract/capsize.css.ts')) // should be false

A: First you need to specify, that you want to match whole string, ie. add start and end mark. (Otherwise it will skip .* as no symbol were matched, which is ok from regex point of view)
Second you need to put not follow by right after any symbol (ie. saying, there can be 0 to infinity symbols not followed by capsize).

const re = /^(.(?!capsize))*\.css\.ts$/;

console.log(re.test('src/packages/graph.css.ts')) // should be true

console.log(re.test('packages/vanilla-extract/capsize.css.ts')) // should be false

A: One possible way:

const re = /^(?!.*?capsize).*\.css\.ts$/;

console.log(re.test('src/packages/graph.css.ts')) // should be true

console.log(re.test('packages/vanilla-extract/capsize.css.ts'))


text:
Q: Seting up vnc on mac through RPI ssh I'm currently away from home, and I would like to access my iMac which is turned on in my place. I set up the mac screen sharing before I leave, but something went wrong, and I can't access it from my MacBook.
My home network is accessible via ssh on a Raspberry Pi. I would like to know, if there is any way to access my iMac and set up a ftp or vnc server on this one via the RPI.
For example, is there any linux software that could allow me to acces another client on the same network via VNC. If it's possible, then I could try to access the RPI from my current place.
EDIT: After @baf comment, here are all my open ports on the iMac:
PORT      STATE    SERVICE
3/tcp     filtered compressnet
22/tcp    open     ssh
88/tcp    open     kerberos-sec
222/tcp   filtered rsh-spx
513/tcp   filtered login
898/tcp   filtered sun-manageconsole
1055/tcp  filtered ansyslmd
1083/tcp  filtered ansoft-lm-1
1455/tcp  filtered esl-lm
2725/tcp  filtered msolap-ptp2
3370/tcp  filtered satvid-datalnk
3801/tcp  filtered ibm-mgr
5900/tcp  open     vnc
8873/tcp  filtered dxspider
9001/tcp  filtered tor-orport
9110/tcp  filtered unknown
10628/tcp filtered unknown
13782/tcp filtered netbackup
20221/tcp filtered unknown
31038/tcp filtered unknown
32772/tcp filtered sometimes-rpc7
32776/tcp filtered sometimes-rpc15
40911/tcp filtered unknown
44176/tcp filtered unknown

EDIT: After baf answer, I update what I currently did:
I execute that command: ssh -L 5999:192.168.1.10:5900 pi_host_over_internet  So if I understand correctly the VNC port from my iMac is accessible throught the port 5999 from my Pi. Now to connect to it from my current location, I need to connect with a VNC client to 'pi_host_over_internet:5999'. I try this, but obviously, it doesn't work because the port 5999 isn't forwarded to the Pi on his router.
EDIT: Clarifying my setup:
What I have right now, where I am (UK):
MacBook connected to a public WiFi

What I have in my home (France):
Imac, local ip:`192.169.1.10`, port 5900 listenin to VNC, port 22 listening to SSH
RPI, local ip:`192.168.1.12`, port 22 listening to SSH
router accessible at `mydomain.com`, port 22 forwarded to RPI@`192,168.1.12:22`

EDIT: Here is what I get after @baf answer:

I would take any suggestion, so feel free to propose anything.

A: On you local machine (outside your network) you should run ssh client with following parameters:
ssh -L 5999:imac_host:5900 pi_host

I chose 5999 for local port but it could be any port. You only have to make sure it is not used by any local service. Substitute imac_host and pi_host with ip addresses.
When you successfully connect with given command, vnc port 5900 from imac_host will be forwarded to your local machine port 5999.
Next you need to configure your vnc client on your local machine to connect to localhost at port 5999 (connect to itself at given port).
How it works
VNC server on you iMac is listening on port 5900 for incoming connections. VNC clients may connect to this port from other machines in your local network. As you don't have direct access to port 5900 on your iMac, you are using ssh to tunnel the connection from your computer over Internet through the router to iMac in your local network.
ssh opens port 5999 (could be any other port) on your current machine and listens on this port for connections. When you connect to this port ssh tunnels the connection (through ssh port 22) to your router and from the router establishes connection to iMac on port 5900. It is called port forwarding.

Your iMac also has ssh enabled. If you don't need vnc, but only want to copy a file, it should be possible to use scp. To make it simple you could try without any port forwarding. Just copy file from imac_host to pi_host. From Pi console run:
scp username@imac_host:path_to_file destination_file`

This will copy path_to_file file to destination_file in your current folder on Pi. Then you can repeat this step and copy file from Pi to your local machine.


text:
Q: Is it possible to create HA cluster on MacOS Catalina? I couldn't find a documentation on configuring HA on Mac OS (Catalina). There's an application called Mac OS Server but the documentation doesn't talk anything about HA rather it looks to be an application to manage multiple devices.
I'm planning to create a HA cluster between two MacPro (2013) loaded on a Sonnet RackMac Pro. After a long search I reached http://preserve.mactech.com/articles/mactech/Vol.23/23.03/OSXFailover-Part1/index.html however it is a writing back from 2006 which I believe was when there were Server OS from Apple.
The question I have here is, Can I create an HA anymore on newer versions of MacOS ? If Yes, is it necessary to configure thunderbolt port to setup HA as per this documentation as discussed in the above link (though that was written before MacPro-2013 was released) or I can just depend over ethernet adapters on both MacPro to complete the project.


text:
Q: Building a structure out of cubes one block at a time I have simplified code in which the motion of a point charge is simulated N times (one particle at a time) in a static electric field. When the point charge comes to rest (using WhenEvent boundary conditions), a Cube is set up at that location. However, I have designed this code such that when the cube is created at the resting position, a BoundaryMeshRegion structure is set up, and becomes a part of the boundary condition for the next simulated point charge. Doing so would allow you to, for instance, build a tower of blocks, one block at a time (if the starting point of the particle in each simulation is r, as seen in this image:

A problem arises sometimes when running the simulation. For example, when trying to make a 5 cube tower an error like this thrown:
NDSolve::nbnum1: The function value {0.700116,0.705879,-0.895985}\[Element]BoundaryMeshRegion[BooleanRegion[#1||#2||#3||#4||#5&,{Cube[{-5,-5,-5},0.03],Cube[{0.484458,0.482154,-0.115},0.03],Cube[{0.487374,0.491032,-0.130001},0.03],Cube[{0.487829,0.490812,-0.145002},0.03],Cube[{0.493027,0.497869,-0.160003},0.03]}]] is not True or False when the arguments are {0.,0.700116,-0.0000380001,0.705879,-0.0000183699,-0.895985,-0.0000352221,-0.0000380001,-524.417,-0.0000183699,<<3>>}.

and the blocks stop stacking properly. Strangely, I have watched this code work for 15 cubes and sometimes more. But it always seems to fail at 5 cubes, beyond 15 What can be done to eliminate this error, such that any number of cubes could be stacked (within bounds of the starting point of the simulation, obviously)?
Here is the code:
Clear["Global`*"];
Needs["NDSolve`FEM`"];

q = 1.617733*10^-18;
r = BoundaryMeshRegion[
   RegionDifference[Cuboid[{-4, -4, -6.5}, {4, 4, 0}],
    Cuboid[{-4, -4, -0.1}, {4, 4, 0}]]];
pol = -1;

V0 = 5000;

(*build electric field*)
{U, {Fx, Fy, Fz}} =
  NDSolveValue[{Laplacian[V[x, y, z], {x, y, z}] == 0,
    DirichletCondition[
     V[x, y, z] ==
      pol*V0/2, (-0.1 <= z <= 0) && (-1 <= y <= 1) && (-1 <= x <= 1)],
     DirichletCondition[
     V[x, y, z] ==
      0, (-6.5 <= z <= -6.4) && (-4 <= y <= 4) && (-4 <= x <=
        4)]}, {V, -Grad[V[x, y, z], {x, y, z}]}, {x, y, z} \[Element]
    r];

(*Visualization of vector field*)
v = Show[
  VectorPlot3D[{Fx, Fy, Fz}, {x, -4, 4}, {y, -4, 4}, {z, -6.5, 0},
   PlotTheme -> "Detailed", ColorFunction -> "Rainbow",
   PerformanceGoal -> "Quality", VectorScale -> 0.05,
   VectorPoints -> 7, PlotLegends -> Automatic],
  RegionPlot3D[r, PlotStyle -> Opacity[0.1]]]

mass = 6.52*10^-11;(*particle mass*)
SeedRandom[1234];
n = 2; (*number of simulations/cube number*)
X0 = Take[RandomReal[{0.7, .71}, 2 n], n]; Y0 =
 Take[RandomReal[{0.7, .71}, 2 n], -n]; Z0 =
 RandomReal[{-.9, -0.89}, n];
rrv = RandomReal[{-0.0001, 0.0001}, 3 n];
u0 = Take[rrv, n]; v0 = Take[rrv, {n + 1, 2 n}];
w0 = Take[rrv, -n];

cubeTable = {Cube[{-5, -5, -5}, 0.03]};(*seed for cubeTable append*)
output = {};

(*Setup equations of motion and boundary conditions*)
SymplecticLeapfrog = {"SymplecticPartitionedRungeKutta",
  "DifferenceOrder" -> 2, "PositionVariables" :> qvars}; time = {t, 0,
   2}; tm = 10*10^3; partRad = 0.02; qvars = {X[t], Y[t], Z[t]};
eqn[i_] := {X''[t] == q/mass tm^2 Fx /. {x -> X[t], y -> Y[t],
     z -> Z[t]},
   Y''[t] == q/mass tm^2 Fy /. {x -> X[t], y -> Y[t], z -> Z[t]},
   Z''[t] == (q/mass tm^2 Fz + 0.000002) /. {x -> X[t], y -> Y[t],
     z -> Z[t]}, X[0] == X0[[i]], Y[0] == Y0[[i]], Z[0] == Z0[[i]],
   X'[0] == u0[[i]], Y'[0] == v0[[i]], Z'[0] == w0[[i]],
   WhenEvent[Z[t] >= -0.115, end = t; "StopIntegration"],
   WhenEvent[{X[t], Y[t], Z[t]} \[Element] cubicMesh // Evaluate,
    end = t; "StopIntegration"]};

h = 10^-4;

(*simulate the motion one cube at a time and build tower*)
Do[

 cubicMesh = BoundaryMeshRegion[RegionUnion[cubeTable]];

 soln[i] =
  NDSolve[eqn[i], qvars, time, StartingStepSize -> h,
   Method -> SymplecticLeapfrog];
 T[i] = end;

 AppendTo[output, qvars /. soln[i][[1]] /. t -> T[i]];
 cubesMade = Cube[#, 0.03] & @output[[i]];
 AppendTo[cubeTable, cubesMade];

 , {i, 1, n}]

(*show output*)
Show[Region[RegionUnion[cubeTable]], Graphics3D[{EdgeForm[None], r}],
 Background -> LightGray, Boxed -> False,
 PlotRange -> {{0, 1}, {0, 1}, {-1, 0}}]


text:
Q: Probability for getting -1 in a game of rolling die In a game, a fair die is rolled. If the result is 1 or 2, you can get 2 points. If the result is 3 or 4, you get -1 points. If the result is 5 or 6, you get 0 points. Now you can roll the die for 6 times, what is the probability that your final score is -1. The answer provided is $\frac {22}{243}$.
I can only think of 2 possible situations, which are getting 3/4 once and 5/6 for the rest, and getting 1/2 once, three 3/4 and two 5/6, so that the final score is -1. But my answer is wrong.

A: There are $3$ values that can come up on each roll so there are $3^6 = 729$ total rolls you can get.
How many ways are there to get $-1$?
You can have one $-1$ and the rest $0$. Since the $-1$ can occur on any of the six rolls there are $6$ ways to get that.
If you have two $-1$s it is impossible to get a final score of $-1$ because there is no way to get $1$.
If you have three $-1$s you can get a score of $-1$ by rolling a $2$ on another roll and $0$ on the rest. Thus there are $6\choose 3$ ways to roll the $-1$s and for each of those there are $3$ ways to roll the $2$ for a total of $6\choose 3$ $*$ $3=60$ ways to get three $-1$s.
If you roll $4, 5$ or $6$ negative $1$s there is no way to get a final score of $-1$.
Therefore, there are $66$ ways to get $-1$ and the probability is $\frac{66}{729}=\frac{22}{243}$.

A:
Hint: $−1=0−1=1−2=2−3$  –  stochasticboy321

Let $\vec X=(x,y,z)$ mean the event of: $x$ "-1", y "0", and $z$ "+1" from the roll of the dice.
This is a multinomial distribution; which is analogous to a binomial distribution: $$\mathsf P(\vec X=(x,y,z))=\binom{6}{x,y,z}{(\frac 1 3)}^6$$
You want to measure $\mathsf P(\vec X\in\{(1,5,0),(2,3,1),(3,1,2)\})$ , the probability of obtaining one more -1 die than +1 die.


text:
Q: Access data from Model in Controller? I have a model for displaying a list of latest articles, and I would like to be able to define how many articles are displayed. I have created a property called DisplayNumberOfPressArticles and I would like to be able to access the value of this property from my controller.
Here is the model:
using Site.Helpers.Selections;
using Site.Models.Blocks.Data;
using EPiServer.DataAnnotations;
using EPiServer.Shell.ObjectEditing;
using System.ComponentModel.DataAnnotations;

namespace Site.Models.Blocks
{
    [SiteContentType(GUID = "884202C2-61F1-4DF5-85A7-DC3D4E493F59")]
    [SiteImageUrl]
    public class LastArticlesTeaserBlock : SiteBlockData, PressOverviewData, ISpaceableData
    {
        [CultureSpecific]
        public virtual string Heading { get; set; }

        [Range(1, 1000)]
        public virtual int DisplayNumberOfPressArticles { get; set; }

    }
}

In my controller, I would like to take the value of DisplayNumberOfPressArticles as a limit for the .Take() query:
using System;
using System.Collections.Generic;
using Site.Models.Blocks;
using EPiServer.Web.Mvc;
using System.Web.Mvc;
using Site.Models.Pages;
using Site.Models.ViewModels;
using EPiServer.Find;
using EPiServer.Find.Api;
using EPiServer.Find.Cms;
using EPiServer.Find.Framework;
using EPiServer.Logging;
using ILogger = EPiServer.Logging.ILogger;
using EPiServer.Globalization;

namespace Site.Controllers
{
    public class LastArticlesTeaserBlockController : BlockController<LastArticlesTeaserBlock>
    {
        private static readonly ILogger Logger = LogManager.GetLogger();
        public override ActionResult Index(LastArticlesTeaserBlock currentContent)
        {
            var model = new LastArticlesTeaserViewModel
            {
                Headline = currentContent.Heading,
                ArticlePages = GetArticlePages(),
                PaddingTop = currentContent.PaddingTop,
                PaddingBottom = currentContent.PaddingBottom
            };

            return PartialView(model);
        }

        private List<PressDetailsPage> GetArticlePages()
        {
            List<PressDetailsPage> result = new List<PressDetailsPage>();

            IClient findClient = SearchClient.Instance;
            var search = findClient.Search<PressDetailsPage>();

            search = search
                .Filter(sp => sp.IsDeleted.Match(false)).PublishedInCurrentLanguage()
                .Filter(sp => sp.Headline.Exists() | sp.Description.Exists())
                .Filter(sp => sp.Language.Name.Match(ContentLanguage.PreferredCulture.Name))
                .OrderByDescending(sp => sp.PublishDate, SortMissing.Last)
                .Take(??);

            try
            {
                var searchResult = search.GetContentResult();

                result.AddRange(searchResult);
            }
            catch (NullReferenceException e)
            {
                Logger.Error(e.ToString());
            }

            return result;

        }
    }
}

Sorry for the newbie question, but everything I have tried hasn't worked so far. I thought I could access the model by using .Take(LastArticlesTeaserBlock.DisplayNumberOfPressArticles);

A: How about changing your signature to something like GetArticlePages(int maxCount) and then invoking it like ArticlePages = GetArticlePages(currentContent.DisplayNumberOfPressArticles) in your Index method?

A: Your SearchClient class looks like a custom implementation and hard to tell if the bug is there.
Option 1:
Something like -- db.ArticleSet.OrderByDescending(t => t.Articles.Count).Take(10);

Option 2:
Or a more direct query.
Make life easier and break it down in two parts firs the query, they execution, then put it back together if you want.
Step 1
var articlesQuery = from x in Articles..
                  where x.IsDeleted == true ....

Step 2
var limitedArticlesQuery  = articlesQuery.Take(25);

From client size send a int pageSize
var pagedProductQuery = articlesQuery.Skip(10 * pageSize).Take(10)


text:
Q: Requests for touch icons from android Does anyone know the logical flow and timing behind requests for apple-touch-icon.png by android apps that use an embedded webkit browser?
What I seem to be seeing (but am having trouble verifying) is that a GET request for the touch icon is made before the webpage itself. Perhaps this is by design so that users get some kind of feedback the page is loading before the bulky webpage is downloaded.
It's causing problems because my company has launched an application that sits behind a single sign-on solution - the SSO intercepts the first get request to the server and returns a login page instead. After the user's logged in, they are then redirected to the URL of the intercepted request.
What seems to be happening on android is that users are logging in, then getting redirected to the /apple-touch-icon.png instead of the page they were expecting...


text:
Q: where are the log files saved in axis2 webservice i have put log4j.properties file into WEB-INF/classes folder in my axis 2 webservice. now i can see logs been printed on console. but i have also put file appender. but i can not find the log file anywhere. could someone help me to find a solution for this problem.

log4j.rootLogger=DEBUG, CA, FA
  #Console Appender log4j.appender.CA=org.apache.log4j.ConsoleAppender
  log4j.appender.CA.layout=org.apache.log4j.PatternLayout
  log4j.appender.CA.layout.ConversionPattern=%-4r
  [%t] %-5p %c %x - %m%n
  #File Appender log4j.appender.FA=org.apache.log4j.FileAppender
  log4j.appender.FA.File=ws.log
  log4j.appender.FA.layout=org.apache.log4j.PatternLayout
  log4j.appender.FA.layout.ConversionPattern=%-4r
  [%t] %-5p %c %x - %m%n
  # Set the logger level of File Appender to WARN
  log4j.appender.FA.Threshold = WARN


text:
Q: Doctrine SQL/table generation failing I am trying to make Doctrine generate SQL from a set of models that I created earlier with a YAML schema. Using the code below which comes from the manual the output should be a set of queries.
<?php
// test.php
require_once('bootstrap.php');

try
{
    $models = Doctrine_Core::generateSqlFromModels('models/generated');

    echo '
';
    var_dump($models);
    echo '
';
}
catch(Exception $e)
{
    echo $e->getMessage();
}

However, the result of this code is:
NULL

while it should return a string with the SQL queries, as said before.
I've also tried the following:
<?php
// test.php
require_once('bootstrap.php');

try {
    $result = Doctrine_Core::createTablesFromModels('models/generated');

    echo '
';
    var_dump($result);
    echo '
';
}
catch(Exception $e)
{
    echo $e->getMessage();
}

but that also returns:
NULL

I was not able to find the solution in the manual, the API reference or in the Doctrine core files. I hope someone here knows.
Thanks in advance.
Update: It can not be because of this (old?) bug, because I have no table name that starts with A or B.
Update: My bootstrap.php looks like this:

/**
 * Bootstrap Doctrine.php, register autoloader specify
 * configuration attributes and load models.
 */

require_once(dirname(__FILE__) . '/lib/vendor/doctrine/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('pgsql://user:pass@localhost/dbname', 'doctrine');

$manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL);
$manager->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL);
$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);

Update: I've changed the line:
$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);

to:
$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_AGGRESSIVE);

but the output of
print_r(Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels('models/generated')))

is still an empty array.

A: The problem was that the generated model names were like this:
<?php
abstract class BaseClass extends Doctrine_Record
{

}

Removing the abstract keyword did the trick. All the other Doctrine models are not using the abstract keyword, so it won't do any harm to remove it.


text:
Q: Android editor Studio, My app needs to be able to use Charles proxy but I am not sure how I can add a reference to the xml file? I am supposed to add the following line to the App manifest:
Then add a reference to this file in your app's manifest, as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config" ... >
        ...
    </application>
</manifest>

However whenever I am trying to add this the 'Packing App' seems to come back with this:
AndroidManifest.xml:277: error: unexpected element  found in .


text:
Q: EarPods are louder when put backwards into my ear My EarPods (wired EarPods) broke recently.
Now if I put them in normally I can barely hear them, even at max volume.
If I cup my ears with my hands (with the EarPods in my ears in a normal position) then it's very loud again.
If I put the backs of the EarPods into my ears then it's loud, or upside down is also louder than the normal orientation.
Every other pair of EarPods I've tested work fine, it seems to be a problem with this specific pair.
How can I fix this problem?
I assume the speakers have twisted inside of them (maybe not), is there a way I can safely and reversibly open the EarPods to put it back the right way round?

A: Referring to the iFixit's Apple EarPods Teardown, it appears that it would be pretty hard to open up the ear drums, put the speakers right way round and assemble them back correctly.

With such a tight fit between the two halves of the EarPods, simply pulling them apart wasn't an option. We knew what we needed to do.

This isn't something you'd want to try at home. Once these Pods are open, they're not closing back up unless you want to involve glue.

Additionally, they are not rated well on serviceability or reparability front.

But unfortunately, these products are still of the throw-away kind. Sourcing parts is next to impossible, and it would be a tough sell to convince someone to take apart their earbuds instead of buying a new pair. They will never be the same once taken apart.

If you still have the original warranty for the iPhone with which the EarPods were bundled, you can try getting a replacement.


text:
Q: SiteFinity 7.1 custom content items and grouping We have a list of faculty and units for a SiteFinity 7.1  site. We have these as custom content items in the site, because we are programming against them and building a few widgets around them.
However, we also have news about these faculty and units, and we'd like to use the existing news items in SiteFinity.
How do we easily tie faculty and units (custom content items) to news items (another content item baked into SiteFinity)? I wasn't sure if we create classifications that list faculty and units, and use these as the grouping mechanism? Or is there an easy way to tie two content items together?

A: It kind of depends on how you're going to (or how you want to) display the data at the end. Here are a couple of different ways to achieve what you're after.
You're planning on using the stock News widget to display the content.
If this is true, using a custom taxonomy would be pretty easy in this case. Here's a video that outlines this method.
You're planning on displaying the news items in close proximity to one of the custom content types you've created.
In this case, adding a related data field to the custom type would allow you use related content items with widget templates.


text:
Q: Python mean value for each row grouped by a column I have a column A and a column B. In column Result I would like to calculate the mean of column B grouped by column A (which means I would like to calculate what I wrote into the column Result).
cor = pd.DataFrame({'A' : [100, 100, 100, 200, 200, 300, 300, 300, 300],
                    'B' : [10, np.NaN, 20, np.NaN, 50, 10, 40, 60, 80],
                   'Result': [15, 15, 15, 50, 50, 47.5, 47.5, 47.5, 47.5]})
print(cor)
values = cor.groupby('A').mean()

In my dataset I have about 200k rows of data, so the function should be quite powerfull.

A: This should work:
import pandas as pd
import numpy as np
cor = pd.DataFrame({'A' : [100, 100, 100, 200, 200, 300, 300, 300, 300],
                    'B' : [10, np.NaN, 20, np.NaN, 50, 10, 40, 60, 80]})
print(cor)
values = cor.groupby('A').mean().reset_index()
print(values)
df = cor.merge(values,how='left',left_on=['A'],right_on=['A'])
df = df.rename(columns={"B_x":"B","B_y":"Result"})
print(df)

Output:
    A     B  Result
0  100  10.0    15.0
1  100   NaN    15.0
2  100  20.0    15.0
3  200   NaN    50.0
4  200  50.0    50.0
5  300  10.0    47.5
6  300  40.0    47.5
7  300  60.0    47.5
8  300  80.0    47.5


text:
Q: Delete a commit in gitlab I pushed a commit to our central repo.  Let's call it commit AAAA.  Then I realized I wasn't quite satisfied with it.  I want to get it out of the repo.  I have no command line access to the central repo, just the gitlab GUI.  I found a question on this site where someone was talking about using the "revert" option in the gitlab GUI.  I tried it.  It actually created a new commit that just undid the changes in commit AAAA.  Let's call this one BBBB.  This is not what I need.  I just simply need AAAA gone, and, of course, BBBB along with it.  Is there some way to do this in the gitlab GUI?  As long as these new commits are there, git thinks my local repo is behind the central repo and I can't do any more pushing.
P.S. Trying to force a reset.
> git reset --hard HEAD~1
> git push -f origin

But I am told, "You are not allowed to force push code to a protected branch on this project."  And I look and, yes, the master branch is protected.  I have permissions to set the protection status, if I only knew how to do it.  Anyone know how?  This would solve my problem, it seems.  And if anyone has any info on my first question, I would still be grateful to hear it.

A: Your only option is force push if you want to remove commits from the git history. You cannot delete commits in the GUI or take other actions that would require a force push.

It actually created a new commit that just undid the changes in commit AAAA

That's probably the behavior you want in most cases, especially for protected branches like main/master. If you rewrite the history of that branch, you will create bigger problems for other users who already cloned those would-be-deleted commits. That's partly why repository owners configure protected branch rules to begin with -- to prevent you from doing exactly that.
If you decide you really want to remove those commits from the protected branch, you must remove the protected branch rule that prevents force pushing, remove the commits locally, then force push to the repo. You must have the maintainer role or higher on the project in order to do this.


text:
Q: iPhone Facebook SDK Login Problem Hey guys
I just tried to implement the facebook sdk like in the DemoApp from Facebook itself into my application. I basically copied everything from the demoApp but I have a problem when I try to login to facebook.
I press the login button and then the facebook app opens. I authorize myself and press OK. Then I am redirected to my app, but then the fbDidLogin() method gets not called. I also defined my app ID in my view controller and the url schema in the info file.
Am I missing something?
Thanks,
Cheers,
Doonot

A: fbDidLogin() isn't an Objective C method.  Is that the way you have it in the code?
Have you handled your custom URL scheme in your app delegate?

A: Ok after some trying I figured it out. I used the Interface Builder to set up my Tab Bar Application. I had to change the tab bar application to programmatically in order to have a reference to the view controller which implements the facebook login method:
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        settingsController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
 ...

As Jim mentioned, I forgot to implement the custom url scheme in my app delegate. Thanks to the settingsViewController I simply added:
// this method is needed by the facebook login procedure
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[settingsController facebook] handleOpenURL:url];
}

That's it, after these changes I can finally login to facebook.
Cheers,
Doonot


text:
Q: Terraform dynamically reference data objects I am reaching out to see if anyone has come across the need to try and do the following in Terraform.
data.aws_iam_policy_document.${var}.json

Basically creating a bunch of IAM policy documents with data. After which, I want to loop over a module call with for_each and use the key to reference the data object and send the json property of the said object as a var to the module.
Psuedo code:
module "example" {
  source = "../example"
  for_each = var.default_endpoints
  policy = lookup(lookup(data.aws_iam_policy_document, var.default_endpoints[each.key].name), "json", null)
}


text:
Q: ORA-28595: Extproc agent : Invalid DLL Path I'm trying to create a table with spatial column in oracle and insert data into it. I'm using ArcSDE and Oracle. The version of Oracle is 11.2.0, the version of ArcSDE is 10.0.
My create statement is:
CREATE TABLE sensitive_areas (area_id integer, name varchar(128),
area_size float, type varchar(10), zone sde.st_geometry);

And insert statement is:
INSERT INTO SENSITIVE_AREAS (area_id, name, area_size, type, zone)
VALUES (1, 'Summerhill Elementary School', 67920.64, 'school', sde.ST_PolyFromText('polygon ((52 28,58 28,58 23,52 23,52 28))', 0));

I've already added st_shaplib.dll and libst_raster_ora.dll to the environment variable EXTPROC_DLLS.
My tnsname.ora:
    LISTENER_ORCL =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

My listener.ora:
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = D:\app\rainman\product\11.2.0\dbhome_3)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:D:\app\rainman\product\11.2.0\dbhome_3\bin\oraclr11.dll;D:\Program Files\ArcGIS\ArcSDE\ora11gexe\bin\st_shapelib.dll;D:\Program Files\ArcGIS\ArcSDE\ora11gexe\bin\libst_raster_ora.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

ADR_BASE_LISTENER = D:\app\rainman

However, I got this error: ORA-28595: Extproc agent : Invalid DLL Path. What should I do?
Thanks
USER_LIBRARIES entry for ST_SHAPELIB is also correct:
ST_SHAPELIB D:\Program Files\ArcGIS\ArcSDE\ora11gexe\bin\st_shapelib.dll    Y   VALID

A: If you've already compiled the PUBLIC and SDE schema after setting the user library, that error message looks like you do not have the actual EXTPROC_DLLS environment variable on your Oracle server. From your settings it looks like your Oracle is on Windows.
Your listener path and user library point to your st_shapelib.dll residing in the ArcSDE home. Oracle won't access that location if the EXTPROC_DLLS environment variable is not set:
Specify the EXTPROC_DLLS environment variable to restrict the DLLs that extproc is allowed to load. **Without the EXTPROC_DLLS environment variable, extproc loads DLLs from ORACLE_HOME/lib on UNIX operating systems and ORACLE_HOME\bin on Microsoft Windows.**

Source:
Enabling Advanced Features of Oracle Net Services - Table 13-5 External Procedures Settings in listener.ora
http://docs.oracle.com/cd/E11882_01/network.112/e41945/advcfg.htm#NETAG0132
To rectify this you can move the st_shapelib.dll file into your Oracle_Home\bin and repoint your listener.ora file and Oracle SDE user library, then compile.
Alternatively, you can create the Windows system environmental variable EXTPROC_DLLS using the source provided. Restart your listener just in case after setting the variable.
Run a quick test after doing so such as:
select sde.ST_AsText(SDE.ST_Geometry('POINT (10 10)', 0)) from dual;

Here is the Esri information on EXTPROC_DLLS:
Configuring the Oracle listener to access the geodatabase with SQL(10.0)
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002n00000091000000
If that doesn't succeed, post the rest of the error message. It should be more than just one line/one Ora error.


text:
Q: Cannot connect to FTP server behind AWS loadbalancer I have configured AWS EC2 instance to be a FTP servers(Passive Mode) and attached a Load balancer target group to the instances. The loadbalancer listener port is 21. The problem I face is the my cellular device is unable to create a data connection with the FTP server the connection times out after the PASV command although the server sends the response as available from the logs. This is not seen while using a wifi connection. Everything works smoothly when using filezilla on my laptop although the when using mobile hotspot a completely new error occurs(Added Below). I have checked the cellular FTP connection without loadbalancer and it works fine.
Status: Resolving address of ftp-loadbalancer-b66f394783ab4656.elb.us-east-1.amazonaws.com
Status: Connecting to [64:ff9b::3e5:5d75]:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/"
Command:    TYPE I
Response:   200 Switching to Binary mode.
Command:    EPSV
Response:   229 Entering Extended Passive Mode (|||43735|).
Command:    LIST
Error:  Connection timed out after 20 seconds of inactivity
Error:  Failed to retrieve directory listing
Status: Disconnected from server
Status: Resolving address of ftp-loadbalancer-b66f394783ab4656.elb.us-east-1.amazonaws.com
Status: Connecting to [64:ff9b::3e5:5d75]:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/"
Command:    TYPE I
Response:   200 Switching to Binary mode.
Command:    EPSV
Response:   229 Entering Extended Passive Mode (|||42066|).
Command:    LIST
Error:  Connection timed out after 20 seconds of inactivity
Error:  Failed to retrieve directory listing

Thanks

A: I assume your office wifi has a SG (security group) rule in there allowing traffic to the port from your office IP range?
Use whatsmyip.com to find out your where you cell phone is coming from, then add the SG rule. and port.
Use nmap to see if indeed you can get to the port. I typically always use stealth scans
nmap -sS (AWS public IP you are going to)

If you have AWS firewall rules / security groups or any firewall appliances in AWS you will need to open access to the following ports: Port: 21 (Used for FTP) Port: 990 (Used for FTPS) Passive Port Range: 50000 – 51000 (Used for data transfer)
https://cloudinfrastructureservices.co.uk/how-to-setup-ftp-server-on-amazon-aws-windows-ec2-instance/#:~:text=If%20you%20have%20AWS%20firewall,51000%20(Used%20for%20data%20transfer)


text:
Q: Magento Template is not Loading I need to remove default Magento checkout and add custom one.Problem is Custom extension template is not loading.Log doesn't show any errors.I have attached screenshot http://skit.ch/nwpi
Code is here https://gist.github.com/3636029
Two questions here,
Blocks are not rendering?
Even though I've unset "checkout.onepage" block,when I dump entire layout,it shows the default checkout layout code.Is this normal behavior?

A: The problem lies in your controller:
$this->getLayout()->getBlock('content')->unsetChildren('checkout.onepage');
See:
Mage_Core_Block_Abstract

/**
 * Unset all children blocks
 *
 * @return Mage_Core_Block_Abstract
 */
public function unsetChildren()
{
    $this->_children       = array();
    $this->_sortedChildren = array();
    return $this;
}

/**
 * Unset child block
 *
 * @param  string $alias
 * @return Mage_Core_Block_Abstract
 */
public function unsetChild($alias)
{
    if (isset($this->_children[$alias])) {
        unset($this->_children[$alias]);
    }

    if (!empty($this->_sortedChildren)) {
        $key = array_search($alias, $this->_sortedChildren);
        if ($key !== false) {
            unset($this->_sortedChildren[$key]);
        }
    }

    return $this;
}

So your code should be, either:
$this->getLayout()->getBlock('checkout.onepage')->unsetChildren();
OR
$this->getLayout()->getBlock('content')->unsetChild('checkout.onepage');


text:
Q: Include records if related entities have a value using LINQ I need to list only the DME's that have values in the Carga's related entities:
Main entity:
public partial class DME
{
    public int Id { get; set; }

    public virtual IList<Carga> Cargas { get; set; }
 }

Related Entity Carga:
public class Carga
{
    public int Id { get; set; }
    public string PesoLiquido { get; set; }
    public string PesoBruto { get; set; }
    public string Volume { get; set; }
}

PesoLiquido and PesoBruto can be NULL or "0" or "10.200"
   Valor can be NULL or "0" or "10.20"
Until now I was able to get this but with errors:
IList<DME> DMEs = db.DMEs
                    .Where(d => d.Cargas.Select(c => c.PesoLiquido) != null && d.Cargas.Sum(c => c.PesoLiquido) > 0)
                    .Where(d => d.Cargas.Select(c => c.PesoBruto) != null && d.Cargas.Sum(c => c.PesoBruto) > 0)
                    .Where(d => d.Cargas.Select(c => c.Valor) != null && d.Cargas.Sum(c => c.Valor) > 0))

Error:
Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1'. Only primitive types, enumeration types and entity types are supported.

A: The problem is this part of each Where:
d.Cargas.Select(c => c.PesoLiquido) != null

You are trying to compare a collection with null, which can't be translated to SQL.
Instead, do
d.Cargas.Any(c => c.PesoLiquido != null)

Also, by your posted code each of these properties is a string, and yet you are doing a sum, which likely won't translate either. Are these columns actually strings in the database or are they numeric?
If they are numbers in the database, change type of each property to double? and do:
   .Where(d => d.Cargas.Any(c => c.PesoLiquido > 0))

If they are strings for some reason, then do:
   .Where(d => d.Cargas.Any(c => c.PesoLiquido != null && c.PesoLiquido != "0.00")


text:
Q: How to handle user authentication popup in Mobile/Tablet I am developing automation scripts using selenium webdirver, Appium for Mobile website automation.
Previously for the website I automate there is no authentication popup asked.
Now for all the lower environments authentication is asked.
So how do I handle user authentication popup.
Technologies I use are java, selenium and appium for both Android and iOS platforms.
Can anyone help me out.

A: You can get xpath/id of popup element and buttons , using these you can perform action on these buttons.
@findby(id="android/button1")
WebElement allow_button;

public void clickonAllow()
{

    allow_button.click();

}

As per requirement you can click on button "Allow" / "Deny" or "Accept" or "Reject"
In web you can try driver.switchTo().alert().accept(); or driver.switchTo().alert().deny();

A: I had similar issue just a while ago, with allowing locations.
This issue should be divided into platform specific
for iOS is bit more specific and it has code like this:
driver.findElement(By.xpath("//XCUIElementTypeAlert//XCUIElementTypeButton[@name='Allow']")).click();

(if You have for eg. 'Allow' button)
and for Android You can break them into elements, here is a code example from my code:
public class Alert implements org.openqa.selenium.Alert
    @AndroidFindBy(id = "com.android.packageinstaller:id/dialog_container")
    @WithTimeout(time = 3, unit = TimeUnit.SECONDS)
    public MobileElement alertControl;

    @AndroidFindBy(id = "com.android.packageinstaller:id/permission_message")
    @WithTimeout(time = 3, unit = TimeUnit.SECONDS)
    private MobileElement content;

    @AndroidFindBy(id = "com.android.packageinstaller:id/permission_allow_button")
    @WithTimeout(time = 3, unit = TimeUnit.SECONDS)
    private MobileElement buttonAccept;

    @AndroidFindBy(id = "com.android.packageinstaller:id/permission_deny_button")
    @WithTimeout(time = 3, unit = TimeUnit.SECONDS)
    private MobileElement buttonDismiss;

    public Alert(SessionInfo sessionInfo){
        super(sessionInfo);
        PageFactory.initElements(new AppiumFieldDecorator(sessionInfo.getMobileDriver(), 3, TimeUnit.SECONDS), this)

      WaitUtils.isElementPresent(sessionInfo.getMobileDriver(),alertControl,2);

        if (!Util.areElementsLoaded(alertControl, content, buttonAccept, buttonDismiss)) {
            setLoaded(false);
        } else {
            setLoaded(true);
        }
        Validate.isScreenLoaded(getSessionInfo(), this.isLoaded());

    }

    @Override
    public void dismiss() {
        buttonDismiss.click();
        Validate.action(getSessionInfo(), "ALERT - click button 'Dismiss'");
    }

    @Override
    public void accept() {
        buttonAccept.click();
        Validate.action(getSessionInfo(), "ALERT - click button 'Accept'");
    }

    @Override
    public String getText() {
        String value = content.getText();
        Validate.action(getSessionInfo(), "ALERT - get content");
        return value;
    }

    @Override
    public void sendKeys(String s) {

    }


text:
Q: How to update variable array names inside "for" loop and store its value for later use in python? I am trying to automate the assignment of data arrays to new names,
The folder contains multiple files of arbitrary names, each file contains two columns of data
here is the code to open those files:
import numpy as np
import os

d = {}
x = {}
y = {}
myfiles = [myfile for myfile in os.listdir() if myfile.endswith(".txt")]
print(myfiles)
ran = len(myfiles)
for myfile in myfiles:
    d[myfile] = np.loadtxt(myfile, delimiter='\t', unpack=True)
    for i in range(ran):
        x[i], y[i] = d[myfile]
        #stuff I didn't figure out
print(x1,y1)
print(x2,y2)
.
.
print(xn,yn)

the task is to store say x1 y1, to use them outside the loop. the naming scheme must also be kept x1,x2,x3...etc
The code so far saves only the last two arrays xn, yn


text:
Q: Compare installed Windows updates against defined array I would like to check if selected updates are installed on a certain computer.
This is my attempt so far:
$HotfixInstaled = Get-Hotfix | Select-Object -Property HotFixID | out-string
$HotfixRequared = @("KB4477029", "KB4486458", "KB4480959")

Compare-Object $HotfixRequared $HotfixInstaled -Property HotFixID | where {$_.sideindicator -eq "<="}

The main problem is, that Compare-Object could't find items that are in $HotfixRequared and in both variables at the same time.

A: Two problems here:

*

*The Out-String makes it hard to compare the objects since you destroy the array structure of the returned object and create a string-array with every letter being its own field. Don't do that.

*You have to use the -IncludeEqual Switch of Compare-Object and change your Where-Object query in the same manner.

This should give you all Hotfixes that are in $HotfixRequarded and in both:
$HotfixInstaled = Get-Hotfix | Select-Object -Property HotFixID
$HotfixRequared = @("KB4477029", "KB4486458", "KB4480959")

Compare-Object $HotfixRequared ($HotfixInstaled.HotFixID) -IncludeEqual| Where-Object {$_.sideindicator -eq "<=" -or $_.sideindicator -eq "=="}


text:
Q: PHP in HTML
A: In this case, they can only be "undefined", not "unset". However, they have "global" prefix, so there is a chance they are defined in some other code, possibly even outside your file.
$window->alert(...) probably outputs HTML that reads as javascript alert or a similar function.
You cannot use javascript alert() in PHP, because it is not PHP function.

A: As far as PHP is concerned, there is no JavaScript — only text.
$window and $document are just variables defined elsewhere in the PHP. $window appears to be an object with some methods that output text (text that happens to include JS syntax)  while $document appears to be a string.
They will be undefined if they haven't been defined already.
You can write any JS function you like as normal text. If you want to use an object to generate it, then you need to have an object that is aware of that function.

A: For a regular web app, the code you're showing makes no sense whatsoever, because PHP runs on the server and JavaScript runs on the client. PHP is used to build the HTML code which forms the DOM tree on which JavaScript functions like getElementById() operate, so it's completely impossible to use them meaningfully within PHP code.
However, a cursory investigation reveals that Appcelerator Titanium is a sort of runtime that is meant to run applications using web technology completely on the client. In such a runtime, it is possible that the PHP code is running in the context of an already complete HTML DOM and interacts with it via JavaScript-like bridge functions. But that's completely different from how PHP normally works.


text:
Q: Magento 2 add product to cart programmatically with custom options I have created one test script file for add product into cart with custom options. I want display selected custom option of product in cart using programmatically.
Please check my below code:
$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');
$params = array();
$params['options[469]'] = 459;
$params['qty'] = 1;
$params['product'] = 25

$cart->addProduct($product, $params);
$cart->save();

Using objectmanager i have created cart and product object. When i have fired this script in browser, it's show me error:

Magento\Framework\Exception\LocalizedException: Please specify
  product's required option(s).

I have already passed custom option in params array. but still it's show error.
How can i add product into cart with selected custom options ?
Please help me.
Any help would be appreciated.

A: I have got the solution of this problem.
Here is my updated code.
$productId = 127;
$product = $obj->create('\Magento\Catalog\Model\Product')->load($productId);

$cart = $obj->create('Magento\Checkout\Model\Cart');
$params = array();
$options = array();
$params['qty'] = 1;
$params['product'] = 127;

foreach ($product->getOptions() as $o)
{
    foreach ($o->getValues() as $value)
    {
        $options[$value['option_id']] = $value['option_type_id'];

    }
}

$params['options'] = $options;
$cart->addProduct($product, $params);
$cart->save();

This code is work for me.

A: please replace your code :
$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');
$params = array();
$params['options[469]'] = 459;
$params['qty'] = 1;
$params['product'] = 25

$cart->addProduct($product, $params);
$cart->save();

Replace with
$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');
$formKey = $objectManager->create('\Magento\Framework\Data\Form\FormKey')->getFormKey();
$option = array('469'=>459);

$params = array(
                    'form_key' => $formKey,
                    'product' => $productId, //product Id
                    'qty'   =>1, //quantity of product
                    'options' => $option
                    );
$cart->addProduct($product, $params);
$cart->save();


text:
Q: Java Reflection: Find method usage in custom AbstractProcessor I'm newbie in reflection. Is there any way to detect where is an specific method invoked? For example:
public class MyClass {

   public static void method(){
       //DO SOMETHING
   }

}

public class Test {

    public test(){
       MyClass.method();
    }

}

public class MyProcessor extends AbstractProcessor {

   public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

      Method method = MyClass.class.getDeclaredMethod("method");

      Class classWhereMethodIsInvoked = obtainClassWhereMethodIsInvoked(method);

   }

   public Class obtainClassWhereMethodIsInvoked(Method method) {
      //here I want to search one class that invoke that method, in this case Test.class
   }

}

is something like this possible or I am going crazy?

A: As mentioned in the comments, Apache BCEL is suitable for your problem. Such libraries are often particularly used for determining compile-time information such as method usage and control flow analysis from the generated bytecode, and such information are difficult, if not impossible, to retrieve using reflection. If you use the BCEL solution, you probably no longer require a custom annotation processor.
But since you already seem to be using a custom annotation processor, the whole point of it is to be able to process annotations in the source files. So one way is to define a custom annotation that marks a method being called, and have the custom processor read these annotations to know which classes call which methods:
@CallerClass("MyClass.method")
public class Test {

    public test() {
       MyClass.method();
    }

}

In the above (trivial) example, a custom CallerClass annotation marks that a class calls the method specified in the annotation's element inside parentheses. The annotation processor can read this annotation and construct the caller information.

A: Yes it doable if you really want it.  You can use the classLoader to search through the class path and scan for the method name through all the class files.  Below is a very simplistic example to show that it is doable.  In the example below I find usage of the "println" method being used in this class.  Essentially you can just broaden the scope from one file in my example to all the class files.
public class SearchClasses {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {

//      InputStream is = SearchClasses.class.getClassLoader().getResourceAsStream("resources.SearchClasses.class");
        InputStream is = new FileInputStream(new File("build/classes/resources/SearchClasses.class"));

        boolean found = false;
        Scanner scanner = new Scanner(is);
        while (scanner.hasNext()) {
            if (scanner.nextLine().contains("println")) {
                System.out.print("println found");
                found = true;
                break;
            }
        }

        if (!found) {
                System.out.print("println NOT found");
        }

    }

    public static void testMethod() {
        System.out.println("testing");
    }

}

In my IDE I had to use the FileInputStream to access the class file I was searching in.... but if you are searching through jar files then you can use the classLoader instead.  You would need mechanism to search through all of the class path... this is not impossible but I left it our for brevity.
EDIT:  Here is an attempt to get it working completely.. searches all files in class path for your method.
public class SearchClasses {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {

        printAllFileWithMethod("println");
    }

    public static void printAllFileWithMethod(String methodName) throws FileNotFoundException, IOException {
        Enumeration<URL> roots = SearchClasses.class.getClassLoader().getResources("");

        List<File> allClassFiles = new ArrayList<>();
        while (roots.hasMoreElements()) {
            File root = new File(roots.nextElement().getPath());
            allClassFiles.addAll(getFilesInDirectoryWithSuffix(root, "class"));
        }

        for (File classFile : allClassFiles) {
            InputStream is = new FileInputStream(classFile);

            boolean found = false;
            Scanner scanner = new Scanner(is);
            while (scanner.hasNext()) {
                if (scanner.nextLine().contains(methodName)) {
                    System.out.print(methodName + " found in " + classFile.getName() + "\n");
                    found = true;
                    break;
                }
            }

        }
    }

    public static void testMethod() {
        System.out.println("testing");
    }

    static List<File> getFilesInDirectoryWithSuffix(File dir, String suffix) {
        List<File> foundFiles = new ArrayList<>();
        if (!dir.isDirectory()) {
            return foundFiles;
        }
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                foundFiles.addAll(getFilesInDirectoryWithSuffix(file, suffix));
            } else {
                String name = file.getName();
                if (name.endsWith(suffix)) {
                    foundFiles.add(file);
                }
            }

        }
        return foundFiles;
    }

}

A: You could define your own mechanism. Use a Map to store the caller of each method :
public static Map<Method, List<String>> callStack = new HashMap<Method, List<String>>();

public static void registerCaller(Method m)
{
    List<String> callers = callStack.get(m);
    if (callers == null)
    {
        callers = new ArrayList<String>();
        callStack.put(m, callers);
    }

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    callers.add(stackTraceElements[3].getClassName());
}

The target class :
class MyClass
{
    public static void method()
    {
        registerCaller(new Object(){}.getClass().getEnclosingMethod());
        // DO SOMETHING
    }
}

Some caller classes :
package the.package.of;

class Test
{
    public void test()
    {
       MyClass.method();
    }
}

class Foo
{
    public void bar()
    {
       MyClass.method();
    }
}

And finally, the test :
new Test().test();
new Foo().bar();

Method method = MyClass.class.getDeclaredMethod("method");
for (String clazz : callStack.get(method))
{
    System.out.println(clazz);
}

Prints :
the.package.of.Test
the.package.of.Foo

A: Well, if you use Eclipse as an IDE, you can find the complete call hierarchy via "Open Call Hierarchy" function. This will find all usages of your method in any open Eclipse projects.
However, if you want to find out during runtime programmatically, then you need to integrate some library, that can statically analyze the bytecode of your classpath for use of your method.

A: You can obtain stack trace right inside the test method:
public class Test {

    public void test() {
        System.out.println(getCallerClass());
    }

    public static String getCallerClass()  {
        for (StackTraceElement e: Thread.currentThread().getStackTrace()) {
            if (!"java.lang.Thread".equals(e.getClassName()) && !e.getClassName().equals(Test.class.getName()))
               return e.getClassName();
        }
        return null;
    }
}


text:
Q: Get min/max values of a javascript array for array propriety I'm trying to get the min/max values of a multidimensional javascript array dependant on 2 fields.
This is timeseries data from an IoT device, it sends me data in this format:
timestamp, device id, value1, value2, value3, etc, etc
I want to write a function to get the min/max value of each device for a particular value
I have a array like this
[
    [
        1577912341,
        "ITEM1",
        131.98840369
    ],
    [
        1577998742,
        "ITEM2",
        127.27418424
    ],
    [
        1578085141,
        "ITEM2",
        133.67909395
    ],
    [
        1578171541,
        "ITEM1",
        134.82513897
    ]
]

How can I get min/max value of each unique item in field 1 using the value in field 3 ?
For example I want to know the max value of the field 3 for (ITEM1), in this example that would be "134.82513897"
min value of field 2 (ITEM1)is 131.98840369
max value of field 2 (ITEM1)is 134.82513897
min value of field 2 (ITEM2)is 127.27418424
max value of field 2 (ITEM2)is 133.67909395

A: Perhaps this can get you started.

const data = [
    [
        1577912341,
        "ITEM1",
        131.98840369
    ],
    [
        1577998742,
        "ITEM2",
        127.27418424
    ],
    [
        1578085141,
        "ITEM2",
        133.67909395
    ],
    [
        1578171541,
        "ITEM1",
        134.82513897
    ]
];
const items = [...new Set(data.map(d => d[1]))];
console.log(items);

const results = items.map(item => {
  const subset = data.filter(d => d[1] === item).map(d => d[2]);
  return {
    item: item,
    min: Math.min(...subset),
    max: Math.max(...subset)
  };
});
console.log(results);


text:
Q: Object following Player I am messing around in Unity and wanted to make a mechanic where a box would touch another object and then that object would follow the Player.
I have Cube set up like this:
And a Sphere with a Box Collider with same options.
My Player script is thus:
public class Player : MonoBehaviour {

public float speed = 0.0f;
public float moveX = 0.0f;
public float moveY = 0.0f;
public GameObject player;
public GameObject obj;
//public float force = 0.0f;
private bool collided = false;

// Use this for initialization
void Start () {
    player = GameObject.FindWithTag ("Player");
}

// Update is called once per frame
void FixedUpdate () {
    moveX = Input.GetAxis ("Horizontal");
    moveY = Input.GetAxis ("Vertical");
    player.GetComponent<Rigidbody> ().velocity = new Vector2 (moveX * speed, moveY * speed);
}

void OnCollisionEnter (Collision col) {
    if (col.gameObject == obj) {
        collided = true;
    }
}

void OnCollisionExit (Collision col) {
    if (col.gameObject == obj) {
        collided = false;
    }
}

void Update () {
    if(collided) {
        obj.transform.position = (player.transform.position - obj.transform.position)*speed;
    }
}

}

What have I yet to do? Hoping someone can nudge me in the right direction.

A: I will provide you two scripts.
1st Script is FollowTarget. This will follow your target forcely.
2nd Script is SmoothFollow which will follow your target in a smooth movement.
FollowTarget.cs
using System;
using UnityEngine;

public class FollowTarget : MonoBehaviour
{
    public Transform target;
    public Vector3 offset = new Vector3(0f, 7.5f, 0f);

    private void LateUpdate()
    {
        transform.position = target.position + offset;
    }
}

SmoothFollow.cs
using UnityEngine;

public class SmoothFollow : MonoBehaviour
{

    // The target we are following
    [SerializeField]
    private Transform target;
    // The distance in the x-z plane to the target
    [SerializeField]
    private float distance = 10.0f;
    // the height we want the camera to be above the target
    [SerializeField]
    private float height = 5.0f;

    [SerializeField]
    private float rotationDamping;
    [SerializeField]
    private float heightDamping;

    // Use this for initialization
    void Start() { }

    // Update is called once per frame
    void LateUpdate()
    {
        // Early out if we don't have a target
        if (!target)
            return;

        // Calculate the current rotation angles
        var wantedRotationAngle = target.eulerAngles.y;
        var wantedHeight = target.position.y + height;

        var currentRotationAngle = transform.eulerAngles.y;
        var currentHeight = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z);

        // Always look at the target
        transform.LookAt(target);
    }
}

Just choose one of them and then attach it to the gameObject. Like another box that is suppose to follow.
Remove your Update() function in your script as you don't need it anymore.
Also Remove your OnCollisionExit()
void OnCollisionEnter (Collision col) {
    if (col.gameObject == obj) {

        // If you choose to use SmoothFollow Uncomment this.
        //col.GetComponent<SmoothFollow>().target = this.transform;

        // If you choose to use FollowTarget Uncomment this
        //col.GetComponent<FollowTarget>().target = this.transform;
    }
}


text:
Q: Лимиты использования многопользовательского SQLite Каковы предельные количественные характеристики SQLite при многопользовательском использовании (с использование WAL) на сетевом диске? Размер, количество соединений?
Предполагается одновременная работа 150-200 пользователей, 20-25 таблиц от 10 от 20 000 записей в каждой. Целесообразно ли использовать SQLite в качестве альтернативы Access, или забить на файл-серверные базы и взять обычную серверную?


text:
Q: JPA and JSON serialization problems Help solve the problem.
I have 2 entity classes:
1.
@Entity
@Table(name = "topic")
public class Topic {
@Id
@Column(name = "topic_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "system_id")
private int systemId;
@Column(name = "topic_name")
private String name;
@OneToMany(mappedBy = "topic", fetch = FetchType.EAGER, orphanRemoval = true)
private List<Faq> faqList;
// getters and setters
@Override
public String toString() {
    return "Topic{" +
            "id=" + id +
            ", systemId=" + systemId +
            ", name='" + name + '\'' +
            ", faqList=" + faqList +
            '}';
}
}

2.
@Entity
@Table(name = "faq")
public class Faq {
@Id
@Column(name = "faq_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "question")
private String question;
@Column(name = "answer")
private String answer;
@ManyToOne
@JoinColumn(name = "topic_id")
@JsonIgnore
private Topic topic;
//getters and setters
@Override
public String toString() {
    return "Faq{" +
            "id=" + id +
            ", question='" + question + '\'' +
            ", answer='" + answer + '\'' +
            ", topicId=" + topic.getId() +
            '}';
}

}
I was forced to in toString method write to console only topic.id, because getting an error "StackOverflow". A similar situation with serialisation to JSON (jackson converter), therefore I used @JsonIgnore annotation. And all was okay. But there is a problem: when i send JSON object from controller.js {topic: {id: "1"}, question: "test", answer: "test"} to the server
@RequestMapping(method = RequestMethod.POST, value = "/faqs")
@ResponseBody
public Message editFaq(@RequestBody Faq faq) {
    System.out.println(faq);

    Message message = new Message("ok");
    return message;
}

in System.out I got NullPointerException. I think that is because @JsonIgnore, when i try get faq.toString (topic.getId()) I got exception. How can I solve this problem?
I solved this, adding path variable to the post:
@RequestMapping(method = RequestMethod.POST, value = "/faqs/{topicId}")
...
Topic topic = new Topic();
topic.setId(topicId);
faq.setTopic(topic);

But this is spike.

A: The StackOverflow error is because of the circular dependency between Topic and Faq. Best to avoid those.
I would also avoid the same class being used in both database and HTTP components such as REST or SOAP endpoints. A change to the database class will be immediately reflected in the structure of the data between client and server - and in the case of SOAP will likely result in a broken client as the interface will have changed. Instead, in your REST or SOAP component write a similar sounding class (FaqVersion1, TopicVersion1) that mirrors the fields of the database but only those fields you want public. Accept this class as a parameter in your methods (editFaq) and map the content to an instance of your database class (Faq). This cleanly separates your database code from your external interfaces (Web).
As a result your Web interface class (FaqVersion1) representing a Faq might have a field called topicId which is a simple String or int reference to the Topic it belongs to. Your application can then be held responsible for accepting a FaqVersion1, spotting the topicId and internally creating a Faq pointing at the real Topic.
Sounds simple doesn't it? It actually is once you hide the database behind your main application and ensure your web component is independent. This separation is seriously good for the health of your application moving forwards.


text:
Q: Directly Set Column of BelongsTo Association in Castle ActiveRecord Say I have the following AR Object:
namespace Models
{
    [ActiveRecord(Lazy = true, Table = "Answer"), Serializable]
    public class Answer : ActiveRecordLinqBase<Answer>
    {
        public Answer() {}

        [PrimaryKey]
        public virtual int ID { get; set; }

        [BelongsTo("QuestionID")]
        public virtual Question Question { get; set; }
    }
}

Is there any way for me to directly set QuestionID?  I tried creating an additional AR [Property] called QuestionID for this purpose, but I run into the NH error described here:
http://devlicio.us/blogs/derik_whittaker/archive/2009/03/19/nhibernate-and-invalid-index-n-for-this-sqlparametercollection-with-count-n-error.aspx
I am trying to unit test this class, and I really don't want to have to set up a database (in memory or otherwise) to do this unit testing.  Setting the QuestionID is all I need to do for the functionality currently under test.
Thanks.

A: I found a hack that accomplishes what I need, but negatively impacts the NH cache (I think): I simply assign to a "new" Question, instantiated with the existing question's ID.  It looks horrible, and, like I said, it essentially loads the cache with these (very) partially-filled question objects (not verified, but behavior seems to indicate as much).


text:
Q: C# - Static events on non-static classes There are situations where I'm quite fond of static events, but the fact that I rarely see them in other people's code makes me wonder if I'm missing something important. I found a lot of discussions about static events on this site, but most of them deal with situations that I'm not interested in (like on static classes) or where I wouldn't think of using them in the first place.
What I am interested in are situations where I might have many instances of something and a single instance of a long-living "manager" object that reacts to something on those instances. A very simple example to illustrate what I mean:
public class God {

    //the list of followers is really big and changes all the time,
    //it seems like a waste of time to
    //register/unregister events for each and every one...
    readonly List<Believer> Believers = new List<Believer>();

    God() {
        //...so instead let's have a static event and listen to that
        Believer.Prayed += this.Believer_Prayed;
    }

    void Believer_Prayed(Believer believer, string prayer) {
        //whatever
    }
}

public class Believer {

    public static event Action<Believer, string> Prayed;

    void Pray() {
        if (Prayed != null) {
            Prayed(this, "can i have stuff, please");
        }
    }
}

To me, this looks like a much cleaner and simpler solution than having an instance event and I don't have to monitor changes in the believers collection either. In cases where the Believer class can "see" the God-type class, I might sometimes use a NotifyGodOfPrayer()-method instead (which was the preferred answer in a few similar questions), but often the Believer-type class is in a "Models"-assembly where I can't or don't want to access the God class directly.
Are there any actual downsides to this approach?
Edit: Thanks to everyone who has already taken the time to answer.
My example may be bad, so I would like to clarify my question:
If I use this kind of static events in situations, where

*

*I'm sure there will only ever be one instance of the subscriber-object

*that is guaranteed to exist as long as the application is running

*and the number of instances I'm watching is huge

then are there potential problems with this approach that I'm not aware of?
Unless the answer to that question is "yes", I'm not really looking for alternative implementations, though I really appreciate everyone trying to be helpful.
I'm not looking for the most pretty solution (I'd have to give that prize to my own version simply for being short and easy to read and maintain :)

A: One important thing to know about events is that they cause objects which are hooked to an event not to be garbage collected until event owner is garbage collected, or until event handler is unhooked.
To put it into your example, if you had a polytheistic pantheon with many gods, where you promoted and demoted gods such as
new God("Svarog");
new God("Svantevit");
new God("Perun");

gods would remain in your RAM while they are attached to Believer.Prayed. This would cause your application to leak gods.

I'll comment on design decision also, but I understand that example you made is maybe not best copy of your real scenario.
It seems more reasonable to me not to create dependency from God to Believer, and to use events. Good approach would be to create an event aggregator which would stand between believers and gods. For example:
public interface IPrayerAggregator
{
    void Pray(Believer believer, string prayer);
    void RegisterGod(God god);
}

// god does
prayerAggregator.RegisterGod(this);
// believer does
prayerAggregator.Pray(this, "For the victory!");

Upon Pray method being called, event aggregator calls appropriate method of God class in turn. To manage references and avoid memory leaks, you could create UnregisterGod method or hold gods in collection of weak references such as
public class Priest : IPrayerAggregator
{
    private List<WeakReference> _gods;

    public void Pray(Believer believer, string prayer)
    {
        foreach (WeakReference godRef in _gods) {
            God god = godRef.Target as God;
            if (god != null)
                god.SomeonePrayed(believer, prayer);
            else
                _gods.Remove(godRef);
        }
    }

    public void RegisterGod(God god)
    {
        _gods.Add(new WeakReference(god, false));
    }
}

Quick tip: Temporarily store event delegate as listeners might unhook their event handlers
void Pray() {
    var handler = Prayed;
    if (handler != null) {
        handler(this, "can i have stuff, please");
    }
}

Edit
Having in mind details you added about your scenario (huge number of event invokers, constant and single event watcher) I think you chose right scenario, purely for efficiency reasons. It creates least memory and cpu overhead. I wouldn't take this approach generally, but for scenario you described static event is very pragmatic solution that I might take.
One downside I see is flow of control. If your event listener is created in single instance as you say, then I would leverage singleton (anti)pattern and invoke method of God from Believer directly.
God.Instance.Pray(this, "For the victory!");
//or
godInstance.Pray(this, "For the victory!");

Why? Because then you get more granular control over performing action of praying. If you decide down the line that you need to subclass Believer to a special kind that doesn't pray on certain days, then you would have control over this.

A: I actually think that having an instance even would be cleaner and defiantly more readable.
It is much more simple to view it as, an instance is preying, so his  pray event gets trigger. And I don't see ant downsides for that. I don't think that monitor changes is not more of a hustle than monitoring the static event. but is the correct way to go...
Monitoring the list:
Change the list to be an ObservableCollection (and take a look at NotifyCollectionChangedEventArgs ).
Monitor it by:
public class God {

    readonly ObservableCollection<Believer> Believers = new ObservableCollection<Believer>();

    public God() {
        Believers  = new ObservableCollection<T>();
        Believers.CollectionChanged += BelieversListChanged;
    }

    private void BelieversListChanged(object sender, NotifyCollectionChangedEventArgs args) {

        if ((e.Action == NotifyCollectionChangedAction.Remove || e.Action ==     NotifyCollectionChangedAction.Replace) && e.OldItems != null)
        {
            foreach (var oldItem in e.OldItems)
            {
                var bel= (Believer)e.oldItem;
                bel.Prayed -= Believer_Prayed;
            }
        }

        if((e.Action==NotifyCollectionChangedAction.Add ||               e.Action==NotifyCollectionChangedAction.Replace) && e.NewItems!=null)
            {
                foreach(var newItem in e.NewItems)
                {
                   foreach (var oldItem in e.OldItems)
                {
                    var bel= (Believer)e.newItem;
                    bel.Prayed += Believer_Prayed;
                }
            }
        }
    }

    void Believer_Prayed(Believer believer, string prayer) {
        //whatever
    }
}


text:
Q: Compare if a var is Hex or RGBA in Sass I have a variable that can either be a hex or rgba value and I need a way to guarantee that the var prints out as a rgba in css.
var $color: #000 || rgba(0, 0, 0, 0.5)

I've looked at rgba($color, 1) but this prints out a hex value if the opacity is 1 and this is can only be used if I know the value is in hex.
How can I accomplish this with sass?

A: If you can accept a very slight opacity, the following appears to work:
color: if(rgba($color,1) == $color, rgba($color,0.99), $color);