text:
Q: Ionic 2 with FCM Push notifications I am using ionic 2
I installed the plugin
HTTP.post to FCM Server not working

cordova plugin add cordova-plugin-fcm

Here is my code
import { Http, Headers } from '@angular/http';

someKey;
t;
constructor(public http: Http) {
      this.t="cwJHK1Ma-Mo:APA91bFRpBudeF9QhTosUs6-N7sSEW3D104cUO3M6gHFyTTDEodTWL5VVMbbbvqbhb5zkgRZwkIMC4p7PYbG7Pmfo6vb4IFB50ZTJN0W-2iJoJ-ZUdeBtcvjJ2nImflgUgtNplA210HP"
      this.someKey="AAAAbZuUvR8:APA91bF3-tKjl5FmXx...."
      let url = 'https://fcm.googleapis.com/fcm/send';
      let body =
       {
         "notification": {
             "title": "Notification title",
             "body": "Notification body",
             "sound": "default",
             "click_action": "FCM_PLUGIN_ACTIVITY",
             "icon": "fcm_push_icon"
         },
         "data": {
             "hello": "This is a Firebase Cloud Messagin  hbhj g Device Gr new v Message!",
         },
         "to": this.t
       };
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': 'key='+this.someKey
    });
    let options = new RequestOptions({ headers: headers });

    console.log(JSON.stringify(headers));

      this.http.post(url, body, headers).map(response => {
        return response;
      }).subscribe(data => {
         //post doesn't fire if it doesn't get subscribed to
         console.log(data);
      });
 }

But I am getting this err
console tells error to be The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at firebase.google.com/docs/cloud-messaging/server. Error 401
EXCEPTION: Response with status: 401 OK for URL: https://fcm.googleapis.com/fcm/send

How can i fix this issue.
Kindly advice me,
Thanks.

A: Hey man I use the https://firebase.google.com/docs/cloud-messaging/admin/send-messages it's easier and you don't have to handle manually the requests.


text:
Q: Azure DevOps build pipeline logid for a specific task - dynamically In Azure DevOps, I have a multistage build pipeline. In that pipeline, I have a task named - Terraform_init. I need the log ID of this task, dynamically. How do I find out the log ID dynamically, if I know the displayname of the task?
Current situation:
Right now I have figured out the Log ID for that task. But later, in my build pipeline, I will add more tasks before the Terraform_init task. So, the log Id will be changed for that task.
Why I need:
After Terraform init task, I have another task called Get_logs. This task gets the logs of the Terraform_init task and saves it in a blob. For that, I have to use the following line -
$logs_url = ('https://dev.azure.com/bmw-ai-big-data-platform/{0}/_apis/build/builds/{1}/logs/27?api-version=6.0' -f $($env:SYSTEM_TEAMPROJECTID), $($env:BUILD_BUILDID)  )
I will have more tasks before the Terrafrom_init task, so ../logs/27.. - this part will need to update every time. I want to avoid this.
Thanks in advanced.

A: Use this code to get the logids:
import requests
import json

url = "https://dev.azure.com/<orgname>/<project name>/_apis/build/builds/<build id>/timeline?api-version=6.0"

payload={}
headers = {
  'Authorization': 'Basic <base64encoded PAT>'
}

response = requests.request("GET", url, headers=headers, data=payload)

reponse_json = response.json()
records = reponse_json['records']
for record in records:
    if record['name'] == 'Initialize job':
        print(record['log']['id'])

After that, using logging command to output the data as variable, and then you can be able to use it in other following tasks(Only for runtime, compile time is unable to achieve.).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to design complex UI in android How can I have a ViewPager above a RecyclerView, or have several RecyclerViews in a ScrollView? I designed the following layout, but it has some problems when scrolling.
What is the problem and how can I solve it?
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dcdcdc"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".ActivityMain"
    tools:showIn="@layout/app_bar_main">

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

       <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="200dip"
           />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </LinearLayout>
</ScrollView>

I have tried compile 'com.bartoszlipinski:recyclerviewheader2:2.0.1' with
 <com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader
           android:id="@+id/header"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal|top">

1- firstly it supports 11 sdk or greater,
2- secondly ViewPager wont work in header RecyclerView.
and i have tried RecyclerView layout_width="wrap_content" but it is just supported in sdk21 .
How can I solve the RecyclerView scrolling ?

A: Try losing the top ScrollView and using a ListView instead of RecyclerView.
ScrollView is unnecessary here and you need a hack for ViewPager to work with RecyclerView as it consumes all touch events. It would be simpler if you could get away with a ListView.

A: You can take your view pager to app bar in collapssing toolbar layout and it will be ok


text:
Q: Webpart, persisting boolean properties I've created a webpart with a lot of properties. All the properties (enums, strings) are persisted just fine when the following attributes are added:
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]

apart from the boolean properties. When the webpart is edited again the stored values for those properties aren't retrieved. Is this behaviour unique to boolean properties?
The property definition is a plain, automatic bool property. In some cases the DefaultValue attribute is applied.
thanks


text:
Q: What statistical software does NOT provide for Classification and Regression models Appended is a list (as far as I can tell) of statistical software that DOES provide for use of Classification and Regression Tree (CART) models.  Some have the CART as a trivial case of things like random-forests or gradient boosted machines.
What I want to know is, outside of these, what software does NOT provide for CART models.
EDIT:
The proprietary software used internally here (not Excel) does not support CART models.  I am making a business case that, when performing ML tasks we need to have software that is capable.  I really am looking for a lack of only this feature.  I am looking for MAINSTREAM statistics GENERAL PURPOSE DATA ANALYSIS packages whose - something likely currently being used by a fortune 500 company to generate actionable results given input information.  I am not looking for every mom-and-pop software package.
I am not asking if anyone could hand-code it in Haskell or Cobol.  I'm asking if it is ALREADY in a PACKAGE for the software.  R has a half-dozen packages.  MatLab has one or two, but it requires a proprietary toolbox.
Outside of the Excel answer - I cannot think of or find a serious package not already accounted for.
If I made a mistake or omission here, please let me know.
As always, suggestions, corrections, comments and feedback are solicited.
Here is my best shot at an exhaustive list of Mainstream/production statistics software with established built-in CART implementations:

*

*(MatLab)
http://www.mathworks.com/help/stats/classification-trees-and-regression-trees.html

*(Python) http://scikit-learn.org/stable/modules/tree.html

*(R)    http://www.statmethods.net/advstats/cart.html

*(JMP)    http://www.jmp.com/support/help/Partition_Method.shtml

*(Weka/RapidMiner)
http://jcsites.juniata.edu/faculty/rhodes/ida/dmcloser.html

*(Mahout/Hadoop)
https://mahout.apache.org/users/classification/partial-implementation.html

*(Mathematica)
http://reference.wolfram.com/language/ref/KaryTree.html?q=KaryTree&lang=en

*(h2o) http://docs.h2o.ai/datascience/gbm.html

*(openCV)    http://docs.opencv.org/modules/ml/doc/decision_trees.html

*(KNIME) https://www.knime.org/files/nodedetails/_labs_treeensemble_Tree_Ensemble_Learner_Regression_.html

*(MS Azure ML)
https://projectbotticelli.com/knowledge/brief-introduction-to-microsoft-azure-ml

*(Statistica)
http://www.statsoft.com/Textbook/Classification-and-Regression-Trees

*(IBM SPSS)
http://www-03.ibm.com/software/products/en/spss-decision-trees

*(Orange)
http://orange.biolab.si/docs/latest/reference/rst/Orange.classification.tree.html

A: As a general rule, whenever you're looking for software without a particular function, Excel is a good place to start.


text:
Q: Javascript won't execute in iPhone Safari I'm running into this issue only because I recently purchased an iPhone.  The javascript for a picture carousel on my website (http://www.stuartmeyerphotography.com) won't execute in Safari for iPhone.  I thought it worked on Mac Safari last I checked with a friend who had a Mac (a year ago), but now I need to go back and check that too to make sure it works on the Mac.  "View source" on my website would show the entire html page, but I've pulled the code from the body section to show here:

Any thoughts?   -Stuart

A: I ran your js through jslint and there were a bunch of problems.  Correcting those might clear up your issues.

A: If you open safari on your mac, there should be a menu item called "Develop".  Under there is an item called user agent in which you can switch your desktop browser to behave like the iPhone mobile safari browser.  It'll be easier to troubleshoot and conduct your iPhone compatibility tests there.
Depending on what you have installed, some options include:
Mobile Safari 4.0.2 - iPhone
Mobile Safari 4.0.2 - iPod Touch
Mobile Safari 3.2.2 - iPad
etc...


text:
Q: browserify require -g modules Some utilities like "sugarjs" I have installed globally on my computer with
npm install sugar -g

However when I try to require sugar in a browserify file it wont work unless I install it locally. This works fine in my node servers, but i'd prefer not to install sugar again for each of my projects.
Is it possible to require files from the global node_modules folder with browserify?

A: You can add something like this to your package.json to tell browserify where to find certain modules:
"browser": {
  "sugar": "/usr/node_modules/sugar/index.js"
}

(Adjust exact filepaths to your system.)


text:
Q: jQuery validate is not working when the button is outside the form I have a problem where jQuery validate is not working when the submit button is placed outside the form tags (which is required form my Cordova mobile app). As soon as .validate is called, the execution stops.
My HTML is set-up this way:
<form id="form-cart" >
  // All form fields here
</form>

<ons-bottom-toolbar>
  <button class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
  Add to Basket
  </button>
</ons-bottom-toolbar>

And the function is then called as:
function addToBasket()
{
    $.validate({
        form : '#form-cart',
        borderColorOnError:"#FF0000",
        onError : function() {
        },
        onSuccess : function() {
        // Run ajax on success
              }
            };
            sNavigator.pushPage("confirmation.html", options);
           return false;
        }
    });
}

How can I get this working so that it validates and calls ajax even if the button is outside of the form tags?

A: According to jQuery validation plugin documentation there are two different methods:
validate() – Validates the selected form.
valid() – Checks whether the selected form or selected elements are valid.
So you should set up the form validation with .validate method outside your function and check if form is valid inside your function (see code example below):
$('#form-cart').validate({

});

function addToBasket() {
    if ($('#form-cart).valid())
        //do you onSuccess stuff
    }
}

A: Try this :
<form id="form-cart" >
    // All form fields here
    // Don't give <input type="submit"> here
</form>

<ons-bottom-toolbar>
    <button type="submit" id="submitBtn" class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
    Add to Basket
    </button>
</ons-bottom-toolbar>

and
$(document).ready(function () {
    $("#submitBtn").click(function () {
        $("#form-cart").submit();
    });
});


text:
Q: Bridge cameras and connect to LAN I'm hoping to connect two H.264 cameras (with ethernet ports) to the main LAN wirelessly. Can a cheap switch be used and somehow have it connected to the LAN via WiFi? Perhaps a wireless bridge? But I read that WiFi isn't designed for bridging. Does anyone know of a good way to connect to the LAN via WiFi?

A: Look for dd-wrt/openwrt compatible routers on your favorite online retailer, or you may even have an old router that might work. (Check the hardware compatibility lists on either firmwares respective websites).
Either firmware will allow you to use the wireless radio in "client" or "bridge mode" essentially turning the router and four port switch to a "Ethernet to wireless adapter".
If you need help setting it up, use your favorite search engine looking for wireless client setup & using the name of whatever firmware you wound up choosing.
Or you could come back and ask about the setup steps as it's own question.
Edit:
Use WDS modes if you are worried about Mac limitations that may or may not be in the newer versions of ddwrt. WDS modes totally overcome the limitations listed here: https://wiki.dd-wrt.com/wiki/index.php/Wireless_Bridge#Limitations
In the case of using WDS, both ends of the link would need to be dd-wrt/openwrt devices, preferably with the same build number of software to ensure both devices have the same WDS compatibility.
~regards


text:
Q: Subtracting two points, the math. I would like to confirm the math of subtracting two points. I've looked online but all of the sources I have seen want to end up with a vector, I need to end with a point.
I am looking at this function in this link,
/*
   Calculate the intersection of a ray and a sphere
   The line segment is defined from p1 to p2
   The sphere is of radius r and centered at sc
   There are potentially two points of intersection given by
   p = p1 + mu1 (p2 - p1)
   p = p1 + mu2 (p2 - p1)
   Return FALSE if the ray doesn't intersect the sphere.
*/
int RaySphere(XYZ p1,XYZ p2,XYZ sc,double r,double *mu1,double *mu2)
{
   double a,b,c;
   double bb4ac;
   XYZ dp;

   dp.x = p2.x - p1.x;
   dp.y = p2.y - p1.y;
   dp.z = p2.z - p1.z;
   a = dp.x * dp.x + dp.y * dp.y + dp.z * dp.z;
   b = 2 * (dp.x * (p1.x - sc.x) + dp.y * (p1.y - sc.y) + dp.z * (p1.z - sc.z));
   c = sc.x * sc.x + sc.y * sc.y + sc.z * sc.z;
   c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z;
   c -= 2 * (sc.x * p1.x + sc.y * p1.y + sc.z * p1.z);
   c -= r * r;
   bb4ac = b * b - 4 * a * c;
   if (ABS(a) < EPS || bb4ac < 0) {
      *mu1 = 0;
      *mu2 = 0;
      return(FALSE);
   }

   *mu1 = (-b + sqrt(bb4ac)) / (2 * a);
   *mu2 = (-b - sqrt(bb4ac)) / (2 * a);

   return(TRUE);
}

specifically at the comments at the top of the function.
I have programmatically found my mu and now need to apply them to the points. So to make sure subtracting $(x_1, y_1)$ from $(x_2, y_2)$ would go
$$(x_1-x_2,\quad y_1-y_2)$$
Then applying mu to a point would just be
$$(x\cdot\mu,\quad y\cdot\mu)$$

A: The "subtraction" of two points does produce a vector in the way you are describing. The idea is that this subtraction gives you the displacement vector between the two points. So if we have $P=(x_1,y_1)$ and $Q=(x_2,y_2)$ then the operation: $$P-Q = (x_1 - x_2, y_1- y_2)$$ is the vector that when you add it to the point $Q$ it will get you to the point $P$.
In this context the operations you are expecting hold true. That is the operation of vector addition and subtraction as well as scalar multiplication.

A: In this context, points - given by their coordinates in 3-space - are identified with vectors, thus justifying the calculations made.


text:
Q: Objective-C Swift bridging header After successfully using my Xcode created Objective-C bridging header Xcode now returns a Swift Compiler error complaining that the bridging header does not exist.

I had been able to use the Xcode created bridging header all day yesterday before Xcode generated this error when the project was compiling. I have attempted to resolve the issue with the solutions here but have been unable to resolve the issue.

Any suggestions?
Thanks in advance.

A: I moved my project location and Xcode (v 6.4 ) still looked for the bridging header in the old folder location which was weird. The only way I fixed it was by using an absolute path to the bridging header (@Aggressor's solution of just dragging the file into the bridging header field populated the field with an absolute path) . Really hoping that later version of Xcode fix this - it seems like a stupid IDE bug to me...

*

*Also ensure to check your project Tests target (if you have one) and do the same there


text:
Q: Как отладить макрос в си? https://github.com/libuv/libuv/blob/v1.x/src/queue.h#L72
Вот например макрос с десятком операций вложенных в другие макросы... Как отладить на какой именно операции я попал в сегфолт?

A: Макроопределения лучше всего дебажить при помощи... Просмотра выхлопа препроцессора! Если используется свободный компилятор gcc, то  у него есть замечательный ключик -E, позволяющий увидеть код, получившийся в итоге на выходе препроцессора. Достаточно просто запустить:
 gcc -E file.c

И посмотреть, что же произошло. Не стоит забывать и о флагах, которые может выставлять ваша система сборки/отладки.
А вот отладка сегфолтов - это уже работа отладчика, здесь нужно скорее использовать ключики -g и -ggdb того же компилятора, чтобы добавить в бинарник отладочную информацию, а потом использовать какой-либо отладчик, вроде gdb, который и укажет проблемное место. Но это уже другой вопрос.


text:
Q: If $\mathbb{E}(X_n)$ is finite for $n=1,2,...$, are $\mathbb{E}|X_n|$ and $\mathbb{E}\left(\sum_{i=1}^n|X_i|\right)$ also finite? I'm not sure that I can think of a counter example for the first one. It seems intuitive to me that this is the case, but perhaps there could exist a sequence of random variables whereby mean of the sum of them is 0, but the mean of the sum of their absolute values is infinite. Or am I totally off the ball here?

A: *

*$\mathbb{E}\left[\sum\limits_{i=1}^n|X_i|\right] =\sum\limits_{i=1}^n\mathbb{E}\left[|X_i|\right]$ so is finite iff each of the $\mathbb{E}\left[|X_i|\right]$ is finite

*If $\mathbb{E}\left[|X_i|\right]$ is infinite then $\mathbb{E}\left[X_i\right]$ is either infinite or undefined, while if $\mathbb{E}\left[|X_i|\right]$ is finite then $\mathbb{E}\left[X_i\right]$ is finite
So each of the $\mathbb{E}\left[X_i\right]$ being finite implies that each of the $\mathbb{E}\left[|X_i|\right]$ is finite and that $\mathbb{E}\left[\sum\limits_{i=1}^n|X_i|\right]$ is finite


text:
Q: How can I get the line number of a search result of a document in googlescript? It's seems like a bit actually, but all I'm doing is having:
var search = DocumentApp.getActiveDocument().getBody.findText("Bill");

which is great because I can get the .getStartOffset(); and the end offset but I need more than that since for the line which the text bill is on I want to make it for example all bold.
So if a document has:

Today on June third: /n
I met Bill - :D. /n
It was awesome. /n

The line "I met Bill." has to be all bolded and not just bill.
How would I go about doing this? There is text after and before bill as well to take into consideration.
Edit: The example I just gave is just random and when actually using the script, it's assumed that the script doesn't know what the example is. So all the script knows that it needs to find the line that Bill is on, and then bold that line.
Also take into consideration this is googlescript which is SIMILAR to javascript but missing some of the functions.

A: You can do this as such,
var search = DocumentApp.getActiveDocument().getBody.findText("Bill");
var arr = [];
if(!!search) {
   arr = search.toString().split("\n");
   var index = -1;
   for(i = 0; i< arr.length; i++) {
       if(index == -1) {
          if(arr[i].indexOf("Bill") != -1)
             index = i;
       }
   }
   if(index != -1) {
      alert("Fount at : " + (index+1));
   }
   else {
      alert("Not found");
   }
}

Give this a try.


text:
Q: Apps script xml importing not working for a website I have a google sheet with the following formula that works fine: =index(importxml("https://sullygnome.com/channel/xqcow/30","//div[@class='InfoStatPanelTLCell']"),1,1)
Trying to do it with google apps script but I get an error.
Using the following:
function parseXml() {
let url = "https://sullygnome.com/";
let data = UrlFetchApp.fetch(url).getContentText();
Logger.log(data);
}

I get this error:
Exception: Address unavailable: https://sullygnome.com/
parseXml    @ Code.gs:3

Tried using the same code with google.com instead and it worked:
function parseXml() {
let url = "https://google.com/";
let data = UrlFetchApp.fetch(url).getContentText();
Logger.log(data);
}

Any ideas how to tackle this?
Thanks

A: The website rejects your request because it's doesn't come from a web browser.
However it looks like you can get around this issue by passing headers and setting the user agent to web browser (e.g Chrome).
For example:
function parseXml() {
    let url = "https://google.com/";

    var options = {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',
        }
    };

    let data = UrlFetchApp.fetch(url, options).getContentText();
    Logger.log(data);
}

Note: I've only tested running the requests with Postman. I simply ran a normal GET requests and then altering the user agent, to get the correct response. It maybe that you'll nee to play around with the code.


text:
Q: Are PS+ Games Free Games Shareable With Other Accounts On the Same PS3? When I get PS+, will other accounts on my PS3 be able to access the game as long as my account with PS+ has a subscription? Or are the games only accessible to my account, even if the other accounts are on the same console? Thanks.

A: Every profile on the system can play any game as long as the account that holds the PS+ subscription is present and active, even if profiles are for other regions. For instance I have both a US and JPN profile on my system and play all the JPN titles from my US profile.
If you cancel the PS+ subscription then all of the Free titles become locked. Any game you purchased, even at a discounted rate is still accessible to all profiles.


text:
Q: Store info from .txt file as variables I am trying to get my code to read from a text file and store what's in it as variables..strings and doubles...to use later. I have no problem getting it to return the info.
This is what's in the .txt file:
circle 5
triangle 3
square 10
sphere 5
cube 4
tetrahedron 8

and for my code I have:
            BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(
                    "src/Data.txt"));

            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                // read next line
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

A: As far as I know, it is not possible to construct a variable name. You can't read "circle" and assign that as a variable name. You can store these as a [key,value] pair using a HashMap<String,Double> to store them as a pair.

A: The first part would be to split the lines, using String.split, to separate variable name and value. If you know in advance which variables you expect in the text file, you can declare those variables and use a switch statement to decide which variable the read name corresponds to, and assign the value accordingly. Otherwise, a HashMap or something similar could be used to store the names and values found in the file.

A: Store your text contents in a hash map, in the following code, I name it "vars". The hashMap vars contains your variables as key,value pairs.
If you need to get the value of any of the variables, you simple write:
    vars.get(key);

so for example to get the value of circle, you write:
     vars.get("circle");

This is your code after modifying it with a hashmap to store variables.
    BufferedReader reader;
    HashMap<String,Double> vars = new HashMap<>();
    try {
        reader = new BufferedReader(new FileReader(
                "src/Data.txt"));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            String[] lineVars = line.split(" ");
            vars.put(lineVars[0],Double.parseDouble(lineVars[1]));
            // read next line
            line = reader.readLine();

        }
        reader.close();
    }catch (IOException e) {
        e.printStackTrace();
    }


text:
Q: Asynchronous data loading in class constructor Example:
var readBackend = function(){
    var deferred = q.defer();
    readData().then(function(data) {
         deferred.resolve(data);
      })
    return deferred.promise;
}

class Test {
    constructor(){
        readBackend().then(function(data) {
            this.importantData = data;
        })
    }

    someFunc() {
        //iterate over important data, but important data is defined
        //promise didnt resolved yet
    }

}

var test = new Test();
test.someFunc(); //throws exception!

Is there any way to ensure, that object properties are initiated by constructor, when I call someFunc?
The only way which comes to my mind is creating init function, which will return promise, but then, everytime I use my class, I would rely on init function to work properly

A:
Is there any way to ensure, that object properties are initiated by constructor, when I call someFunc?

Not without restructuring your code. You cannot have your constructor perform asynchronous operations and expect your synchronous methods to work.

I see two possible solutions:
1. Have a static method which loads the data and returns a new instance of your class:
class Test {
    static createFromBackend() {
      return readBackend().then(data => new Test(data));
    }

    constructor(data){
      this.importantData = data;
    }

    someFunc() {
      // iterate over important data
    }
}

Test.createFromBackend().then(test => {
  test.someFunc();
});

This ensures that the data is available when the instance is created and you can keep the API of the class synchronous.
2. Store the promise on the object:
class Test {
    constructor(){
      this.importantData = readBackend();
    }

    someFunc() {
      this.importantData.then(data => {
        // iterate over important data
      });
    }
}

Of course if someFunc is supposed to return something, that would require it to return a promise as well. I.e. the API of your class is asynchronous now.


text:
Q: D3js mulitline chart mouseOver I'm trying to adapt this D3js line chart example of mouse-over usage to my multi-line chart.
It seems that d3.mouse(this)[0] on the mousemove function generate the following error: "Cannot read property 'sourceEvent' of null".
1 Any idea why I get the null sourceEvent error ?
2 Any tips on how to adapt the mouse over example from a single line chart to a multi (n) line chart ?
Here is a jsfiddle to demonstrate the issue.
( And the solution )
var myApp = angular.module('app', []);
myApp.directive("lineChart", function() {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      id: '@'
    },
    link: function (scope, element, attrs) {
      scope.$watch( 'data', function ( data ) {
        d3.select("#"+attrs.id).select("svg").remove();
        if (data) {
          var margin = {top: 20, right: 20, bottom: 30, left: 40},
              width = element[ 0 ].parentElement.offsetWidth - margin.left - margin.right,
              height = element[ 0 ].parentElement.offsetHeight - margin.top - margin.bottom;
          var parseDate = d3.time.format("%d-%b-%y").parse;
          var x = d3.time.scale()
              .range([0, width]);
          var y = d3.scale.linear()
              .range([height, 0]);
          var xAxis = d3.svg.axis()
              .scale(x)
              .orient("bottom")
              .innerTickSize(-height)
              .ticks(4)
              .outerTickSize(0)
              .tickPadding(5)
              .tickFormat(function(d) { return d3.time.format('%d/%m %H:%M')(new Date(d)); });
          var yAxis = d3.svg.axis()
              .scale(y)
              .orient("left")
              .innerTickSize(-width)
              .outerTickSize(0)
              .tickPadding(10);
          var line = d3.svg.line()
              .x(function(d) { return x(d[0]); })
              .y(function(d) { return y(d[1]); });
          var svg = d3.select(element[0]).append("svg")
              .attr("width", '100%')
              .attr("height", '100%')
              .attr('viewBox','0 0 '+ element[ 0 ].parentElement.offsetWidth +' '+ element[ 0 ].parentElement.offsetHeight )
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
          var minX = d3.min(data, function (item) { return d3.min(item.values, function (d) { return d[0]; }) });
          var maxX = d3.max(data, function (item) { return d3.max(item.values, function (d) { return d[0]; }) });
          var minY = d3.min(data, function (item) { return d3.min(item.values, function (d) { return d[1]; }) });
          var maxY = d3.max(data, function (item) { return d3.max(item.values, function (d) { return d[1]; }) });
          x.domain([minX, maxX]);
          y.domain([0, maxY]);
          svg.append("g")
              .attr("class", "x axis")
              .attr("transform", "translate(0," + height + ")")
              .call(xAxis);
          svg.append("g")
              .attr("class", "y axis")
              .call(yAxis);
          var domaine = svg.selectAll(".domaine")
              .data(data)
              .enter().append("g")
              .attr("class", "domaine");
          domaine.append("path")
              .attr("class", "line")
              .attr("d", function (d) {
                  return line(d.values);
              })
              .style("stroke", function (d) {
                return d.color;
              });
          var focus = svg.append("g")
              .attr("class", "focus")
              .style("display", "none");
          focus.append("circle")
              .attr("r", 4.5);
          focus.append("text")
              .attr("x", 9)
              .attr("dy", ".35em");
          svg.append("rect")
              .attr("class", "overlay")
              .attr("width", width)
              .attr("height", height)
              .on("mouseover", function() { focus.style("display", null); })
              .on("mouseout", function() { focus.style("display", "none"); })
              .on("mousemove", mousemove());
          function mousemove() {
            var x0 = x.invert(d3.mouse(this)[0]),
                i = bisectDate(data, x0, 1),
                d0 = data[i - 1],
                d1 = data[i];/*
                To adapt for multi line
                ,
                d = x0 - d0.date > d1.date - x0 ? d1 : d0;
            focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
            focus.select("text").text(formatCurrency(d.close));*/
          }
        }
      });
    }
  };
});
function MainCtrl($scope) {
$scope.lineData = [{"key": "users","color": "#16a085",
"values": [[1413814800000,4034.418],[1413815400000,5604.155000000001]]},
{"key": "users 2","color": "#d95600",
"values": [[1413814800000,3168.183],[1413815400000,1530.8435]]}];
}

A: When you write
.on("mousemove", mousemove());

it is immediately call the mousemove function and passes its return value as the listener function to the "mousemove" event. Because you are not setting correctly the this that is why d3.mouse(this) returns null.
The fix is very easy: just pass in your mousemove function as reference and don't call it:
.on("mousemove", mousemove);

However even after this fix you will still get an error in the fiddle because your bisectDate function is missing...


text:
Q: How to add a users name to path in C#? Hello stackoverflow community, I want to know how I would be able to do this code: Directory.Delete(@"C:\NAME\AppData\Local", true);But where it says "NAME" I want to get the username of the computer, is this possible? Thanks.

A: I hope you are looking for a way to replace "NAME" with current user logged on that computer. If so then you can use Environment.UserName. Environment.UserName will return you the user on the current thread.

A: You can use,
Getting the computer name in windows
and
string directory = "C:\"+username+"\AppData\Local";
 Directory.Delete(@directory, true);

A: Try this.
Directory.Delete(string.Format(@"C:\{0}\AppData\Local",Environment.UserName), true);

As per Alex comment, if you want to delete "C:\USERS\NAME\AppData\Local" then use this code.
var directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
Directory.Delete(directory, true);


text:
Q: R: Identify Clusters of Adjacent Cells (contiguous regions in 2D matrix of 0-1 values) I'm interested in identifying contiguous regions within a matrix (not necessarily square) of 0-1 (boolean) values, using R. I would like, given a matrix of 0-1 values, to identify each contiguous cluster (diagonals count, although an option of whether to count them or not would be ideal) and register the number of cells within that cluster.
Take the following example:
set.seed(14)
p <- matrix(0, ncol = 10, nrow = 10)
p[sample(1:100, 10)] <- 1
ones <- which(p == 1)
image(p)

I'd like to be able to identify (since I'm counting diagonals) four different groups, with (from top to bottom) 2, 1, 5, and 2 cells per cluster.
The raster package has an adjacent function which does a good job of locating adjacent cells, but I can't figure out how to do this.
One last constraint is that an ideal solution should be fast. I'd like to be able to use it within a data.table dt[, lapply(.SD, ...)] type situation with a large number of groups (each group being a data set from which I could create the matrix).

A: You definitely need connected component labeling algorithm


text:
Q: How to rename list objects in self defined function? quote <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  return(list(namefoo=foo,namebar=bar))
}

From the above function, If I ran quote(test, test1) the name of the two objects in the list remain as namefoo and namebar instead of what I specified in the function call.
If I just ran the code seperately as:
set.seed(3)
foo <- rnorm(n = 5)
bar <- rnorm(n = 5)
obj <- list(test=foo,test1=bar)

Then obj will return foo and bar with the amended names. How do I make my function do this? I've tried several combinations of including quotes as well, from the function call to the function itself but it doesn't seem to work.

A: One way is this:
quote <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  out <- list(foo, bar)
  names(out) <- c(namefoo, namebar)
  out
}

You can save the list to a variable and then name the elements with names.
# quote('foo', 'bar')
# $namefoo
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319
# [5]  0.1957828
#
# $namebar
# [1]  0.03012394  0.08541773  1.11661021
# [4] -1.21885742  1.26736872

A: It's a very bad idea to name your function quote, a very important R function is named just like that.
Use setNames :
fun <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  setNames(list(foo,bar),c(namefoo, namebar))
}

fun("hi","there")
# $hi
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319  0.1957828
#
# $there
# [1]  0.03012394  0.08541773  1.11661021 -1.21885742  1.26736872

You might also see this kind of code around too, using more advanced features of rlang / tidyverse :
library(tidyverse)
fun2 <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  lst(!!namefoo := foo,!!namebar := bar)
}

fun2("hi","there")
# $hi
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319  0.1957828
#
# $there
# [1]  0.03012394  0.08541773  1.11661021 -1.21885742  1.26736872

A: We can do
quotefn <- function(...) {
        nm <- c(...)
        out <- replicate(length(nm), rnorm(n = 5), simplify = FALSE)
        names(out) <- nm
        out}
quotefn("foo", "bar")
#$foo
#[1] -0.5784837 -0.9423007 -0.2037282 -1.6664748 -0.4844551

#$bar
#[1] -0.74107266  1.16061578  1.01206712 -0.07207847 -1.13678230


text:
Q: How to detect certain gestures? SO i am building a game in which i want to be able to allow the user to do certain actions based on the gesture on the screen.
For example, the user makes a circle with their finger on the screen and then something will happen.
Or the user makes a triangle and then something happens..
Is there any way to detect this type of gestures?

A: This guy wrote an awesome post on the topic with source included:
http://www.androiddevblog.net/android/gesture-detection-in-android-part-2-of-2


text:
Q: How to arrange date in R if date is in character? Now I have a column called trending_month with character values:
'Jan 2018', 'Dec 2017', 'Feb 2018', 'Nov 2017'

How do I order them in ascending timeline to get this?
'Nov 2017', 'Dec 2017', 'Jan 2018', 'Feb 2018'

As trending_month is in character, when I order it in ascending order, it arranges it according to alphabetical format.

A: One way would be to convert the values into date and then order. In base R, that can be done as
df[order(as.Date(paste(1, df$trending_month), "%d %b %Y")), ]

#  x trending_month
#4 4       Nov 2017
#2 2       Dec 2017
#1 1       Jan 2018
#3 3       Feb 2018

data
df <- data.frame(x = 1:4,
                 trending_month = c('Jan 2018','Dec 2017','Feb 2018','Nov 2017'))


text:
Q: Repeated photo access If user denied app's photo access, is it possible to re-request photo access?
Like here image
Special thanks!

A: No, once access is denied you cannot ask again. The only way to get access is for the user to enter settings and enable it themselves.
One alternative to this that I have seen is to display a message like ...

To enable us to blah blah blah we need access to your photos. Is that OK to ask?
  "YES"      "Not Now"

Then if they tap yes you can ask for photo access and they will probably give you access.
If they press Not Now then you don't ask them but next time you can display your initial request again.
This means you only actually ask for access when they are probably going to grant access anyway.


text:
Q: How to construct SOAP message with pysimplesoap? I'm trying to call a SOAP service from the Dutch government land register (WSDL here) with PySimpleSoap. So far I did this to connect:
from pysimplesoap.client import SoapClient
client = SoapClient(wsdl='http://www1.kadaster.nl/1/schemas/kik-inzage/20141101/verzoekTotInformatie-2.1.wsdl')

and with the help of an awesome answer by Plamen Petrov I now understand I need to send the xml below using the client.VerzoekTotInformatie() method.
What I do not understand however, is how I can get the desired XML (see below). I can of course build it manually, but I've got the feeling that there is a smarter/more pythonic way of constructing that. Can I use pysimplesoap to construct this message xml?
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.kadaster.nl/schemas/kik-inzage/20141101" xmlns:v20="http://www.kadaster.nl/schemas/kik-inzage/ip-aanvraag/v20141101">
   <soapenv:Header/>
   <soapenv:Body>
      <ns:VerzoekTotInformatieRequest>
         <v20:Aanvraag>
            <v20:berichtversie>?</v20:berichtversie>
            <v20:klantReferentie>ABC</v20:klantReferentie>
            <v20:productAanduiding>?</v20:productAanduiding>
            <v20:Ingang>
               <v20:Object>
                  <v20:IMKAD_KadastraleAanduiding>
                     <v20:gemeente>Amsterdam</v20:gemeente>
                     <v20:sectie>123</v20:sectie>
                     <v20:perceelnummer>456</v20:perceelnummer>
                     <v20:appartementsindex>789</v20:appartementsindex>
                     <v20:deelperceelnummer>10</v20:deelperceelnummer>
                     <v20:AKRKadastraleGemeenteCode>20</v20:AKRKadastraleGemeenteCode>
                  </v20:IMKAD_KadastraleAanduiding>
               </v20:Object>
            </v20:Ingang>
         </v20:Aanvraag>
      </ns:VerzoekTotInformatieRequest>
   </soapenv:Body>
</soapenv:Envelope>

[EDIT]
Following the examples in the docs I now try adding the VerzoekTotInformatieRequest with a berichtversie in it, after which I tried to do a request to the soap-service. But as you can see below, the body still only has an empty <VerzoekTotInformatie> (no Request in it), plus I get a massive error. Any ideas how I can build the message above?
>>> client['VerzoekTotInformatieRequest'] = {'Aanvraag': {'berichtversie': 'yay'}}
>>> c.VerzoekTotInformatie()
INFO:pysimplesoap.client:POST https://service1.kadaster.nl/kik/inzage/20141101/VerzoekTotInformatieService
DEBUG:pysimplesoap.client:SOAPAction: "VerzoekTotInformatie"
Content-length: 378
Content-type: text/xml; charset="UTF-8"
DEBUG:pysimplesoap.client:<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Header/>
<soap:Body>
    <VerzoekTotInformatie xmlns="http://www.kadaster.nl/schemas/kik-inzage/20141101">
    </VerzoekTotInformatie>
</soap:Body>
</soap:Envelope>
DEBUG:pysimplesoap.client:date: Fri, 24 Apr 2015 12:51:05 GMT
status: 404
content-length: 956
content-type: text/html;charset=utf-8
DEBUG:pysimplesoap.client:<title>JBossWeb/2.0.0.GA_CP05 - Error report</title>
HTTP Status 404 -

type Status report

message

description The requested resource () is not available.

JBossWeb/2.0.0.GA_CP05

ERROR:pysimplesoap.simplexml:<title>JBossWeb/2.0.0.GA_CP05 - Error report</title>
HTTP Status 404 -

type Status report

message

description The requested resource () is not available.

JBossWeb/2.0.0.GA_CP05

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pysimplesoap/client.py", line 181, in <lambda>
    return lambda *args, **kwargs: self.wsdl_call(attr, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/pysimplesoap/client.py", line 346, in wsdl_call
    return self.wsdl_call_with_args(method, args, kwargs)
  File "/Library/Python/2.7/site-packages/pysimplesoap/client.py", line 370, in wsdl_call_with_args
    response = self.call(method, *params)
  File "/Library/Python/2.7/site-packages/pysimplesoap/client.py", line 262, in call
    jetty=self.__soap_server in ('jetty',))
  File "/Library/Python/2.7/site-packages/pysimplesoap/simplexml.py", line 56, in __init__
    self.__document = xml.dom.minidom.parseString(text)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 1928, in parseString
    return expatbuilder.parseString(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 940, in parseString
    return builder.parseString(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
ExpatError: mismatched tag: line 1, column 944

A: Constructing xml is not the necessary (or correct) way to call a soap method. PySimpleSoap has already provided quite an elegant and human-readable way to do this:
client = SoapClient(wsdl='http://www1.kadaster.nl/1/schemas/kik-inzage/20141101/verzoekTotInformatie-2.1.wsdl', trace=True)
client.VerzoekTotInformatie(Aanvraag={'berichtversie':4.7,
                                      'klantReferentie':'cum murmure',
                                      'productAanduiding': 'aeoliam venit'})

The debug log would be like this:
INFO:pysimplesoap.client:POST https://service1.kadaster.nl/kik/inzage/20141101/VerzoekTotInformatieService
DEBUG:pysimplesoap.client:SOAPAction: "VerzoekTotInformatie"
Content-length: 842
Content-type: text/xml; charset="UTF-8"
DEBUG:pysimplesoap.client:<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Header/>
        <soap:Body>
            <VerzoekTotInformatieRequest xmlns="http://www.kadaster.nl/schemas/kik-inzage/20141101">
                <Aanvraag xmlns="http://www.kadaster.nl/schemas/kik-inzage/ip-aanvraag/v20141101">
                    <berichtversie xmlns="http://www.kadaster.nl/schemas/kik-inzage/ip-aanvraag/v20141101">4.7000000000</berichtversie>
                    <klantReferentie xmlns="http://www.kadaster.nl/schemas/kik-inzage/ip-aanvraag/v20141101">cum murmure</klantReferentie>
                    <productAanduiding xmlns="http://www.kadaster.nl/schemas/kik-inzage/ip-aanvraag/v20141101">aeoliam venit</productAanduiding>
                </Aanvraag>
            </VerzoekTotInformatieRequest>
        </soap:Body>
</soap:Envelope>

As you can see, the xml is automatically constructed and sent to server. However I got 401: Unauthorized error, which you may know how to fix.


text:
Q: Key difference between PID and LQI integral terms I am working on control theory implementation on quadcopters. So far I have empirically implemented a PID and an LQI (Linear Quadratic Integral) controllers and tested them. I got a MUCH robust performance from LQI in terms of noise and disturbance rejection, and model uncertainties (click here for detailed analysis).
However, I understand that the PID control output u is:
u(s) = [Kp + Ki/s + Kd*s]*e(s)
and the LQI output is:
u(s) = -Kx * x(s) - Ki * xi(s)
My question is mainly about the integral term in each controller. Both of the controllers integrate the error e and have a zero at the origin. How is the LQI controller is better (more robust) that the PID one?

A: This is not always true though in general it is practically true since PID control tuning is a local optimization problem compared to the state feedback+integrator design.
What the difference is that in the LQI control you are using the state information to control the system and driving the steady state error quicker with an extra integrator.
In PID case however you are using the output of the system which (assuming observability and controllability) cannot immediately have all the information. Imagine there are two states a fast one and a rather slow one and you are only observing a strange combination of them encoded in your C matrix. PID works on that observed quantity whereas LQI works with both states simultaneously.


text:
Q: how to add a dynamic image src with laravels blade My question is very simple. i use blade in laravel to show the images like

but what if my image is dynamic like:

i cant use

because then i will end with:

How can i call to a $variable in a blade {{}} call?

A:
How can i call to a $variable in a blade {{}} call?

The normal PHP way. A blade {{}} is just the equilivant of <?php echo() ?>
So the answer to your question is:

A: How about

EDIT
when you need printing more than one strings where there may be variables,functions... you need to concatenate them
Also asset('assets/images/') is equivalent to asset('assets/images') so you need to add / before printing your variable $imgsrc
Finally, in Blade {{"foo"}} is equivalent to <?php echo "foo" ?>

A: Mine had multiple dynamic parts in the src and this is how I did it after getting in the right direction, thanks to @Laurence's answer.
event_logo}}" class="event-page-country-logo">


text:
Q: not able to run all sites automation in loop one by one in selenium python It's not running sites one by one in loop, if site 1 runs then ( sms ) should count 1, and when site 2 runs then ( sms ) should count 2 but when the loop starts, both sites runs once then ( sms ) counts 1.
I want to make it site 1 = ( sms ) count 1 , site 2 = ( sms ) count 2.
If amount = 50, then the loop should run 50 times sites 1 by 1 till 50.
If site 1 runs so sms = 1 should be like this
mobile_number = '9199999999'
amount = 10
for sms in range(1,amount):
    print(sms)

    browser.get('https://www.site.in/') #this is site 1
    time.sleep(2)
    login = browser.find_element_by_class_name('m-0').click()
    time.sleep(1)
    number = browser.find_element_by_class_name('floating-input').send_keys(mobile_number)
    button = browser.find_element_by_class_name('decabutton').click()
    time.sleep(2)

    browser.get('https://www.site.in/customer/account/create/')  #this is site 2
    time.sleep(2)
    number = browser.find_element_by_class_name('mobnumber').send_keys(mobile_number)
    time.sleep(1)
    otp = browser.find_element_by_class_name('regi-sendotp').click()
    time.sleep(2)

A: You have to pass the iteration
def make_incrementers():
    amount = 10
    result = []

    for i in range(amount):
        def incrementer(x):
            return x + i
        result.append(incrementer)
    return result


text:
Q: iPhone : Getting the size of an image after AspectFt Real odd one to get stuck on but weirdly I am.
You you have a imageView containing a image.  You size that imageView down and then tell it to use UIViewContentModeScaleAspectFit.  so your imageView might be 300 by 200 but your scaled image within could be 300 by 118 or 228 by 200 because its aspectfit.
How on earth do you get the size of the actual image?
imageView.image.size is the size of the original image.
imageview.frame is the frame of the imageview not the contained image.
imageview.contentstretch does not work either

A: The Swift version of the accepted answer:
extension UIImageView {
var imageScale: CGSize {
    let sx = Double(self.frame.size.width / self.image!.size.width)
    let sy = Double(self.frame.size.height / self.image!.size.height)
    var s = 1.0
    switch (self.contentMode) {
    case .scaleAspectFit:
        s = fmin(sx, sy)
        return CGSize (width: s, height: s)

    case .scaleAspectFill:
        s = fmax(sx, sy)
        return CGSize(width:s, height:s)

    case .scaleToFill:
        return CGSize(width:sx, height:sy)

    default:
        return CGSize(width:s, height:s)
    }
  }
}

A: Just adding a little security on Individual11 code.
Calling imageScale on an imageView without an actual image would crash.
extension UIImageView {
    var imageScale: CGSize {

        if let image = self.image {
            let sx = Double(self.frame.size.width / image.size.width)
            let sy = Double(self.frame.size.height / image.size.height)
            var s = 1.0
            switch (self.contentMode) {
            case .scaleAspectFit:
                s = fmin(sx, sy)
                return CGSize (width: s, height: s)

            case .scaleAspectFill:
                s = fmax(sx, sy)
                return CGSize(width:s, height:s)

            case .scaleToFill:
                return CGSize(width:sx, height:sy)

            default:
                return CGSize(width:s, height:s)
            }
        }

        return CGSize.zero
    }
}

A: I have written a quick category on UIImageView to achieve that:
(.h)
@interface UIImageView (additions)
- (CGSize)imageScale;
@end

(.m)
@implementation UIImageView (additions)
- (CGSize)imageScale {
    CGFloat sx = self.frame.size.width / self.image.size.width;
    CGFloat sy = self.frame.size.height / self.image.size.height;
    CGFloat s = 1.0;
    switch (self.contentMode) {
        case UIViewContentModeScaleAspectFit:
            s = fminf(sx, sy);
            return CGSizeMake(s, s);
            break;

        case UIViewContentModeScaleAspectFill:
            s = fmaxf(sx, sy);
            return CGSizeMake(s, s);
            break;

        case UIViewContentModeScaleToFill:
            return CGSizeMake(sx, sy);

        default:
            return CGSizeMake(s, s);
    }
}
@end

Multiply the original image size by the given scale, and you'll get your actual displayed image size.

A: well .. you have to do some math. you have the size of the original image and you have the size of the image view.. so you can calculate whether it will be resized by the height or the width.
if you image view is 300x200 and the image is 1024x768 you can calculate which is the limiting factor
300/1024 = 0.29296875
200/768 = 0.260416667

so the height is the limiting factor ... the image will be:
267x200


text:
Q: How do i update the openstack api access to be accessible from the outside world My openstack install is working wonderful, with the exception that all api access URLS are 192.168.x.x ... I have looked through a lot of postings and im still left confused. Which commands do i use to allow openstack to have local lan ip and 'foo.com' (public) api access?
I apologize if this has been posted before, i'm not seeing it.
Thanks in advance!

A: On your server hosting keystone check :
keystone service-list

retrieve the id of the service your looking fo
keystone endpoint-list | grep id

You'll have three url : public, internal, admin
To change the public url use mysql command like
mysql -uroot -p
use keystone;
update endpoint set url="http://publicURL:port/" where id="yourID";

Hope it'll help


text:
Q: Geting a value from select box using jQuery I've got a simple select input and I'm using jQuery's .val() to get the selection from it.
For some reason, it is throwing a "Object doesn't support this property or method" error in Internet Explorer 8, the first error I've ever seen jQuery actaully throw.
I've replicated this error at http://jsfiddle.net/gWvwS
What am I doing wrong? Seems pretty straight forward to me...

A: Try:
var isplay_entry_form = $('#display_entry_form').val();
alert(isplay_entry_form);

display_entry_form on the global window is actually the element. It's much less known, because it's really bad and shouldn't be used. So you are overwriting it in IE.
Fixed Example for IE8: http://jsfiddle.net/gWvwS/7/

A: Javascript variables with the same name as DOM elements  are not supported by IE. It appears that IE uses a common mechanism for addressing DOM elements by id and addressing javascript variables. Which means that whichever object (DOM element or javascript var) is declared later in the source is the one that gets used. This will likely cause an "object does not support this property or method" error when you try to access your javascript variable. (source)
This should work:
display_entry_form_value = $('#display_entry_form > option:selected').val();
alert(display_entry_form_value);

A: I suppose it has to do with, that value belongs to option, not to select.
Try
$('select#display_entry_form option:selected').val();

A: Your document contains an element with name display_entry_form. In IE, named elements are globally accessible through their name. So, you have to either use var (to declare a new, local variable[Need verification]), or choose another name.
var other_name = $('#display_entry_form').val();
alert(other_name);

Fiddle http://jsfiddle.net/gWvwS/5/

A: I updated jsfiddle to correct code:
http://jsfiddle.net/gWvwS/6/

A: The <select> tag doesn't have a value attribute, but rather a selectedIndex attribute.


text:
Q: Comfortable Edge Labeling of Undirected Graph I'm working on a program that finds special [called "interval"] edge-colorings for graphs. Output is as follows:
Coloring = {1 \[UndirectedEdge] 10 -> 1, 1 \[UndirectedEdge] 2 -> 2,
            9 \[UndirectedEdge] 10 -> 2, 1 \[UndirectedEdge] 9 -> 3,
            2 \[UndirectedEdge] 10 -> 3, 1 \[UndirectedEdge] 3 -> 4}

Now I want to visualize the coloring. I use EdgeLabels->Coloring, but it writes the labels in the middle, which is not comfortable, especially in case of symmetric graphs like Complete Graphs. I want to display 2 labels on both ends of each edge.
Right now I can display it only on one end of each edge using the following code:
1 \[UndirectedEdge] 10 -> Placed[1, 1/6]

and I get the following result:

Documentation suggests to use Placed[{1,1},{"Start","End"}] to display 2 labels on two ends. That particular example works, but when I change "Start" or "End" to 1/6 or 5/6, no labels are displayed at all.

A: You may:
Show@Table[
  CompleteGraph[3,
   EdgeLabels -> {1 \[UndirectedEdge] 3 -> Placed[1, p]},
   ImagePadding -> 10], {p, {1/6, 1/2, 5/6}}]

A: Using GraphPlot and a custom EdgeRenderingFunction
ClearAll[erf];
erf[pos_List, lblcolors_, fontsizes_, linecolor_: Blue] := {linecolor, Line[#],
 Sequence @@ Table[Inset[Style[Text[#3], lblcolors[[i]], FontSize -> fontsizes[[i]]],
    pos[[i]] First@# + (1 - pos[[i]]) Last@#, Automatic, Automatic, -Subtract @@ Sort[#],
   Background -> White], {i, 1, Length@pos}]} &

Example:
edges = {{4 -> 2}, {5 -> 1}, {3 -> 2}, {2 -> 5}, {3 -> 5}};
labelededges = MapIndexed[{First@#1, ToString@First@#2} &, edges];

GraphPlot[labelededges,
 EdgeRenderingFunction -> erf[{(5/6), 1/6}, {Green, Red}, {16, 24}],
 PlotStyle -> Thick, VertexLabeling -> True, ImagePadding -> 20]


text:
Q: Do the output of command `tty` and the file `/dev/tty` both refer to the controlling terminal of the current bash process?
*

*From man tty

tty - print the file name of the terminal connected to standard input

$ tty
/dev/pts/2

*From APUE:

Historically, the name of the controlling terminal in most versions of the UNIX System has been /dev/tty. POSIX.1 provides a
  runtime
  function that we can call to determine the name of the controlling
  terminal.
#include <stdio.h>
char *ctermid(char *ptr);

$ ls -la /dev/tty
crw-rw-rw- 1 root tty 5, 0 May 26 00:16 /dev/tty

So I was wondering if the output of command tty and the file /dev/tty  both refer to the controlling terminal of the current bash process?
If yes, why does command tty output a pseudoterminal slave file /dev/pts/2, which is different from /dev/tty?
Since the terminal emulator lxterminal and the bash shell running in it use a pseudoterminal pair, isn't the pseudoterminal slave /dev/pts/2 the controlling terminal of the bash shell?
/dev/tty and /dev/pts/2 aren't symlinks to one another, so are they different files?
Thanks.
A follow up post what relations are between my current controlling terminal and `/dev/tty`?

A: The command tty (1) returns the name of the terminal connected to standard input. This may be the controlling terminal or it may not be. The process may even have a controlling terminal but it is not written in stone that that terminal must be connected to standard input.
From the POSIX manual page for tty (1):

The tty utility shall write to the standard  output  the  name  of  the terminal that is open as standard input. The name that is used shall be equivalent to the string  that  would  be  returned  by  the  ttyname() function defined in the System Interfaces volume of POSIX.1‐2008.

Try it for yourself; run
< /dev/null sh -c 'tty; sleep 10; echo "Done."'

and press Ctrl+C after seeing the message "not a tty" written out by tty because standard input it not a (pseudo-)terminal.
On the other hand, /dev/tty is always a synonim for the controlling terminal of a process, provided that the process actually has a controlling terminal.

A:
Do the output of command tty and the file /dev/tty both refer to the controlling terminal of the current process?

Well, no, they're not the same. tty outputs the name of the tty connected to it's standard input. That's not necessarily the same as the controlling terminal (which what /dev/tty refers to).
$ tty
/dev/pts/12
$ tty < /dev/pts/1
/dev/pts/1
$ tty < /dev/null
not a tty

Of course, usually if you have stdin connected to a terminal, it's the controlling terminal.
The use case for tty that I've seen, is to determine if a script is running interactively or not. For that use, checking stdin instead of the controlling terminal allows to detect situations where the stdin is connected to something other than a terminal, and where the user can't provide interactive input. E.g. running maybe_interactive.sh < some_input_file from an interactive shell.

/dev/tty and /dev/pts/2 aren't symlinks to one another, so are they different files?

/dev/tty can't be a symlink since the controlling terminal is different for different processes, and symlinks are the same for every process.


text:
Q: iTextPDF: changing the Table Alignment dynamically I want to dynamically align the iText PdfTable.
How to set the x and y position based alignment in iTextPDF.
PdfPCell cell;
cell = new PdfPCell(testTable);
cell.setFixedHeight(44f);
cell.setColspan(3);
cell.setBorder(0);
table.addCell(cell);
table1.addCell(table);

A: please look in to this example...
public static void Main() {

        // step 1: creation of a document-object
        Document document = new Document();

        try {

            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter writer = PdfWriter.getInstance(document, new FileStream("Chap1002.pdf", FileMode.Create));

            // step 3: we open the document
            document.Open();

            // step 4: we grab the ContentByte and do some stuff with it
            PdfContentByte cb = writer.DirectContent;

            // we tell the ContentByte we're ready to draw text
            cb.beginText();

            // we draw some text on a certain position
            cb.setTextMatrix(100, 400);
            cb.showText("Text at position 100,400.");

            // we tell the contentByte, we've finished drawing text
            cb.endText();
        }
        catch(DocumentException de) {
            Console.Error.WriteLine(de.Message);
        }
        catch(IOException ioe) {
            Console.Error.WriteLine(ioe.Message);
        }

        // step 5: we close the document
        document.Close();
    }
}

A: Please take a look at the C# port of the examples of chapter 4 of my book: http://tinyurl.com/itextsharpIIA2C04
You can add the table to a ColumnText object and add the column at an absolute position:
ColumnText column = new ColumnText(writer.DirectContent);
column.AddElement(table);
column.SetSimpleColumn(llx, lly, urx, ury);
column.Go();

In this snippet llx, lly and urx, ury are the coordinates of the lower-left corner and the upper-right corner of the column on the page (see the ColumnTable example).
In the PdfCalendar example, another method is used:
table.WriteSelectedRows(0, -1, x, y, writer.DirectContent);

The first parameters define which rows need to be drawn (0 to -1 means all rows), x and y define the absolute position.


text:
Q: How to display object in a JTextArea? I have a Paper class that has 4 attributes.
public class Paper(int id, String author, String title, int rank){

}

Then I have a LinkedList that contains the paper object.
I have a GUI that displays the paper object in the JTextArea. GUI has buttons that let users to add paper, delete and save the file. When users press save button the Paper objects are saved in a txt file as follows:
46,Evolutionary Comp,Michael Smith,12/01/10,4
61,Fuzzy Logic and App,John Peterson,13/01/10,3
118,Neural Networks,Arthur London,20/01/10,5
200,Evolutionary Comp,Scott Jones,30/01/10,1
210,Fuzzy Logic and App,Joe Wang,01/02/10,4

How do I display the content of txt file in the the JTextArea. Paper class has toString() method that prints the data of Paper Object.
Thanks. If the question is not very clear please make a comment and I will try and make it as clear as possible.

A: I haven't actually tried this myself, but it would seem you could use JTextArea.append(String) or JTextArea.insert(String, int).
Details:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html
In general, if you want to know what you can do with a given type Foo, try googling "java Foo" and javadoc pages usually show up as the first few hits.

A: JTextarea.append(string) worked perfectly for me. Thanks
// addPaper() returns paper object
displayTxtArea.append(addPaper().toString());


text:
Q: How could I add my web browser game to Adsense? I tried to add my recently published web browser game to adsense. However, they rejected it and replied with needs attention, your site doesn't have any content.
How can I make it approved by adsense? Because it is a web browser game, it is quite normal that there is no content like blogs
Is there any alternative way to make my site publish any advertising by adsense, or any alternative for adsense that can allow web browser games?

A: Hey AdSense is for Unique and Informative text content. In online game nothing unique or text. So I will suggest you to create app and use AdMob or try AdX.


text:
Q: Стилизация checkbox? Как правильно стилизовать checkbox с такой структурой html, что-бы при клике появлялся синий квадрат в checkbox? Спасибо

.mfilter-col-input {
  position: relative;
  top: 3px;
   width: 20px;
  height: 20px;
}

.mfilter-col-input input {
  position: absolute;
  top: 3px;
  width: 20px;
  height: 20px;
  margin: 0px;
  z-index: -1;
  opacity: 0;
}

.mfilter-col-label::before {
    content: "";
    display: inline-block;
    position: absolute;
    left: 0;
    top: 3px;
    width: 20px;
    height: 20px;
    margin: 0px 10px 0px 10px;
    border: 1px solid #726f6f;
    box-sizing: border-box;
    background: #f5f6f6;
    border-radius: 0px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 90% 90%;
}

.mfilter-col-input input:checked + .mfilter-col-label::before {
    border-color: #347a89;
    background-color: #347a89;
}

  <input class="mfilter-col-inp" id="mfilter-opts" type="checkbox" value="текст">

  Текст

A: Основная загвоздка была в том что элементы должны быть соседними, т.е. нет возможности определить див в котором чекбокс установлен (чекбокс будет выбран в качестве результата, не див)
Стили я тоже немного поправил, но это уже дело вкуса, основной упор на разметке.

.mfilter-col {
  display: inline-flex;
  flex-direction: column;
  justify-content: flex-start;
}

.mfilter-col .mfilter-col-inp {
  align-self: flex-start;
}

.mfilter-col-label::before {
  content: "";
  display: inline-block;
  position: absolute;
  top:  6px;
  left: 0px;
  width: 20px;
  height: 20px;
  margin: 0px 10px 0px 10px;
  border: 1px solid #726f6f;
  box-sizing: border-box;
  background: #f5f6f6;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 90% 90%;
}

.mfilter-col-inp:checked + .mfilter-col-label::before {
  border-color: #347a89;
  background-color: #347a89;
}

<input class="mfilter-col-inp" id="mfilter-opts" type="checkbox" value="текст">

  Текст


text:
Q: Trying to install Homebrew, but I get this "fatal: cannot create directory at 'Library/ENV/pkgconfig/10.10': Permission denied" I am having issues with Brew. It was working fine, but now it's a little wonky.
Tried re-installing, but I get this error:"fatal: cannot create directory at 'Library/ENV/pkgconfig/10.10': Permission denied"
Anyone know how to fix this?
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
-e:70: warning: Insecure world writable dir /usr/local in PATH, mode 040777
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...
/usr/local/share/man/man1/brew.1
Press RETURN to continue or any other key to abort
==> /usr/bin/sudo /bin/chmod g+rwx /Library/Caches/Homebrew
Password:
==> Downloading and installing Homebrew...
remote: Counting objects: 207213, done.
remote: Compressing objects: 100% (55712/55712), done.
remote: Total 207213 (delta 150324), reused 207201 (delta 150315)
Receiving objects: 100% (207213/207213), 43.70 MiB | 3.08 MiB/s, done.
Resolving deltas: 100% (150324/150324), done.
From https://github.com/Homebrew/homebrew
* [new branch]      master     -> origin/master
fatal: cannot create directory at 'Library/ENV/pkgconfig/10.10': Permission denied
Failed during: git reset --hard origin/master

A: I would suggest go and visit 'Library/ENV/pkgconfig/10.10', if it's there, try to look at its permission, if it differs, try to delete it and re-run the installation.
It happen to me once also but it's coming from sass/grunt. Permission denied just to find out that special file was created by other user (because I copied it from somewhere) and it have overriding problems, thats why it return permission denied.
Well, that's my case, hope this little stuff might help you. Who knows :P

A: The error appears to be your permissions are too global on /usr/local so it's trying to default to /usr/local/Library
Try changing to 755:
sudo chmod 755 /usr/local

Also the user should be root:admin (if not already)
sudo chown root:admin /usr/local

NOTE: not using the -R flag here as most, if not all stuff within /usr/local belongs to current user


text:
Q: Cannot copy CSV to database table because access is denied I have a CSV file named CropData.csv that I want to copy into a postgreSQL table called Crops as follows:
\copy "Crops" FROM '/home/erooijak/zaaikalender/CropData.csv' DELIMITER ',' CSV;

I also tried using COPY instead of \copy. Unfortunately, both attemps give the message:

ERROR:  could not open file "/home/erooijak/zaaikalender/CropData.csv" for reading: Permission denied

I tried making the user postgres owner of the files and setting the permissions to read write and execute as follows:
su
chown postgres:postgres CropData.csv
chmod 777 CropData.csv

This still gives the same error.
When I display the properties of a file using the explorer I see this:

Can someone explain to me why I cannot copy the CSV into a table and how I would be able to do it? Thanks.

A: One way to do it was by copying the CSV via the GUI tool pgadmin3 as follows:

Still not clear why I cannot get it to work in a command.


text:
Q: Include custom post type in Wordpress loop Sorry, I think I read every post about this but cant get it to work.
I have a Wordpress custom post typ called "external" and I would like to show both the post from "external" aswell as my normal standard posts at the same time on my homepage.
This is my loop:
<?php
get_header();

if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>
    <?php the_content(); ?>

<?php endwhile; wp_reset_postdata(); endif; ?>

How can I include the "external" posts in this code?
The theme then uses blocks to display content on the startpage, here is block8.php with a post query.
function block_eight_ajax_query($atts='') {
    $args = array (
$is_ajax = 0;
if($atts==''){
    $is_ajax=1;
    $atts=$_GET;
    if($atts['global_query']){
        unset($atts['no_found_rows']);
        unset($atts['suppress_filters']);
        unset($atts['cache_results']);
        unset($atts['update_post_term_cache']);
        unset($atts['update_post_meta_cache']);
        unset($atts['nopaging']);
    }
}
$atts['is_ajax'] = $is_ajax;
$query = null;
$query = new WP_Query( $atts );
$html = '';
if ( $query->have_posts() ) {
    ob_start();
    $i = 1;
    while ( $query->have_posts() ):
        $query->the_post();

        $atts['video'] = rd_field( 'abomb_post_video' );
        $atts['extern'] = rd_field( 'extern' );
        $atts['audio'] = rd_field( 'abomb_post_audio' );
        $atts['gallery'] = rd_field( 'abomb_post_gallery' );
        $atts['counter'] = $i;
        block_grid_content($atts);
        if ($atts['column'] == 'grid-12') { $divide = 1; }
        else if ($atts['column'] == 'grid-3') { $divide = 4; }
        else if ($atts['column'] == 'grid-4') { $divide = 3; }
        else { $divide = 2; }
        if ($i%$divide==0 && $divide!=1) {
            echo '

';
        }
        $i++;
    endwhile;
    if ($atts['nav'] == 'numbered') {
        echo '
';
            rd_pagination($query->max_num_pages);
        echo '
';
    }
    wp_reset_postdata();
    $html = ob_get_clean();
    if($is_ajax==1){
        echo $html;
        exit();
    }
    return $html;
}
else{
    if($is_ajax==1){
        echo '-11';
        exit();
    }
    return '';
}
}

Update: I added this code to functions:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() )
    $query->set( 'post_type', array( 'post', 'extern' ) );
return $query;
}

Now I can see the posts in for exampel the search result but I need the Query in Block8.php to fetch them aswell.
I Thanks!

A: To include a custom post type in the regular loop (ie. posts page) just add the following code to index.php before if ( have_posts() ) :
$args = array(
'post_type'   => array('post', 'custom_post_type'),
'post_status' => 'publish',
);
$new_post_loop = new WP_Query( $args );

then modify the following two lines:
if ( have_posts() ) : change it to if ( $new_post_loop -> have_posts() ) :
and
while ( have_posts() ) : the_post(); to while ( $new_post_loop -> have_posts() ) : $new_post_loop -> the_post();
This solution avoids the problem of having the custom post type listed in the all posts screen on the backend, which @David.J's answer produces ;)

A: Add this to your functions.php file.
/**
* @param WP_Query $query
* @return WP_Query
*/

function add_my_custom_post_type( $query ) {
    if ($query->is_main_query())
        $query->set( 'post_type', array( 'post', 'external' ) );
    return $query;
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );

Ref & duplicate: https://wordpress.stackexchange.com/questions/27104/how-to-display-regular-posts-custom-post-types-that-fall-under-a-category-usin

A: function add_my_custom_post_type( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ($query->is_main_query()) {
            $query->set( 'post_type', array( 'post', 'some_custom_post_type_name' ) );
        }
    return $query;
    }
}
add_action( 'pre_get_posts', 'add_my_custom_post_type' );

This is the correct way to write the code so as not to break the dashboard queries.


text:
Q: if conditional of number and its increment by 16 in iOS i have an integer called count , and i want it when it comes 1 or 17 or 33 to forever by the same sequence i.e count += 16
the first ball be unhidden , and the same thing when count comes to 2 or 18 or 34 to forever by the same sequence i.e count += 16 , the second ball to unhidden
at first i typed this code but it is very hard to type all numbers with their increments to the end in if condition
if(count == 1 || count == 17 || count == 33 || count == 49 || count == 65 || count == 81 || count == 97 || count == 113 || count == 129 || count == 145  || count == 161 || count == 177 || count == 193 || count == 209 || count == 225 || count == 241)
{
    _firstBall.hidden = NO;
}

if(count == 2 || count == 18 || count == 34 || count == 50 || count == 66 || count == 82 || count == 98 || count == 114 || count == 130 || count == 146  || count == 162 || count == 178 || count == 194 || count == 210 || count == 226 || count == 242)
{
    _secondBall.hidden = NO;
}

A: Try this:
if( ((count-1) % 16) == 0) {
    _first.hidden = NO;
}

if( ((count-2) % 16) == 0) {
    _secondBall.hidden = NO;
}

A: The % operator returns the integer remainder (or modulus). Your first sequence: 1, 17, 33 is 16 * n + 1 so the remainder when divided by 16 is 1. Similarly your second second sequence is 16 * n + 2.
So you can:
switch (count % 16) // switch on the remainder of division by 16
{
   case 1:
      _firstBall.hidden = NO; break;
   case 2:
      _secondBall.hidden = NO; break;
   // add more cases if needed
}


text:
Q: How to get the significance of coeficients in logistic regression using `ml_logistic_regression` I want to know the significance of each coefficient of a logistic regression model using spark function ml_logistic_regression. The code is as follows:
# data in R
library(MASS)
data(birthwt)
str(birthwt)
detach("package:MASS", unload=TRUE)

# Connection to Spark
library(sparklyr)
library(dplyr)
sc = spark_connect(master = "local")

# copy the data to Spark
birth_sc = copy_to(sc, birthwt, "birth_sc", overwrite = TRUE)

# Model
# create dummy variables for race (race_1, race_2, race_3)
birth_sc = ml_create_dummy_variables(birth_sc, "race")
model = ml_logistic_regression(birth_sc, low ~ lwt + race_2 + race_3)

The model I get is the following:
> model
Call: low ~ lwt + race_2 + race_3

Coefficients:
(Intercept)         lwt      race_2      race_3
 0.80575496 -0.01522311  1.08106617  0.48060322

In an R model you use summary and it gives you the significance of the coefficients, but if I use it with this model I get the same result:
> summary(model)
Call: ml_logistic_regression(birth_sc, low ~ lwt + race_2 + race_3)

Coefficients:
  (Intercept)         lwt      race_2      race_3
0.80575496 -0.01522311  1.08106617  0.48060322

How could get the significance of each variable in the model?

A: You just don't. None of the Spark's LogisticRegressionSummary variants provide feature importances, therefore these cannot be (and as pointed out by eipi10 is not) provided by sparklyr.

A: You might be able to get what you're looking for by using the Generalized Linear Model where the family == "Binomial." See http://spark.rstudio.com/reference/ml_generalized_linear_regression/ and the Spark Reference for more information: https://spark.apache.org/docs/2.1.0/ml-classification-regression.html#generalized-linear-regression


text:
Q: Can not customize hr module in openerp by adding additional fields I was trying to add a extra field in hr module i.e in hr.employee object by inheritance but when I'm adding that field ,in Hr module employee form my given field is not displayed .So pls help. All I want to do is create another seperate module so whenever that module is installed then that column should appear.(my field jdate should appear after coach_id field)
class joining_date(osv.osv):
   _name="joining.date"
   _inherit = "hr.employee"
   _columns={
          'jdate':fields.date('Joining date'),
          }

 joining_date()

xml part:
<?xml version="1.0" encoding="UTF-8"?>
  <openerp>
  <data>
     <record id="view_join_date" model="ir.ui.view">
     <field name="name">Join_date</field>
     <field name="model">joining.date</field>
     <field name="inherit_id" ref="hr.view_employee_form"/>
     <field name="arch" type="xml">
        <data>
        <xpath expr="//form/sheet/notebook/page/group[1]/group[2][@name='coach_id']" position="after">
            <field name="jdate"/>
        </xpath>
        </data>
      </field>
      </record>

openerp file:
{
'name': 'HR join date',
'version': '1.0',
'category': 'Tools',
'description': """ To add extra join date field""",
'author': 'Greywind',
'website': 'http://www.greywind.com',
'depends': ['hr','base', 'account_accountant'],
'data': [
         'joindate_view.xml'],
'demo': [],
'installable': True,
'auto_install': False,

}

A: I think your XML should look like this:
<record id="view_join_date" model="ir.ui.view">
    <field name="name">Join_date</field>
    <field name="model">joining.date</field>
    <field name="inherit_id" ref="hr.view_employee_form"/>
    <field name="arch" type="xml">
        <field name="coach_id" position="after">
            <field name="jdate"/>
        </field>
    </field>
</record>

A: Try to -name and -inherits field as the same id. if its so you can add your field in to the inherited module.
Then ref=base module view idand also if you want all the fields of your base module to your new module then you just change ref = **base module view id . new module view id  you should create the view for the new module with all the fields you needed from base & new field.
You should refer MrEthan Furman xml code.


text:
Q: ReactJS and Webpack Module Federation Application contains urls with undefined when deployed to cloudfront I have a micro-frontends app that consists of a container application with several remote applications. It is using ReactJS with Webpack 5 module federation and works fine on my local environment. However, when I deploy it to AWS CloudFront it doesn't work as expected.
It seems that the container app loads on the correct path but 'undefined' is added to the url  of the remoteEntry.js file of the remotes.
Please see screenshot below:

The container projects webpack production config is as follows:

const prodConfig = {
  mode: "production",
  output: {
    filename: "[name].[contenthash].js",
    publicPath: "/container/latest/",
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "container",
      remotes: {
        auth: `auth@${domain}/auth/latest/remoteEntry.js`,
        marketing: `marketing@${domain}/marketing/latest/remoteEntry.js`,
        dashboard: `dashboard@${domain}/dashboard/latest/remoteEntry.js`,
      },
      shared: packageJson.dependencies,
    }),
  ],
};

The remote projects webpack production config is as follows:

const prodConfig = {
  mode: "production",
  output: {
    filename: "[name].[contenthash].js",
    publicPath: "/marketing/latest/",
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "marketing",
      filename: "remoteEntry.js",
      exposes: {
        "./MarketingApp": "./src/bootstrap",
      },
      shared: packageJson.dependencies,
    }),
  ],
};

The container projects App.js is as follows:

import React, { lazy, Suspense, useState, useEffect } from "react";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import {
  StylesProvider,
  createGenerateClassName,
} from "@material-ui/core/styles";
import { createBrowserHistory } from "history";

import Progress from "./components/Progress";
import Header from "./components/Header";

const MarketingLazy = lazy(() => import("./components/MarketingApp"));
const AuthLazy = lazy(() => import("./components/AuthApp"));
const DashboardLazy = lazy(() => import("./components/DashboardApp"));

const generateClassName = createGenerateClassName({
  productionPrefix: "co",
});

const history = createBrowserHistory();

export default () => {
  const [isSignedIn, setIsSignedIn] = useState(false);

  useEffect(() => {
    if (isSignedIn) {
      history.push("/dashboard");
    }
  }, [isSignedIn]);

  return (
    <Router history={history}>
      <StylesProvider generateClassName={generateClassName}>
        <div>
          <Header
            onSignOut={() => setIsSignedIn(false)}
            isSignedIn={isSignedIn}
          />
          <Suspense fallback={<Progress />}>
            <Switch>
              <Route path="/auth">
                <AuthLazy onSignIn={() => setIsSignedIn(true)} />
              </Route>
              <Route path="/dashboard">
                {!isSignedIn && <Redirect to="/" />}
                <DashboardLazy />
              </Route>
              <Route path="/" component={MarketingLazy} />
            </Switch>
          </Suspense>
        </div>
      </StylesProvider>
    </Router>
  );
};

I am struggling to figure out where the error is. I am not sure if its an error with:

*

*React

*React Router

*Webpack Module Federation

*AWS CloudFront

Any help would be appreciated

A: If you look carefully at your browser logs.
There is a undefined/marketing/latest/remoteEntry.js in your url loading the module federated remote urls.
It is likely you need to setup your domain variable to be the cloudfront endpoint.

A: A little late,
Problem:
The problem is maybe you are just deploying the marketing app alone and the container app is not aware of marketing app changes until it is redeployed.
Solution;
All you need to do is just make changes to both Marketing and container app and commit to git to trigger a workflow for both apps.
hope this may help someone with same issue.


text:
Q: Does critical strike multiply the damage from items or only base damage? Does a critical strike multiply the whole player damage (including +damage from items) or only the base damage from stats ?
e.g. My hero has a base damage of 100 and a monkey king bar that gives +88 damage. Normally I will hit for 188 damage, if I proc a 200% critical strike damage, will I do (100*2)+88 = 288 dmg or (100+88)*2 = 376dmg ?
Bonus question : will the bash damage from the MKB be multiplied by the critical stike ?

A: From the wiki:

Because critical strike multiplies the attack damage of a unit, after attack damage modifiers, it is a scaling ability (unlike the damage of Monkey King Bar's mini-bash ability).

Since it is mentioned that it is a scaling ability, it can safely be concluded that critical strikes multiply the whole player damage, including +damage from items and attack modifiers.

Bashes and Critical Strikes can proc on the same attack, and are never multiplied.

As seen from the above, both Bash and Critical Strike can proc on one hit, but the damage from Bash will not critically hit and is counted as additional source of damage.


text:
Q: Minimize code for getElementById / getElementsByClassName I have 2 blocks of code that originally forms 120 lines of code with a lot of repitions. I also foresee that the code lines will grow. Below you find a minimal extraction.
Question:
Is it possible to iterate over [getElementById] and [getElementsByClassName] ?
Or should I break up the text in strings and construct new strings using variables?
Could "template literals" be a solution by embedding expressions in the strings?

There are some difference in the lines that needs to change: The number, the subset [x] and "block"/"none".
function display_page_2_button_1() {
    document.getElementById("show_services_inline_1").style.display = "block";
    document.getElementById("show_services_inline_2").style.display = "none";
}

function display_page_4_button_1() {
    document.getElementsByClassName("show_demos_inline_1")[0].style.display = "block";
    document.getElementsByClassName("show_demos_inline_1")[1].style.display = "block";
    document.getElementsByClassName("show_demos_inline_2")[0].style.display = "none";
    document.getElementsByClassName("show_demos_inline_2")[1].style.display = "none";
}

A: Short answer: yes, you can use string literals for this.
Long answer:
If possible I would change the setup slightly to have all the elements include a more generic class (show_demos_inline) or use a data attribute and querySelecrorAll, which you can then iterate over.
Using some simple logic could then differentiate between block/none depending on what you are trying to do.  Proably you only want one element to show? You could pass some identifier for this element to the function and check on it during the loop.

A: Below code minimize the amount of code lines (assuming that the startpoint is +120 lines). It also copes with growth of amount of divs.
A function is created at the beginning of the script to first close all divs. Each [display_page_2_button_X] function then only make one div visible.
It use "template literals" to adapt the code so that I can run the string in a for-loop.
The code for [services]:
service = "show_services_inline_";

function hide_all_services_div() {
    for (i = 1; i < 6; i++) {
        document.getElementById(`${service}${i}`).style.display = 'none';
    }
}

function display_page_2_button_1() {
    hide_all_services_div();
    document.getElementById(`${service}1`).style.display = "block";
}

The code for [demos]:
demo = "show_demos_inline_";

function hide_all_demos_div() {
    for (i = 1; i < 6; i++) {
        document.getElementsByClassName(`${demo}${i}`)[0].style.display = "none";
    }

    for (i = 1; i < 6; i++) {
        document.getElementsByClassName(`${demo}${i}`)[1].style.display = "none";
    }
}

function display_page_4_button_1() {
    hide_all_demos_div();
    document.getElementsByClassName(`${demo}1`)[0].style.display = "block";
    document.getElementsByClassName(`${demo}1`)[1].style.display = "block";
}


text:
Q: appcelerator - Interactive Notifications I use two different events for notification push, first is usernotificationsettings, second is remotenotificationaction when i put category in payload. the probleme is when i use an interactive notification the event remotenotificationaction does not respond, only usernotificationsettings.
first event

Ti.App.iOS.addEventListener("usernotificationsettings", registerForIOS8Push);

second event for interactive Notifications

Ti.App.iOS.addEventListener('remotenotificationaction', remotenotificationaction);

A: The two events are very different. The first one will be fired when registerUserNotificationSettings is done. The second one will be fired when the user selects an action from an interactive notification.


text:
Q: What is the best way to programmatically log into a web site in order to screen scrape? (Preferably in Python) I want to be able to log into a website programmatically and periodically obtain some information from the site. What is the best tool(s) that would make this as simple as possible? I'd prefer a Python library of some type because I want to become more proficient in Python, but I'm open to any suggestions.

A: You can try Mechanize (http://wwwsearch.sourceforge.net/mechanize/) for programmatic web-browsing, and definitely use Beautiful Soup (http://www.crummy.com/software/BeautifulSoup/) for the scraping.

A: Most of us use urllib2 to get the page; it can handle various forms of authentication and cookie collection.  Then Beautiful Soup to parse the results.

A: I once wrote a Python script to automatically log into vBulletin forums. The difficult part was knowing how to correctly form the login request and that is something that a library won't help you with. I found Live Http Headers - an addon for Firefox - to be pretty helpful in seeing what is sent between the client and server during the login process.
I also agree with everyone else that Beautiful Soup is pretty awesome.

A: i recommend using twill it makes it a snap to do the login procedure.  then use beautifulsoup etc.
 as described above. ive never tried mechanize, but it looks pretty good.

A: just for screen scraping you can use combination of url lib + pyqyery.
https://pythonhosted.org/pyquery/


text:
Q: more sopisticated python post request (web scraping) I'm trying to acquire some data from polish gas system operator website.
Here is a site: http://en.gaz-system.pl/customer-zone/transmission/
Then link to "nominations"
Host is: https://swi.gaz-system.pl/swi/public/embed.seam
Then I change Data (From) and click Filter button
I want to use Python and request module.
My simple code:
    import requests
    swi_url = 'https://swi.gaz-system.pl/swi/public/embed.seam?viewId=E_PUB_043NN&lang=en'

    payload = {
    "embedsubview:subview_nomination_list_id:form_nomination_table_list_id":"embedsubview:subview_nomination_list_id:form_nomination_table_list_id",
    "embedsubview:subview_nomination_list_id:form_nomination_table_list_id:j_id17":"Filtruj",
    "embedsubview:subview_nomination_list_id:form_nomination_table_list_id:nominationTable:dayFromField:dayFromInputDate":"2015-01-01",
    "embedsubview:subview_nomination_list_id:form_nomination_table_list_id:nominationTable:dayToField:dayToInputDate":"2015-10-20",
     }

    r = requests.post(swi_url, data=payload)
    a = r.text
    print(a)

Response is not what I expect, because it returns the data of today's date
What should be improved?

A: That page HTML is not from a raw PHP or HTML document, but it seems to be dinamically generated from javascript scripts. You need to use selenium, Phantom JS, or Casper JS to scrape that.


text:
Q: DocuSign JWT Auth Error while requesting server, received a non successful HTTP code Error with response Body C# sdk I am trying to integrate docusign rest api in my web application where my .net version is 4.7.2. I have used docusign dll of version 5.2.0.
I am trying to get access token using jwt auth type. So I set up app, integrator key and rsa private key for app.
                var scopes = new List<string>{"impersonation","signature"}

                string directorypath = Server.MapPath("~/App_Data/" + "Files/");
                string fileNameOnly = "docusign_private_key.txt";

                var filePath = Path.Combine(directorypath, fileNameOnly);
                var privateKeyBytes = System.IO.File.ReadAllBytes(filePath);

                var apiClient = new ApiClient();
                var authToken = apiClient.RequestJWTUserToken
                    (
                        clientId: credential.ClientID,
                        userId: credential.UserID,
                        oauthBasePath: credential.BasePath,
                        privateKeyBytes: privateKeyBytes,
                        expiresInHours: 1,
                        scopes: scopes
                    );

I used integrator key as clientId, API Username as UserId, https://demo.docusign.net/restapi as oauthBasePath. Is there anything I forgot to mention or make mistake? I am not able to get access token. It throws ApiException with message Error while requesting server, received a non successful HTTP code Error with response Body

A: To generate JWT token in demo environment, change your oauthBasePath to account-d.docusign.com ( authentication server ). You can read more here. https://demo.docusign.net/restapi is the application base path you can use to make calls to all eSignature endpoints.


text:
Q: generate dropdown using values from another table in asp.net. vb mvc 4 I have created model class and controller related to a database table and want to populate a dropdown list from another table. my model and controller code is below:-
Imports System.Data.Entity

Namespace employee1
   Public Class EmployeeController
       Inherits System.Web.Mvc.Controller

       Private db As New EmployeeDBContext
       '
       ' GET: /Employee/

       Function Index(ByVal sortOrder As String) As ActionResult
           ViewBag.LastNameSortParm = If(String.IsNullOrEmpty(sortOrder), "LastName_desc", String.Empty)
           Dim Employee = From e In db.Employee Select e
           Select Case sortOrder
               Case "LastName_desc"
                   Employee = Employee.OrderByDescending(Function(e) e.LastName)
               Case Else
                   Employee = Employee.OrderBy(Function(e) e.LastName)
           End Select
           Return View(Employee.ToList())
       End Function

       '
       ' GET: /Employee/Details/5

       Function Details(Optional ByVal id As Integer = Nothing) As ActionResult
           Dim employeemodel As EmployeeModel = db.Employee.Find(id)
           If IsNothing(employeemodel) Then
               Return HttpNotFound()
           End If
           Return View(employeemodel)
       End Function

       '
       ' GET: /Employee/Create

       Function Create() As ActionResult
           Return View()
       End Function

and this is my model
Imports System.Data.Entity
Public Class EmployeeModel
   Public Property ID() As Integer
   Public Property CompanyCode() As String
   Public Property FirstName() As String
   Public Property LastName() As String
   Public Property DeptNum() As String
   Public Property Status() As Char
   Public Property txtCity() As String
   Public Property txtState() As String
   Public Property txtZip() As String
   Public Property txtPhone() As String
   Public Property txtPhoneExt() As String
   Public Property LastReviewDate() As Date
   Public Property HireDate() As Date

End Class

Public Class EmployeeDBContext
   Inherits DbContext
   Public Property Employee() As DbSet(Of EmployeeModel)

End Class

I want a dropdown list in create view for status from another table named IDStatus view is like
@Using Html.BeginForm()
   @Html.ValidationSummary(True)
   @<fieldset>
       <legend>EmployeeModel</legend>

           @Html.LabelFor(Function(model) model.CompanyCode)

           @Html.EditorFor(Function(model) model.CompanyCode)
           @Html.ValidationMessageFor

   </fieldset>
End Using

A: Either you can add one more property as a collection of the same model, or you can fill that collection in a ViewBage and use it the same at your view.
At Controller
ViewBag.DropDownCollection = "Collection"

At View
@Html.DropDownList("dropDownName",ViewBag.DropDownCollection)

Fiddle

A: create viewmodel and pass both table properties in that
public class viewmodel
{
public table1 Table1{get;set;}   //return your first table properties here
public table2 Table2{get;set;}   //return your second table properties here
}

In view
@htnl.dropdownlistfor(m=>m.Table2.propertyname,-----)`enter code here`


text:
Q: What is the $\lim_{n\to \infty} {\sqrt[n]{(1+1/n)(1+2/n)...(1+n/n)}}$ Because $(1+\frac{k}{n})\leq (1+\frac{1}{n})^k$ $$ {\sqrt[n]{(1+1/n)(1+2/n)...(1+n/n)}}\leq\sqrt[n]{(1+\frac{1}{n})^{n(n+1)/2}}=(1+\frac{1}{n})^{(n+1)/2}$$ and so $$\lim_{n\to \infty}{\sqrt[n]{(1+1/n)(1+2/n)...(1+n/n)}}<\sqrt{e}$$
But what is the exact limit?

Added: I Gave this to Wolfram and the answer was $\infty$ ! but why?

A: You can apply Cauchy's limit theorem
$$\lim_{n \to \infty} \sqrt[n]{a_n} = \lim_{n \to \infty} \frac{a_{n+1}}{a_n},$$
with
$$a_n = (1+1/n)(1+2/n)…(1+n/n) = \frac{(2n)!}{n! n^n}.$$
Then
$$\frac{a_{n+1}}{a_n} = \frac{(2n+2)!}{(n+1)!(n+1)^{n+1}}\frac{n!n^n}{(2n)!} \\ = \frac{(2n+2)(2n+1)n^n}{(n+1)(n+1)^{n+1}} \\ = 2\frac{(2 + 1/n)}{(1+1/n)}\frac{1}{(1+1/n)^n},$$
and
$$\lim_{n \to \infty}\sqrt[n]{a_n} = \lim_{n \to \infty}\frac{a_{n+1}}{a_n} = 2 \cdot 2 \cdot \frac{1}{e} = \frac{4}{e}$$

A: Take logarithm:
$$\frac1n \sum_{k=1}^n \log \left( 1 + \frac{k}n\right)$$
which converges (using Riemann sums) to:
$$\int_0^1 \log(1+x) dx = 2\log 2 - 1$$
Therefore the original limit is:
$$e^{2 \log 2 -1} = 4/e$$