text:
Q: Overwrite a function in R. Avoiding infinite recursion I want to override some function in R, adding feature to them or modifying their behavior. For example I can't stand that for min, max, mean, sd and others the na.rm argument is false by default, or that if you run as.numeric on a factor it doesn't parse the level text but the level identifier.
So I want to rewrite it:
as.numeric <- function(x) {
    if(is.numeric(x)) return(x)
    if (is.factor(x)) x <- as.vector(x)

    as.numeric(x)
}

Unfortunately this trigger an infinite recursion (of course). How do I solve this problem?

A: If you're careful about isolating names (and unfortunately R doesn't encourage this), there's no reason against overriding existing names.
In your case, all you have to do is explicitly qualify the package name of the function you want to call, to disambiguate it:
as.numeric <- function(x) {
    if(is.numeric(x)) return(x)
    if (is.factor(x)) x <- as.vector(x)

    base::as.numeric(x)
}

That said, I'd use this judiciously.
If you find yourself shadowing existing function names a lot, you should think about isolating your names in their own namespace. You can use modules to do this properly.


text:
Q: google.android.gms:play-services-oss-licenses not working after obfuscation I'm working on a personal android application. I can't start OssLicensesMenuActivity after obfuscating. Application crashes. It works fine without obfuscation.
startActivity(new Intent(getContext(), com.google.android.gms.oss.licenses.OssLicensesMenuActivity.class));

Here is my release configuration:
release {
            minifyEnabled true
            debuggable true
            shrinkResources true
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

I added this line to proguard-rules.pro:

-keep class com.google.android.gms.oss.licenses.** { *; }

Also, I couldn't see a proguard documentation in the official guide:
https://developers.google.com/android/guides/opensource
Only release version of my app crashes. The error below is from Logcat.
Can you help me why this error occurs, and what is the solution?
2019-04-21 13:03:01.051 com.myapp.myapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.myapp.myapp, PID: 10763
    android.view.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class x
    Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class x
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.x" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.myapp.myapp-pBk73fi1FLACrYcen4kXlg==/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.myapp-pBk73fi1FLACrYcen4kXlg==/lib/arm64, /data/app/com.myapp.myapp-pBk73fi1FLACrYcen4kXlg==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.view.LayoutInflater.createView(LayoutInflater.java:606)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:703)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:68)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at com.google.android.gms.oss.licenses.zzp.onComplete(:18)
        at com.google.android.gms.tasks.zzj.run(:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7045)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)

A: OK i found the problem. I keep drawable resources in res/raw/keep.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:shrinkMode="strict"
    tools:keep="@drawable/*"/>

I removed the tools:shrinkMode="strict" and problem solved. Everything works fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does android ImageSpan show my picture twice (when setBounds exceed certain magic width)? Here is my code to put an ImageSpan in an EditText.
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    EditText et = (EditText) getActivity().findViewById(R.id.html_text);

    SpannableString ss = new SpannableString("ABC");
    Drawable d = getResources().getDrawable(R.drawable.ic_launcher);

    d.setBounds(0,0,2256,760);

    ImageSpan span = new ImageSpan(d, "haha", ImageSpan.ALIGN_BASELINE);
    ss.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    et.setText(ss);
}

While playing around, I noticed something strange.  My AVD is 2560x1600.  When the setBounds call with width less or equal to 2256, the picture is showing correctly.  But for width larger than 2256, the picture is shown twice.!  The magic value is the same for different pictures.  I also tried AVD with different size.  For 720x1080, the magic width is 608.  What is this magic width?  How can I make sure my picture doesn't exceed this magic width?
BTW, here is the layout for the EditText:
<EditText
    android:id="@+id/html_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

A: this worked for me
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matn_activity3);
Display display = getWindowManager().getDefaultDisplay();
     width = display.getWidth();  // deprecated
     height = display.getHeight();  // deprecated
 SpannableString ss = new SpannableString("ABC");
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
double ratio= (double)((double)(d.getIntrinsicWidth())/(double)(d.getIntrinsicHeight()));
//this shows the original ratio of image

                if(d.getIntrinsicWidth()<width){
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                Log.v("small","small");
                }else{
                    Log.v("big","big");
                    d.setBounds(0, 0,(int)(width*.95),(int)(d.getIntrinsicHeight()/ratio*.95));
//i dont know why but if you put 1 instead of .95 again you will see 2 images
//this is exactly the magic width you have said
                }
}

it may have little problems because my project is  big and different i cant put the exact code
.but it generally works


text:
Q: Question about a differentiable function at point $a$. Let $f$ be differentiable at point $a$. Prove than if $\lim \limits_{n \to \infty}x_n =\ a^{+}$ and $\lim \limits_{n \to \infty}y_n = a^{-}$ then $$\lim \limits_{n \to \infty} \frac{ f(x_n) - f(y_n)}{x_n - y_n} = f'(a)$$
I thought about proving this by using lagrange's theorem, but I didn't know where to go with this because the question has limit and its talking about one point, not an interval.
Is there any ideas how to solve this question?

A: Since $f$ is differentiable on $a$ then
$$f(x_n)=f(a)+(x_n-a)f'(a)+(x_n-a)\epsilon_1(x_n)$$
where $\epsilon_1(x_n)\xrightarrow{n\to\infty}0$ and similarly we have
$$f(y_n)=f(a)+(y_n-a)f'(a)+(y_n-a)\epsilon_2(y_n)$$
where $\epsilon_2(y_n)\xrightarrow{n\to\infty}0$. Now subtracting the two equalities and we get
$$f(x_n)-f(y_n)=(x_n-y_n)f'(a)+\underbrace{(x_n-a)\epsilon_1(x_n)-(y_n-a)\epsilon_2(x_n)}_{=R_n}$$
$$R_n=(x_n-y_n)\epsilon_1(x_n)+(y_n-a)(\epsilon_1(x_n)-\epsilon_2(y_n))$$
and notice that
$$0\le a-y_n=\underbrace{(a-x_n)}_{\le0}+(x_n-y_n)\le x_n-y_n$$
Can you take it from here?

A: Using algebraic manipulation we may write
$$\begin{align}\frac{f(x_n) - f(y_n)}{x_n - y_n} &= \frac{[f(x_n) - f(a)] - [f(y_n) - f(a)]}{x_n - y_n} = \frac{f(x_n) - f(a)}{x_n-y_n} - \frac{f(y_n) - f(a)}{x_n - y_n}\\&=\underbrace{\Bigg(\frac{x_n - a}{x_n - y_n}\Bigg)}_{t_n}\frac{f(x_n) - f(a)}{x_n-a} + \Bigg(\frac{(x_n - x_n) -(y_n - a)}{x_n - y_n}\Bigg)\frac{f(y_n) - f(a)}{y_n-a}\\&=t_n\underbrace{\frac{f(x_n) - f(a)}{x_n-a}}_{\to f'(a)} + \Big(1 - t_n\Big)\underbrace{\frac{f(y_n) - f(a)}{y_n-a}}_{\to f'(a)} \end{align}$$
Notice that $$y_n < a \Rightarrow x_n - a < x_n - y_n \Rightarrow \frac{x_n - a}{x_n - y_n} < 1$$ then the sequence $\{t_n\}$ is bounded and $0 < t_n < 1$. Then
$$\lim_{n \to \infty}\frac{f(x_n) - f(y_n)}{x_n - y_n} = \lim_{n \to \infty}t_n\underbrace{\frac{f(x_n) - f(a)}{x_n-a}}_{\to f'(a)} + \Big(1 - t_n\Big)\underbrace{\frac{f(y_n) - f(a)}{y_n-a}}_{\to f'(a)} = f'(a)$$


text:
Q: Real-time sensor data as Server-Sent Events (SSE) from Python through PHP? I'm in the process of updating a web app presenting real-time sensor data, which in it's current first iteration does this by continuous AJAX polling.
However, in order to make this more like a 'true real-time' app, I would like it to be event-based.
I've been reading up on event-based techniques, and based on the fact that the real-time communication only has to go one way (server - > client), I have chosen to go with Server-Sent Events (SSE) for now instead of something like websockets.
As described here on the Mozilla Docs, this is easily implemented on the server side with something like (a little simplified):
<?php
// SSEscript.php
date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream\n\n");

while (1) {
   if ($new_data_available) {
      echo "data:". $data;
   }

   sleep($short_time_to_spare_cpu);
}
?>

and on the client side with:
<script>
var evtSource = new EventSource("SSEscript.php");

evtSource.onmessage = function(e) {
   var data = e.data;
   // Do something with data object
}
</script>

All the above works fine for me.
However, the sensor data is initially retrieved by a Python script running continuously on the server, so how do I transfer the sensor data from the Python script to the PHP script IMMEDIATELY when it is retrieved, so that an event can be generated and sent?
Can I do something like depicted below? :

At the same time all new data is stored in a MySQL db, so I could of course make the PHP script query the db really often for new entries, but there has to be a smarter way. So can I make 2.1 and 2.2 in the image happen at the same time?
All the answers I could find in here describes how data can be transferred by making the PHP execute the Python script, but that is not what I want as this has to run whether or not a user asks for data.
Is a kind of socket the way to go, and if so, can you point me in the direction of how to do so?
I hope you can help me out!

A: I use redis to do the signalling between python and redis. After python do all the stuffs, rpush a token (or the latest data) into a redis queue. In the PHP I use a while(true) loop to hold the request and redis lpop(queue,timeout) to wait for the token, and send data out, something like this:
<?php
    require __DIR__.'/predis-1.0/autoload.php';
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Connection: keep-alive");

    $lastId = isset($_SERVER["HTTP_LAST_EVENT_ID"]) ?
              $_SERVER["HTTP_LAST_EVENT_ID"] : null;
    if (isset($lastId) && !empty($lastId) && is_numeric($lastId)) {
        $lastId = intval($lastId);
        $lastId++;
    }

    $index = isset($_GET['index']) ? $_GET['index'] : null;

    echo "retry: 2000\n";

    $client = new Predis\Client();
    while (true) {
        $data = $client->blpop('queue',5);
        if ($data) {
            error_log("$index : " . strlen($data));
            sendMessage($lastId, $data);
            $lastId++;
        }
    }

    function sendMessage($id, $data) {
        echo "id: $id\n";
        echo "data: $data\n\n";
        ob_flush();
        flush();
    }


text:
Q: Bug or why? Null being displayed as a space in a string. (FromCharacterCode ASCII) I expect Print[FromCharacterCode[{97, 0, 97}, "ASCII"]]
output to look the same as Print[FromCharacterCode[{97, 97}, "ASCII"]], but instead it looks like Print[FromCharacterCode[{97, 32, 97}, "ASCII"]].
I see that the "Null space" is being handled differently; FromCharacterCode[{0}, "ASCII"] == FromCharacterCode[{32}, "ASCII"] outputs False. But why would it display anything in the first place?
Non ASCII seems to work as I expect."a"~StringJoin~"\[Null]"~StringJoin~"a" outputs without displaying a separation but still keeping a Null in the middle. BTW I had to type it in backwards to avoid \[Nu]. And it works as I expect with "UTF-8". ex: FromCharacterCode[{97, 97, 239, 142, 160, 97}, "UTF-8"].
I will be switching to UTF-8 but just curious about ASCII.

A: This is likely to be a font issue; both Consolas and Source Code Pro are used as the default code font on at least some Mathematica versions.

You can check your current set code font:
CurrentValue[{StyleHints, "CodeFont"}]

(* "Source Code Pro" *)

(That's on my Mac running v13.2.1.)
Only even semi-sensible reason for having different fonts on different platforms that I can come up with is that Consolas might render just a bit better on the Windows platform. No idea if that's the rationale chosen by WRI, though.


text:
Q: remove dead jobs from nomad status I was running a cron (periodic) job through nomad which ran every 30 sec, the job does nothing but just
echo "some string"
and hence ends immediately
when I do
nomad status
I get all the dead jobs also-- the jobs that have finished executing, which are useless to me. Is there some way to remove the dead jobs?
PS: one obvious solution is to grep out the dead jobs, any solution provided by nomad?

A: Dead/Completed jobs are cleaned up in accordance to the garbage collection interval.
You can force garbage collection using the System API endpoint which will run the global garbage collector. The CURL command would look like:
$ curl -X PUT http://localhost:4646/v1/system/gc

If you wish to lower the GC interval permanently for jobs, you can use the job_gc_threshold configuration parameter within the server config stanza.


text:
Q: How to install emerald package on Mint? How can I install the Emerald package on Mint? I cannot seem to find and install it in the Synaptic Package Manager. I think the repository of this package is missing. But I don't know where it is and how to add it to the current list of repositories.

A: The emerald window decorator isn't available in the Ubuntu official repositories(Mint included) anymore, unfortunately, but there are other way to acquire it.
I am not aware of any PPAs for Precise, but building it from source is really straightforward. Here's a basic guide for 12.04:
http://iamfuss.deviantart.com/journal/Install-emerald-for-Ubuntu-12-04-292806813


text:
Q: Static member accessed via instance reference (using 'this' keyword) public class RoundCapGraph extends View {
   static private int strokeWidth = 20;

   public void setStrokeWidth(int strokeWidth){
       this.strokeWidth = strokeWidth;
       //warning : static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference
   }
}

In android studio I'm trying to set strokeWidth using setStrokeWidth.
But I get warning
static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference
Question : Does 'this' keyword make new instance and access variable via new instance?
EDITED : I don't really need to set strokeWidth variable static, but I want to understand why using 'this' keyword produce particular warning

A: this keyword doesn't create a new instance, but this. is usually used to access instance variables.
Therefore, when the compiler sees that you try to access a static variable via this., it assumes that you might have made a mistake (i.e. that your intention was to access an instance variable), so it warns about it.
A better way to access the static variable is:
RoundCapGraph.strokeWidth = strokeWidth;

EDIT: you are setting your static variable within an instance method. This is a good indication that the compiler was right in warning you about accessing the static variable as if it was an instance variable.
You should set static variables via static methods, and set instance variables via instance methods.

A: When you access static member using object's instance, the instance gets replace by Class. i.e this.strokeWidth would be replace with RoundCapGraph.strokeWidth
There will be no NullPointerException due to the instance replacement.
I found a reference to this in the Java Specification: Chapter 15, Section 11: Field Access Expressions.

Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception

public class RoundCapGraph extends View {
   static private int strokeWidth = 20;

   public void setStrokeWidth(int strokeWidth){
       RoundCapGraph roundCapGraph = null;
       roundCapGraph.strokeWidth = strokeWidth; // NullPointerException?
       //warning : static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference
   }
}

A: Correct, Static members belong to the class not to an instance.


text:
Q: Getting UITableViewCell from UITapGestureRecognizer I have a UITableView with multiple sections and in my cellForRowAtIndexPath method I add a UITapGestureRecognizer to the cell's imageView (each cell has a small image). I have been successful in accessing that image (in order to change it) by using:
var imageView : UIImageView! = sender.view! as UIImageView

What I need to do now, however, is access the cell's data, which I believe means I need to be able to access the cell in order to get the section and row number. Can anyone advise on how to do this? The idea is that I am changing the image to an unchecked checkbox if the task is done, but then in my data I need to actually mark that task as done.

A: You can get the position of the image tapped in order to find the indexPath and from there find the cell that has that image:
var position: CGPoint =  sender.locationInView(self.tableView)
var indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(position)!
var cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)

A: In your function that handles the tap gesture recognizer, use tableView's indexPathForRowAtPoint function to obtain and optional index path of your touch event like so:
func handleTap(sender: UITapGestureRecognizer) {
    let touch = sender.locationInView(tableView)
    if let indexPath = tableView.indexPathForRowAtPoint(touch) {
        // Access the image or the cell at this index path
    }
}

From here, you can call cellForRowAtIndexPath to get the cell or any of its content, as you now have the index path of the tapped cell.

A: You're missing that you can use the Delegate design pattern here.
Create a protocol that tells delegates the state changes in your checkbox (imageView):
enum CheckboxState: Int {
    case .Checked = 1
    case .Unchecked = 0
}

protocol MyTableViewCellDelegate {
    func tableViewCell(tableViewCell: MyTableViewCell, didChangeCheckboxToState state: CheckboxState)
}

And assuming you have a UITableViewCell subclass:
class MyTableViewCell: UITableViewCell {

    var delegate: MyTableViewCellDelegate?

    func viewDidLoad() {

        // Other setup here...

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapImage:")
        imageView.addGestureRecognizer(tapGestureRecognizer)
        imageView.userInteractionEnabled = true
    }

    func didTapImage(sender: AnyObject) {

        // Set checked/unchecked state here
        var newState: CheckboxState = .Checked // depends on whether the image shows checked or unchecked

        // You pass in self as the tableViewCell so we can access it in the delegate method
        delegate?.tableViewCell(self, didChangeCheckboxToState: newState)
    }

}

And in your UITableViewController subclass:
class MyTableViewController: UITableViewController, MyTableViewCellDelegate {

    // Other methods here (viewDidLoad, viewDidAppear, etc)...

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
        var cell = tableView.dequeueReusableCellWithIdentifier("YourIdentifier", forIndexPath: indexPath) as MyTableViewCell

        // Other cell setup here...

        // Assign this view controller as our MyTableViewCellDelegate
        cell.delegate = self

        return cell
    }

    override func tableViewCell(tableViewCell: MyTableViewCell, didChangeCheckboxToState state: CheckboxState) {

        // You can now access your table view cell here as tableViewCell

    }

}

Hope this helps!

A: Get tableView's cell location on a specific cell. call a function which holds the gesture of cell's Objects Like UIImage or etc.
let location = gesture.location(in: tableView)
   let indexPath = tableView.indexPathForRow(at: location)
   Print(indexPath.row)
   Print(indexPath.section)


text:
Q: How to add Double in ireport All I wanted to do is add variables which are both Double data type.
"$V{iAmt} + V{iFee}"
But error is "illegal use of null value or 'null' literal;".

A: Try to fill your textfield with:
//if your variables are strings:
new Double(Double.parseDouble($V{iAmt}) + Double.parseDouble($V{iFee}))

//if your variables are already double
new Double($V{iAmt} + $V{iFee})

// checking nulls
new Double(($V{iAmt} != null ? $V{iAmt} : 0) + ($V{iFee} != null ? $V{iFee} : 0));

A: You can try something like this
  $V{iAmt}.doubleValue() + V{iFee}.doubleValue()


text:
Q: Setting up jwt or oauth in web application I'm buliding a new spa app using angular 4 and I've started to search for different options for implementing security. As I dived deeper I found every mechanisim very vulnerable to basic attacks. I wonder what is the most rewarding way to implement security in a small web application without the deep need for background knowledge in security world. here is my thoughts and questsions:

*

*Using a session , the cookie can be very easly stolen using a simple CSRF.

*Using a token based approach, I found to have few options and drawbacks.

*

*Create a token and save expiration in database , on each request to server ,server will increase the expiration in X time.
This solution is very dangerous. if malicious user steals the token , he can easly keep it alive forever.

*OAuth2 - use a refresh_token with access_token. This is great protocol for server where the refresh_token can be saved in server side. the problem is that both the access_token and refresh_token will be saved in client side in the same place. It will be easy to steal the refresh_token as it will be with the access_token using a simple XSS.

*token with non expended expiration- after user will be authetnicated, he will recive a token with expiration of X minutes. after expiration, user will be navigated to login page. This is awful in product point of view, but the easiest to implement and the most secure in my not-professional-at-all opinon.

*Storage-where to save the tokens/sessionId?

*

*local storage - very easy to steal using simple xss, or someone with access to computer.

*session storage- same as above , but with shorter living time.

*cookie - easly can be stolen by simple CSRF or simple xss

*cookie (Http-Only) - not sure about CSRF but blocks javascript access only in some of the browsers (if I understand correctly)

*My suggestion (Will really like feedback)
  I thought about using some kind of symetric encryption in the client side.
  When I will get the token from server I will encrypt it with some accessable data like browsertpye,operation etc... Although the encryption algorithm will be in the client, the javascipt is obfuscated which will add one more layer of difficulty to hack.
We build a web application with a low budget, and can't efford spending to much time on this. Is there an elegant solution?

A: We use tokens and they are great! Your fears are the same fears I had but here are a couple things to remember.

*

*If you are saving any "state" information on the server, the point of using a token just went out the window. The whole point is to simplify and reduce the footprint of the "authentication/authorization" system on the server. Tokens were the answer in that once the server signs it and sends it, there's nothing remaining on the server until it has to verify it for an incoming request.

*Use HTTPS. This way unless someone gains physical access to a computer with a valid token, and further knows what they are looking for and how to extract it, the likelihood of someone replaying a token is low. This particular fear is one we developers like to blow way out of the realm of reasonable probability.

*If security is that big of a deal, make your tokens expire after 24 hours, period. Don't worry about resetting their expiry. Most people don't care about logging back into a system, especially if the interval is reasonable.

*Your token server should have certain security levers built in. If you suspect that a number of tokens have been owned, the server should be able to be restarted, and generate it's own token secret on every boot up, this will invalidate any token out there (the big red button, if you will).

*Save as little information in the token as possible, it's not mobile storage. In fact your client shouldn't even be able to decrypt the token.


text:
Q: angularjs not caching resource data . ( even after using cacheFactory ) I am trying to cache the response with angularjs but its not happening .
code #1
var app = angular.module("jsonService", ["ngResource"]);

app.factory("JsonFactory", function($resource,$cacheFactory) {
    var cache = $cacheFactory('JsonFactory');

    var url = "myurl?domain=:tabUrl";

    var data = cache.get(url);

    if (data==undefined) {
    var retObj = $resource(url, {}, {
        list: {
            method: "GET",
            cache: true
        }
    });
    data = retObj;
    cache.put(url, data);
    };
    return cache.get(url);
});

code #2
var app = angular.module("jsonService", ["ngResource"]);

app.factory("JsonFactory", function($resource) {

    var url = "myurl?domain=:tabUrl";
    console.log(url);

    var retObj = $resource(url, {}, {
        list: {
            method: "GET",
            cache: true
        }
    });
    return retObj;
});

after both the code i wrote . when looking in to dev tools there always goes a XHR request in Network tab.
obviously : date does not changes . ( that's the whole point of caching )

A: After reading some of your responses, I think that what you are asking, is why does the network tab show a 200 response from your server, while using angular caching.
There are two caches. The first cache is angular's cache. If you see an xhr request in the network tab at all, then that means angular has decided that the url does not exist in its cache, and has asked the browser for a copy of the resource. Furthermore, the browser has looked in it's own cache, and decided that the file in its cache does not exist, or is too old.
Angular's cache is not an offline cache. Every time you refresh the browser page, angular's caching mechanism is reset to empty.
Once you see a request in the network tab, angular has no say in the server response at all. If you're looking for a 304 response from the server, and the server is not providing one, then the problem exists within the server and browser communication, not the client javascript framework.
A 304 response means that the browser has found an old file in its cache and would like the server to validate it. The browser has provided a date, or an etag, and the server has validated the information provided as still valid.
A 200 response means that either the client did not provide any information for the server to validate, or that the information provided has failed validation.
Also, if you use the refresh button in the browser, the browser will send information to the server that is guaranteed to fail (max-age=0), so you will always get a 200 response on a page refresh.

A: According to the documentation for the version of angular that you are using, ngResource does not support caching yet.
http://code.angularjs.org/1.0.8/docs/api/ngResource.$resource
If you are unable to upgrade your angular version, you may have luck configuring the http service manually before you use $resource.
I'm not exactly sure of syntax, but something like this:
yourModule.run(function($http)
{
    $http.cache=true;
});

A: $cacheFactory can help you cache the response. Try to implement the "JsonFactory" this way:
app.factory("JsonFactory",function($resource,$cacheFactory){
    $cacheFactory("JsonFactory");
    var url="myurl?domain=:tabUrl";

    return{
      getResponse:function(tabUrl){
        var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
        var response=cache.get(tabUrl);
        //if response is not cached
        if(!response){
          //send GET request to fetch response
          response=retObj.list({tabUrl:tabUrl});
          //add response to cache
          cache.put(tabUrl,response);
        }
        return cache.get(tabUrl);
      }
    };
});

And use this service in controller:
app.controller("myCtrl",function($scope,$location,JsonFactory){
  $scope.clickCount=0;
  $scope.jsonpTest = function(){
    $scope.result = JsonFactory.getResponse("myTab");
    $scope.clickCount++;
}
});

HTML:

Clicked: {{clickCount}}

Response: {{result}}

    <input type="button" ng-click="jsonpTest()" value="JSONP"/>

Screenshot:

[EDIT] for html5 localStorage solution
JSBin Demo
.factory("JsonFactory",function($resource){
  var url="ur/URL/:tabUrl";
  var liveTime=60*1000;  //1 min
  var response = "";

  return{
    getResponse:function(tabUrl){
      var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
      if(('localStorage' in window) && window.localStorage !== null){

      //no cached data
      if(!localStorage[tabUrl] || new Date().getTime()>localStorage[tabUrl+"_expires"])                  {
        console.log("no cache");
        //send GET request to fetch response
        response=retObj.list({tabUrl:tabUrl});

        //add response to cache
        localStorage[tabUrl] = response;
        localStorage[tabUrl+"_expires"] = new Date().getTime()+liveTime;
      }
      //console.log(localStorage.tabUrl.expires+"..."+new Date().getTime());
      return localStorage[tabUrl];
      }
      //client doesn't support local cache, send request to fetch response
      response=retObj.list({tabUrl:tabUrl});

      return response;
    }
  };
});

Hope this is helpful for you.


text:
Q: java: convert binary string to int I'm trying to convert a couple of binary strings back to int. However it doesn't convert all my binary strings, leaving me a java.lang.NumberFormatException exception.
Here is my test code with 3 binary string:
public class Bin {

    public static void main(String argvs[]) {
            String binaryString ;
            binaryString = Integer.toBinaryString(~0);
            //binaryString = Integer.toBinaryString(~1);
            //binaryString = "1010" ;
            int base = 2;
            int decimal = Integer.parseInt(binaryString, base);
            System.out.println("INPUT=" + binaryString + " decimal=" + decimal) ;
    }
}

If I convert the "1010" it works great, but when I try to convert one of the other two I get the exception. Can someone explain to me why this is ?
Cheers

A: As explained above, Integer.toBinaryString() converts ~0 and ~1 to unsigned int so they will exceed Integer.MAX_VALUE.
You could use long to parse and convert back to int as below.
int base = 2;
for (Integer num : new Integer[] {~0, ~1}) {
    String binaryString = Integer.toBinaryString(num);
    Long decimal = Long.parseLong(binaryString, base);
    System.out.println("INPUT=" + binaryString + " decimal=" + decimal.intValue()) ;
}

A: From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString() method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt() method throws NumberFormatException if "The value represented by the string is not a value of type int".
Note that both ~0 and ~1 are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int, so causing the NumberFormatException that you are seeing.

A: The bits for "~0" are 11111111111111111111111111111111 (32 1's).  Normally, this represents the number -1.  The bits for "~1" are 11111111111111111111111111111110 (31 1's followed by a zero).  Normally, this represents the number -2.
I tried "01111111111111111111111111111111" (a 0 and 31 1's), which represents the highest signed integer, in parseInt and there was no error.  But I tried "10000000000000000000000000000000", which represents the minimum signed integer, and there was the error again.
The parseInt method seems to expect a "-" in the input to indicate that a negative number is desired.  It looks like this method is detecting overflow in the integer and throwing the NumberFormatException.

A: Adding all four updated methods and comparisons here for easier understanding
public static void binary() {

    // Gives magnitude in binary along with sign for negative values
    System.out.println(Integer.toString(-1,2)); // -1
    // Give the int value of input binary representation along with sign
    System.out.println(Integer.parseInt(Integer.toString(-1, 2),2)); // -1

    // Gives signed binary representation of input value
    System.out.println(Integer.toBinaryString(-1)); // 11111111111111111111111111111111
    // Gives the integer value of signed binary number
    System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2)); // -1
}


text:
Q: When I am running scripts with IE in robot framework, I am getting below error:WebDriverException: Message: Invalid timeout type specified: sessionId When I am running scripts with IE driver in robot framework, I am getting the  below error:
WebDriverException: Message: Invalid timeout type specified: sessionId

Code:
Open Browser    ${url}  ie
Maximize Browser Window
Input Text  ${x_username}   ${d_username}

I am using IEDriverServer with version 3.13. Could you please help me why I am  getting this error. Same script is working fine with chrome and firefox.

A: Some people here have similar issue. Seems that IEDriverServer v5.0.0 works. Have you tried?


text:
Q: org.springframework.beans.factory.wiring.BeanWiringInfo.BeanWiringInfo is initialized with null name I'm trying to re-wire an @Autowired field after a session serialization to  Redis using Spring Session and Aspectj.
This is the bean:
@UIScope()
@SpringComponent(value = AboutView.VIEW_NAME)
@SpringView(name = AboutView.VIEW_NAME)
//
@Configurable(autowire = Autowire.BY_NAME, value = AboutView.VIEW_NAME, dependencyCheck = false, preConstruction = true)
public class AboutView extends AbstractView {

    public static final String VIEW_NAME = "butterfly-effect-frontend-system:about";

    private Table tableFrontEndInformation;

    private GridLayout backendLayout;

    private GridLayout frontendLayout;

    @Autowired
    private transient DiscoveryClient discoveryClient;

This bean is using @Configurable and the name of the bean definition (value). Unfortunately the aspect is creating a BeanWiringInfo with null bean name, that will raise an error as the name is required.
@Configurable(autowire = Autowire.BY_NAME, value = AboutView.VIEW_NAME, dependencyCheck = false, preConstruction = true)

The error happens due the following constructor which is called by AnnotationBeanWiringInfoResolver
/**
     * Create a new BeanWiringInfo that points to the given bean name.
     * @param beanName the name of the bean definition to take the property values from
     * @param isDefaultBeanName whether the given bean name is a suggested
     * default bean name, not necessarily matching an actual bean definition
     * @throws IllegalArgumentException if the supplied beanName is {@code null},
     * is empty, or consists wholly of whitespace
     */
    public BeanWiringInfo(String beanName, boolean isDefaultBeanName) {
        Assert.hasText(beanName, "'beanName' must not be empty");
        this.beanName = beanName;
        this.isDefaultBeanName = isDefaultBeanName;
    }

The AnnotationBeanWiringInfoResolver instantiates the BeanWiringInfo from this code:
protected BeanWiringInfo buildWiringInfo(Object beanInstance, Configurable annotation) {
        if (!Autowire.NO.equals(annotation.autowire())) {
            return new BeanWiringInfo(annotation.autowire().value(), annotation.dependencyCheck());
        }
        else {
            if (!"".equals(annotation.value())) {
                // explicitly specified bean name
                return new BeanWiringInfo(annotation.value(), false);
            }
            else {
                // default bean name
                return new BeanWiringInfo(getDefaultBeanName(beanInstance), true);
            }
        }
    }

This is the error:
Caused by: java.lang.IllegalArgumentException: 'name' must not be null
    at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.BeanFactoryUtils.transformedBeanName(BeanFactoryUtils.java:72) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.transformedBeanName(AbstractBeanFactory.java:1109) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedBeanDefinition(AbstractBeanFactory.java:970) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at com.vaadin.spring.internal.SpringViewDisplayPostProcessor.postProcessAfterInitialization(SpringViewDisplayPostProcessor.java:66) ~[classes/:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1594) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:400) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.wiring.BeanConfigurerSupport.configureBean(BeanConfigurerSupport.java:142) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect.configureBean(AnnotationBeanConfigurerAspect.aj:63) ~[spring-aspects-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.aspectj.AbstractDependencyInjectionAspect.ajc$before$org_springframework_beans_factory_aspectj_AbstractDependencyInjectionAspect$1$e854fa65(AbstractDependencyInjectionAspect.aj:79) ~[spring-aspects-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at com.scipionyx.butterflyeffect.frontend.configuration.ui.view.AboutView.<init>(AboutView.java:72) ~[classes/:na]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_45]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422) ~[na:1.8.0_45]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 107 common frames omitted

Does anyone knows what can be wrong on this configuration ?
Your help us much appreciated.

A: I'm still trying to understand why, but it seems that removing the autowire = Autowire.BY_NAME from the @Configuration seems to solve the problem.
Now the Class looks like this:
@UIScope()
@SpringComponent(value = AboutView.VIEW_NAME)
@SpringView(name = AboutView.VIEW_NAME)

//
@Configurable(value = AboutView.VIEW_NAME)
public class AboutView extends AbstractView {


text:
Q: At which hour of sleep, additional hour will have a negative impact on test score (curvilinear relationship) Let's assume that there is a curvilinear relationship between test score and number of sleep hours.  According to the simple example below, starting from 8 hours, test score goes down. I can see it from data.  But, how can I calculate it? how can I calculate that at which point, no. of sleep hour will have negative impact on text score?
Score   **Hr of sleep**
1.20    **1**
3.30    **2**
6.00    **3**
7.00    **4**
12.00   **5**
18.00   **6**
18.00   **7**
16.00   **8**
8.00    **9**
6.00    **10**

A: If your "hours of sleep" is discrete and you have a sufficient number of observations, I would create a series of dummy variables "at least x hours of sleep" (maybe group them at the bottom "less than four hours" , more than four hours, more than five hours, more than six hours etc. Then do a regular linear regression with test score as the dependent and the dummys as explanatory variables and finally plot the betas. (Alternatively, if you use Stata like I do, do a regression then check out margins and marginsplot)

Score   Hr of sleep more4hours more5hours more6hours  etc
1.20    1                0            0            0
3.30    2                0            0            0
6.00    3                0            0            0
7.00    4                0            0            0
12.00   5                1            0            0
18.00   6                1            1            0
18.00   7                1            1            1
16.00   8                1            1            1
8.00    9                1            1            1
6.00    10               1            1            1


text:
Q: sum is 1 irrespective of numbers having cal_sum in the last cout statement gives 1 as output irrespective of the values entered. when x+y is entered in place of cal_sum in cout statement then I m getting the correct answer .why?
#include<iostream>
using namespace std;
 //sum of 2 numbers.
 int cal_sum(int a,int b)
 {
     int sum;
     sum=a+b;
     return sum;
 }
int main()
{
    int x,y;
    cout<<"enetr any 2 no\n";
    cin>>x;
    cin>>y;
    cal_sum(x,y);
    cout<<"sum ="<<cal_sum;
}

A: You are printing cal_sum itself, when you should be printing cal_sum(x, y):
#include <iostream>

//sum of 2 numbers.
int cal_sum(int a,int b)
{
    return a + b;
}

int main()
{
    int x,y;
    std::cout << "enetr any 2 no\n";
    std::cin >> x;
    std::cin >> y;
    std::cout << "sum =" << cal_sum(x,y);
}

You might be wondering why printing cal_sum always prints 1. The reason is that there is no overload for the << operator which takes a function, so instead cal_sum is printed as a bool. cal_sum is not a nullptr, so it is true or 1 as shown in the output.


text:
Q: How can NULL and regular values be handled without using different prepared statements? Consider this simple method:
public ResultSet getByOwnerId(final Connection connection, final Integer id) throws SQLException {
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM MyTable WHERE MyColumn = ?");
    statement.setObject(1, id);
    return statement.executeQuery();
}

The example method is supposed to select everything from some table where a column's value matches, which should be simple.
The ugly detail is that passing NULL for the id will result in an empty ResultSet, regardless how many rows there are in the DB because SQL defines NULL as not euqaling anyting, not even NULL.
The only way to select those rows I know of is using a different where clause:
SELECT * FROM MyTable WHERE MyColumn IS NULL

Unfortunately the only way to make the method work properly in all cases seems to be to have two entirely different execution pathes, one for the case where the id argument is null and one for regular values.
This is very ugly and when you have more than one column that can be nulled can get very messy quickly. How can one handle NULL and normal values with the same code path/statement?

A: I haven't tried this, but the way to send nulls to preparedStatements is to use the setNull() option
   PreparedStatement statement = connection.prepareStatement("SELECT * FROM MyTable WHERE MyColumn = ?");
    if ( id == null)
       statement.setNull(1, java.sql.Types.INTEGER);
    else
      statement.setObject(1, id);
    return statement.executeQuery();

EDIT : Thanks for the responses @Gabe and @Vache. It does not look like there is an easy way to do this other than taking a more longwinded approach to dynamically create the preparedstatment.
Something like this should work --
String sql = " SELECT * FROM MyTable WHERE " + (id==null)?"MyColumn is null":"MyColumn = ?" ;
       PreparedStatement statement = connection.prepareStatement(sql);
        if ( id != null)
          statement.setObject(1, id);
        return statement.executeQuery();

A: You could use a query like this:
select * from MyTable where
  case when ?1 is null then MyColumn is null else MyColumn = ?1

But it reuses the same parameter, so I don't know whether the syntax I've proposed (?1) will work.


text:
Q: Error: "argument --job-dir: expected one argument" while training model using AI Platform on GCP Running macOS Mojave.
I am following the official getting started documentation to run a model using AI platform.
So far I managed to train my model locally using:
# This is similar to `python -m trainer.task --job-dir local-training-output`
# but it better replicates the AI Platform environment, especially
# for distributed training (not applicable here).
gcloud ai-platform local train \
  --package-path trainer \
  --module-name trainer.task \
  --job-dir local-training-output

I then proceed to train the model using AI platform by going through the following steps:

*

*Setting environment variables export JOB_NAME="my_first_keras_job" and export JOB_DIR="gs://$BUCKET_NAME/keras-job-dir".

*Run the following command to package the trainer/ directory:

Command as indicated in docs:
 gcloud ai-platform jobs submit training $JOB_NAME \
   --package-path trainer/ \
   --module-name trainer.task \
   --region $REGION \
   --python-version 3.5 \
   --runtime-version 1.13 \
   --job-dir $JOB_DIR \
   --stream-logs

I get the error:

ERROR: (gcloud.ai-platform.jobs.submit.training) argument --job-dir:
  expected one argument Usage: gcloud ai-platform jobs submit training
  JOB [optional flags] [-- USER_ARGS ...]   optional flags may be
  --async | --config | --help | --job-dir | --labels | ...

As far as I understand --job-dir: does indeed have one argument.

I am not sure what I'm doing wrong. I am running the above command from the trainer/ directory as is shown in the documentation. I tried removing all spaces as described here but the error persists.

A: Are you running this command locally? Or on a AI notebook VM in Jupyter? Based on your details I assume youre running it locally, I am not a mac expert, but hopefully this is helpful.
I just worked through the same error on an AI notebook VM and my issue was that even though I assigned it a value in a previous Jupyter cell, the $JOB_NAME variable was passing along an empty string in the gcloud command. Try running the following to make sure your code is actually passing a value for $JOB_DIR when you are making the gcloud ai-platform call.
echo $JOB_DIR


text:
Q: How can i share cusome title and description in google plus like facebook? I have a  lot of products and want to share each one with different title and description in Google plus instead of page meta tags. How can i do that?

A: Google+
Will recognize:
<meta itemprop="name" content="The page Title for sharing">
<meta itemprop="description" content="The description less than 200 characters">
<meta itemprop="image" content="http://www.yoursite.com/image-200x200.jpg">

Facebook
Open Graph Tags (Other Social networks read it too):
<meta property="og:image" content="http://www.yoursite.com/the-page-thumb-200x200.jpg" />
<meta property="og:title" content="The page Title for sharing" />
<meta property="og:type" content="website" /> (or "article")
<meta property="og:url" content="http://www.yoursite.com/the-url-for-sharing" />
<meta property="og:description" content="The Description less than 200 characters" />
<meta property="og:site_name" content="Your Site name" />
<meta property="fb:app_id" content="your-facebook-app-id" />
<meta property="fb:admins" content="your-facebook-user-id" />

Get app-id
@ https://developers.facebook.com/
Login with your FB credentials and then setup a facebook app.
Use the Debug tool
@ https://developers.facebook.com/tools/debug
to see how your Data is seen.
Twitter Tags
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@publisher_handle">
<meta name="twitter:title" content="The page Title for sharing">
<meta name="twitter:description" content="The description less than 200 characters">
<meta name="twitter:creator" content="@author_handle">
<meta name="twitter:image" content="http://www.yoursite.com/image-200x200.jpg">

A:
instead of page meta tags

You cannot. Google+ will only fetch data about the page from the page. You cannot override it with URI parameters or though any JS API.


text:
Q: Ruby on Rails app on Heroku file upload not working I'm new to Rails and Heroku as well.
Following tutorials I succeed to upload my app to Heroku.
My app is enable us to upload csv file to uploads folder in public.
So I can upload file in heroku deployed app and show table as I want.
But after 30 mins or so those files are removed automatically and showing error that no such file in public/uploads folder.
It is properly working on my local which is using sqlite3.
But heroku want to use psql for production mode so I changed production mode to use psql.
So if I upload csv file then it is stored in 'public/uploads' folder.
I think heroku app is automatically update to github repo even I didn't execute 'git push heroku master' command.
In my local repository files are stored but they are run on development mode.
How can I make upload functionality fully working?
Any help would be appreciate.

A: Ephemeral filesystem is just the way heroku works, as explained in the article - uploaded files will be removed when the instance is restarted.
What you should do is to upload those files for example to S3 (https://devcenter.heroku.com/articles/s3), you can achieve this with CarrierWave gem with Fog gem but there are other possibilities as explained in this thread here: https://www.reddit.com/r/rails/comments/2k9sq4/heroku_any_files_you_upload_will_not_be_saved/


text:
Q: Extract only id object to a new object How can I only take the id when I create a new array?
In the example below, my Permission object has a variable "id", that is all I need when I create my array.  I don't need the other properties of Permission, they should be null in the new array.
@Override
public List<Permission> extractPermissionsToId(Role role) {
    List<Permission> unextracted = role.getPermissions();
    List<Permission> extracted = new ArrayList<>();

    for (Permission permission : unextracted) {
        extracted.addAll(permission.getId());
    }

    return null;
}

A: If you would be comfortable with creating new Permission objects for your extracted list, then you may try something along the lines of the following:
for (Permission permission : unextracted) {
    Permission p = new Permission();
    p.setId(permission.getId());
    extracted.add(p);
}

In other words, you can try creating a new Permission object based off the unextracted one, setting only the id field.


text:
Q: VBA forumla longer than 255 characters Formula Array .replace with vba cell references I am trying to take the following formula and have it so I can enter it into the cells in a new row in a listobject which gets cleared repeatedly. The formula is longer than 255 characters, so I need to break it up using the formula array .replace method.
=SUM(IFERROR(INDEX($H7:$H8,MATCH(X$5,$H7:$H8,0)+1,1),0)+IFERROR(INDEX($I7:$I8,MATCH(X$5,$I7:$I8,0)+1,1),0)+IFERROR(INDEX($J7:$J8,MATCH(X$5,$J7:$J8,0)+1,1),0)+IFERROR(INDEX($K7:$K8,MATCH(X$5,$K7:$K8,0)+1,1),0)+IFERROR(INDEX($L7:$L8,MATCH(X$5,$L7:$L8,0)+1,1),0)+IFERROR(INDEX($M7:$M8,MATCH(X$5,$M7:$M8,0)+1,1),0)+IFERROR(INDEX($N7:$N8,MATCH(X$5,$N7:$N8,0)+1,1),0))
The .replace will not replace the selection with my string. I do not understand why. Can someone please help me with this? Here is the code that I am using.
           tblabwk.ListRows.Add
        abwkrw = tblabwk.ListRows.Count
        tblabwk.ListRows(abwkrw).Range.ClearContents
        wslncl = tblconwk.ListColumns("Last Name").Range.Column
        wsfncl = tblconwk.ListColumns("First Name").Range.Column
        wsconcl = tblconwk.ListColumns("Contract").Range.Column
        wssuncl = tblconwk.ListColumns("Sun").Range.Column
        wsmoncl = tblconwk.ListColumns("Mon").Range.Column
        wstuecl = tblconwk.ListColumns("Tue").Range.Column
        wswedcl = tblconwk.ListColumns("Wed").Range.Column
        wsthucl = tblconwk.ListColumns("Thu").Range.Column
        wsfricl = tblconwk.ListColumns("Fri").Range.Column
        wssatcl = tblconwk.ListColumns("Sat").Range.Column
        abfrarw = tblconwk.ListRows(conwkrarw).Range.Row
        abfttlrw = tblconwk.ListRows(conwkttlrw).Range.Row
        strlstnf = "=INDEX(" & wswk.Range(wswk.Cells(abfrarw, wslncl), wswk.Cells(abfttlrw, wslncl)).Address(True, True) & ",MATCH($U$4," & wswk.Range(wswk.Cells(abfrarw, wsconcl), wswk.Cells(abfttlrw, wsconcl)).Address(True, True) & "),0)"
        tblabwk.ListColumns("Last Name").DataBodyRange(abwkrw).Formula = strlstnf
        strfstnf = "=INDEX(" & wswk.Range(wswk.Cells(abfrarw, wsfncl), wswk.Cells(abfttlrw, wsfncl)).Address(True, True) & ",MATCH($U$4," & wswk.Range(wswk.Cells(abfrarw, wsconcl), wswk.Cells(abfttlrw, wsconcl)).Address(True, True) & "),0)"
        tblabwk.ListColumns("First Name").DataBodyRange(abwkrw).Formula = strfstnf
For i = 3 To tblabwk.ListColumns.Count
                        wshrrw = tblabwk.HeaderRowRange.Row
                        wshrcl = tblabwk.ListColumns(i).Range.Column
                        strabf = "=SUM((AAA)+(BBB)+(CCC)+(DDD)+(EEE)+(FFF)+(GGG))"
                        strsunf = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wssuncl), wswk.Cells(abfrarw, wssuncl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wssuncl), wswk.Cells(abfrarw, wssuncl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strmonf = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wsmoncl), wswk.Cells(abfrarw, wsmoncl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wsmoncl), wswk.Cells(abfrarw, wsmoncl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strtuef = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wstuecl), wswk.Cells(abfrarw, wstuecl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wstuecl), wswk.Cells(abfrarw, wstuecl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strwedf = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wswedcl), wswk.Cells(abfrarw, wswedcl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wswedcl), wswk.Cells(abfrarw, wswedcl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strthuf = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wsthucl), wswk.Cells(abfrarw, wsthucl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wsthucl), wswk.Cells(abfrarw, wsthucl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strfrif = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wsfricl), wswk.Cells(abfrarw, wsfricl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wsfricl), wswk.Cells(abfrarw, wsfricl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        strsatf = "IFERROR(INDEX(" & wswk.Range(wswk.Cells(abfrarw, wssatcl), wswk.Cells(abfrarw, wssatcl).Offset(1, 0)).Address(True, True) & ",MATCH(" & wswk.Cells(wshrrw, wshrcl).Address(True) & "," & wswk.Range(wswk.Cells(abfrarw, wssatcl), wswk.Cells(abfrarw, wssatcl).Offset(1, 0)).Address(True, True) & ",0)+1,1),0"
                        With tblabwk.ListColumns(i).DataBodyRange(abwkrw)
                            .FormulaArray = strabf
                            .Replace "AAA", strsunf, lookat:=xlPart
                            .Replace "BBB", strmonf, lookat:=xlPart
                            .Replace "CCC", strtuef, lookat:=xlPart
                            .Replace "DDD", strwedf, lookat:=xlPart
                            .Replace "EEE", strthuf, lookat:=xlPart
                            .Replace "FFF", strfrif, lookat:=xlPart
                            .Replace "GGG", strsatf, lookat:=xlPart
                        End With
                    Next i


text:
Q: Zip a folder and archive it using powershell Im new to powershell and I would like to archive the folders using it
following are my folders in C:\Bridge\Build\destination

Vista
Tamil
CSK

I want to archive these folders in C:\Bridge\Build\Build_Achive\2020-05-15 with the file name  as 2020-05-1.zip
The folder destination and file name will be generated based on current date and time stamp so I would like  to use the variable in destination and file name
I tried the following code its giving me error can anyone please help
$path = "C:\Bridge\Build\Build_Achive\$((Get-Date).ToString('yyyy-MM-dd'))"
    If(!(test-path $path))
        {
              New-Item -ItemType Directory -Path "C:\Bridge\Build\Build_Achive\$((Get-Date).ToString('yyyy-MM-dd'))"
              ECHO 'Created folder '  $path
        }
    ELSE
        {
              Write-Host 'Folder ' ' - ' $((Get-Date).ToString('yyyy-MM-dd'))   ' - ' 'already exists'
        }
$FileLogdate = (Get-Date -f yyyy-MM-dd-HHmmss)

echo $path
echo $FileLogdate
$filename =$path\$FileLogdate
Compress-Archive -Path C:\Bridge\Build\destination -DestinationPath filename.zip

A: You have problems in the last two lines:

*

*Variable file name - you need to use quotes, as you are trying to create a string: $filename ="$path\$FileLogdate"

*I believe you would like to compress the files not with name filename.zip, but with the content of the variable $filename:
Compress-Archive -Path C:\TEMP\AdComputers_WindowsServer_2008.csv -DestinationPath $filename


text:
Q: UML. How to illustatrate usage of external libraries? How to illustrate in UML dependency on external libraries, like Hibernate, Apache POI etc?

A: You would normally represent this in an implementation diagram that shows the module (component) structure.  Simply put the external libraries on the diagram and stereotype them appropriately to make it clear that they are external dependencies.  Then use a "uses" dependency relation to indicate the parts of the system that depend on them.
For example, to use a trivially simple case ...

This shows two system modules (JAR files) with one dependent on the other, and one of them dependent on an external JAR file.   The stereotypes used to make the nature of the modules clear are custom stereotypes that I've created for this model (as UML doesn't come with such specific stereotypes in its meta-model).


text:
Q: D3js v4. How to determine custom event? I want to remove svg elements by custom "click + delete" event. I know how to determine click event, and events like ctrlKey, shiftKey, altKey, metaKey. But I want to use other keys. What is the right way to do it?

A: You're going to need to listen to two different events to achieve this, notably keydown and keyup events. Let's pretend we've got a circle:
const DELETE_KEYCODE = 46;
let deletePressed = false;

d3.select("svg")
  .selectAll("circle")
  .on("keydown", () => { deletePressed = d3.event.keyCode === DELETE_KEYCODE; })
  .on("keyup", () => { deletePressed = false; })
  .on("click", (d, i, elements) => {
      if (deletePressed) {
         d3.select(elements[i]).remove();
      }
  });

Now realistically you probably want keyup to be a bit more intelligent, in case they pressed several keys and didn't keyup the delete! But I'll let you work that bit out.


text:
Q: Ubuntu 20.04 sudden boot error Without any update or change in file system Ubuntu boot error occured.
I tried to boot from the recovery mode, first time it was successful so I updated the system but the problem still persists and I cannot boot into the system even from recovery mode.
Also giving some error about initramfs decoding failed.

A: After an hour of search, I realized that it was caused because a laptop key was automatically pressed (don't know how the keypress triggered this serious error).
After fixing the keyboard problem (cleaning and reinserting the internal keyboard) the boot problem was automatically solved.


text:
Q: Azure Functions Consumption plan failover If you're using Consumption plan for Azure Functions is there any kind of failover if your region goes down or hardware failure occurs? Hardware failure I'd assume yes, but for a region it doesn't seem like it since you can only choose one.
So if we really need multi-region failover are we limited to using App Service plan for Functions?

A: It won't failover to a different geo region, no matter the hosting SKU. Use Traffic Manager to achieve that level of redundancy.
Needless to say, all resources your function depends on need to exist in the 2nd region as well (SQL instances, Redis, Event Hubs, ...). You are responsible for keeping state consistent across regions (think Azure SQL auto-failover groups).
One notable exception is Cosmos DB, which (if configured) can have automagically-managed replicas in multiple regions. Your function will always use the same connection string.


text:
Q: Issue with bubble sorting SO I decided to create a bubble algorithm in Python. The thing is that it works for some numbers,  but it doesn't work for others. Can anyone help:
def sort(number):
    to_sort = list(str(number))
    sorted_list = sorted(to_sort)
    print(sorted_list)
    i = 0
    while True:
        if to_sort == sorted_list:
            print(f"Sorted {number} to {''.join(to_sort)}" )
            break
        first_index = to_sort[i]
        try:
            second_index = to_sort[i+1]
        except IndexError:
            i = 0
        if first_index < second_index:
            i += 1
            print(to_sort)
            continue
        elif first_index > second_index:
            print(f"switching {to_sort[i+1]} to {first_index}")
            to_sort[i+1] = first_index
            print(to_sort)
            print(f"Switching {to_sort[i]} to {second_index}")
            to_sort[i] = second_index
            print(to_sort)
            i += 1
            continue

sort(49304)

It works for 51428 but not 49304. Anyone know why?

A: The fatal flaw is in your loop reset (to 0), combined with your disconnected swapping logic.
    first_index = to_sort[i]
    try:
        second_index = to_sort[i+1]
    except IndexError:
        i = 0
    ...
    elif first_index > second_index:
        ...
        to_sort[i] = second_index

In the case of running off the end of the list, second_index now has the wrong value: it's the previous value, since you never reset it after looping i back to 0.
(1) Fix your immediate problem by inserting that reset:
    except IndexError:
        i = 0
        second_index = to_sort[0]

(2) Research existing bubble sorts.  Among other things, make your exchange simpler.
    to_sort[i], to_sort[i+1] = to_sort[i+1], to_sort[i]

Control i so that it doesn't go out of bounds.  Note that you don't have to really worry about swapping the last element with the first: a bubble sort doesn't skip ends like that.


text:
Q: Use Powershell to sum a column in a directory of CSVs with headers I have a batch of .csv files in a directory with a column in each featuring values I need to sum. The .csv files all have identical headers such as ID, SIZE, FILE_PATH, etc., and "SIZE" is the column I need to sum. I found a handy one-liner to do it one by one (below), but as I try to have it cycle through each of the CSVs with a wildcard operator, I keep getting this error message: "Measure-Object: Input object 'SIZE' is not numeric." The command executes but only gives a total count of all of the rows, not of the summed size.
The one-by-one version that works is:
Get-Content "file.csv" | ConvertFrom-Csv | Measure-Object "SIZE" -Sum
The version I have tried to make work is:
Get-Content ".\*.csv" | ConvertFrom-Csv | Measure-Object "SIZE" -Sum
Everything in the column is numeric except the header, but how do I both specify the column by its name "SIZE" and ignore the header?
Do you have any suggestions? I have to run this monthly over hundreds of .csv files, so it would be ideal to be able to get it to work in one go.

A: Try this instead
Get-ChildItem .\*.csv |
    foreach {Import-Csv $_} |
        Measure-Object size -sum

And if you want just the sum
(Get-ChildItem .\*.csv |
    foreach {Import-Csv $_} |
        Measure-Object size -sum).sum

or
Get-ChildItem .\*.csv |
    foreach {Import-Csv $_} |
        Measure-Object size -sum |
            Select-Object -Expand Sum

or
$sum = Get-ChildItem .\*.csv |
    ForEach-Object {Import-Csv $_} |
        Measure-Object -Property size -sum

$sum.sum

A: You're getting headers in the middle because Get-Content against multiple files will combine text from all files before processing it. You can use Get-ChildItem and Import-Csv for a better experience.
for example:
Get-ChildItem "*.csv" | ForEach-Object { Import-Csv -Path $_.FullName } | Measure-Object -Property Size -Sum


text:
Q: How do I save user information (like NSUserDefaults in obj-c) with C++? In objective-c it's easy. Although, in C, you have to call fopen, read, close and all of that jazz. How do you do it in C++?

A: just use the header fstream
example:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream file;
file.open("file.txt");
file << "Test!\n";
file.close()
return 0;
}


text:
Q: The connection string 'DefaultConnection' in the application's configuration file does not contain the required providerName attribute." Just trying to publish my first MVC app to Godaddy Plesk hosting.
My app is working just fine running on localhost on my machine but when deploy it to host(used webdeploy ) whenever i try to run some database stuff (used EF -code first) i get: The connection string 'DefaultConnection' in the application's configuration file does not contain the required providerName attribute." error.
Here is my connection string
add name="DefaultConnection" connectionString="Data Source=myserverIP;Network Library =DBMSSOCN;Initial Catalog=mydatabase;User ID=myuser;Password=mypass;" providerName="System.Data.SqlClient"
The strangest thing is that when I use this connection string on my local development machine instead of default "...Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename etc..." string, App runs just fine and I see data stored in database on godaddy hosting.
Also I connect to this database from Microsoft SQL Server Managament Studio using credentials from conncetion string above and without any problem run querys
Hope somebody can help me out
thanks in advance


text:
Q: aarch64-linux-gnu-cpp: error: unrecognized command line option '-mthumb' I am trying to build U-boot. After doing make xconfig I run
make CROSS_COMPILE=aarch64-linux-gnu-

and I encounter this error:
  OBJCOPY u-boot.srec
  OBJCOPY u-boot.bin
  OBJCOPY u-boot.hex
fatal: bad revision 'HEAD'
Building board/amlogic/gxl_p212_v1/acs.bin
fatal: bad revision 'HEAD'
Building board/amlogic/gxl_p212_v1/bl21.bin
    CPP user_task.lds
aarch64-linux-gnu-cpp: error: unrecognized command line option '-mthumb'
aarch64-linux-gnu-cpp: error: unrecognized command line option '-mno-sched-prolog'
make[2]: *** [/media/saleh/NEWVOLUME/UBOOT/openlinux/uboot-2016-08-18-edd7f116ab/build/scp_task/user_task.lds] Error 1
make[1]: *** [bl301.bin] Error 2
make: *** [sub-make] Error 2

Anyone knows what the problem is?


text:
Q: Como pegar uma posição especifica do no foreach com PHP Estou criando uma aplicação que vou ter um RSS, e criei esse script em PHP:

<?php
// permite requisições a urls externas
ini_set('allow_url_fopen', 1);
ini_set('allow_url_include', 1);

// caminho do feed do meu blog
$feed = 'https://www.conjur.com.br/rss.xml';
// leitura do feed
$rss = simplexml_load_file($feed);
// limite de itens
$limit = 1;
// contador
$count = 0;

// imprime os itens do feed
if($rss)
{
    foreach ( $rss->channel->item as $item )
    {
        // formata e imprime uma string
        printf('%s
', $item->link, $item->title, $item->title);
        // incrementamos a variável $count
        $count++;
        // caso nosso contador seja igual ao limite paramos a iteração
        if($count == $limit) break;
    }
}
else
{
    echo 'Não foi possível acessar o blog.';
}

E preciso exibir um bloco com apenas uma noticia e depois mais 4, porém a primeira não pode repetir nas outras 4.
Qual seria a melhor forma pra fazer isso? Alguém pode me ajudar por favor!

A: Você pode verificar se existe em um array cada um desses RSS, se não ele vai adicionar esse link, assim fica mais fácil para ser manipulado posteriormente, podendo assim até exibir quantas e como quiser.
Fica assim um exemplo em base ao seu código:
<?php
// permite requisições a urls externas
ini_set('allow_url_fopen', 1);
ini_set('allow_url_include', 1);

// caminho do feed do meu blog
$feed = 'https://www.conjur.com.br/rss.xml';
// leitura do feed
$rss = simplexml_load_file($feed);
// limite de itens
$limit = 1;
// contador
$count = 8;
$noticias = array();

// imprime os itens do feed
if($rss)
{
    foreach ( $rss->channel->item as $item )
    {
        // formata e imprime uma string
        //printf('%s
', $item->link, $item->title, $item->title);
        $link = $item->link;
        $titulo = $item->title;

        $noticia = "$titulo
";

        if(!in_array($noticia,$noticias)){
            array_push($noticias,$noticia);
        }
        // incrementamos a variável $count
        $count++;
        // caso nosso contador seja igual ao limite paramos a iteração
        if($count == $limit) break;
    }
}
else
{
    echo 'Não foi possível acessar o blog.';
}

var_dump($noticias);
?>


text:
Q: UDF for concatenating elements of two arrays VBA Excel Suppose there are two 1D arrays each of them contains 3 elements as follow
A   1
2   3
B   C

How does one concatenate the two arrays into a single array with elements
A1
23
BC

It's easy to do that in sheet operation by using either & or CONCATENATE function, but how to do this in array?

A: Iterate through the array and combine them into a third:
Sub foooooo()
Dim arr1() As Variant
Dim arr2() As Variant
Dim outArr() As Variant
arr1 = Array("A", "2", "B")
arr2 = Array("1", "3", "C")

ReDim outArr(UBound(arr1))
For i = LBound(arr1) To UBound(arr1)
    outArr(i) = arr1(i) & arr2(i)
Next i

Debug.Print Join(outArr, ",")

End Sub


text:
Q: Return onPostExecute Value into onBindViewHolder of RecyclerAdapter I have chat screen where i am downloading attachment from FirebaeStorage.
I have various formats of file which can be send doc,pdf,apk etc. and for each i have same TextViews and ImageViews.
In Chat screen's recyclerview adapter i am setting file path of local storage which can be obtain by run AsyncTask which downloads files from Firebase Storage and return file path.This work perfectly but the issue is how to get back that file path in onBindViewHolder on particular if else
Here is my RecyclerAdapter where i am calling AsyncTask and need result back into same scope and wait till download completes then set views according to data returned
public void onBindViewHolder(final Chat_Adapter.ViewHolder holder, int position) {

if (fileType.equals("pdf")){
 new DownloadFileFromFS(Download_URL,FileName+".pdf").execute();

//HERE I NEED THE RESULT FROM ASYNCTASK AND WAIT TILL DOWNLOAD COMPLETES
 //THEN SET THE VIEWS WITH RETURN RESULT FROM ASYNCTASK

    if (DownloadFilePath!=null){
        File file=new File(DownloadFilePath);
        long sizeFile=file.length()/1024; //In KB
        holder.Doc_FileName.setText(DownloadFilePath);
        holder.Doc_FileSize.setText(String.valueOf(sizeFile));
    }
    else {
        Log.d(TAG,"DOWNLOAD FILE PATH IS NULL");
    }

}

AsyncTask
public class DownloadAttachment extends AsyncTask<Void, String, String> {
    String DownloadUrl,fileName;
    File file;
    Context context;
    ProgressBar progressBar;
    public static final String TAG="###Download Attachment";

    public DownloadAttachment(Context context, String downloadUrl, String fileName) {
        DownloadUrl = downloadUrl;
        this.fileName = fileName;
        this.context=context;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
    }

    @Override
    protected String doInBackground(Void... params) {
        int count;
        try {
            File root = android.os.Environment.getExternalStorageDirectory();

            Log.d(TAG,"DO IN BACKGROUND RUNNING");
            File dir = new File(root.getAbsolutePath() + "/Downloaded Files/");
            if (dir.exists() == false) {
                dir.mkdirs();
            }

            URL url = new URL(DownloadUrl); //you can write here any link
            file = new File(dir, fileName);

            long startTime = System.currentTimeMillis();
            Log.d(TAG, "download begining");
            Log.d(TAG, "download url:" + url);
            Log.d(TAG, "downloaded file name:" + fileName);

       /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            //this will be useful so that you can show a typical 0-100% progress bar
            int lengthOfFile=ucon.getContentLength();
       /*
        * Define InputStreams to read from the URLConnection.
        */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

       /*
        * Read bytes to the Buffer until there is nothing more to read(-1).
        */
            ByteArrayOutputStream baf = new ByteArrayOutputStream(5000);
            int current = 0;
            long total=0;
            while ((current = bis.read()) != -1) {
                baf.write((byte) current);
                total=total+current;
                //PUBLISH THE PROGRESS
                //AFTER THIS onProgressUpdate will be called
                publishProgress(""+(int)(total*100)/lengthOfFile);
            }

       /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.flush();
            fos.close();
            Log.d("DownloadManager", "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
            Log.d(TAG,"File Path "+file);

        } catch (IOException e) {
            Log.d("DownloadManager", "Error: " + e);
        }

        return file.toString();
    }

}

UPDATE As @Atef Hares suggest,i did implement in code.its working fine but what if i have different format. How to call particular if else after getting result from asynctask cuz code suggested only call pdf if statement.
if (fileType.equals("pdf")){
    final String nameFile=UUID.randomUUID().toString();
    new DownloadFileFromFS(chat_wrapper.getDocuments(),nameFile).execute();

     filePathInterface=new FilePath() {
        @Override
        public void LocalFilePath(final String Path) {
           //HERE I AM GETTING RESULT FROM ASYNCTASK
           //AND SETTING VIEWS ACCORDING TO IT
        }
    };

}
else if (fileType.equals("doc")){
//HOW TO GET RESULT FROM ASYNCTASK HERE IF FILETYPE IS "doc"

}
else if (fileType.equals("ppt")){
//HOW TO GET RESULT FROM ASYNCTASK HERE IF FILETYPE IS "ppt"
}

A: Okay using interfaces -as you know- will achieve what you need!
just do it like this:
public interface AsyncTaskCallback {
    void onSuccess (String filePath);
}

and in the Adapter, don't set any data to the view unless you got the data back from asyncTask, like this:
public void onBindViewHolder(final Chat_Adapter.ViewHolder holder, int position) {

         //Initialize filetype here

        new DownloadFileFromFS(Download_URL, FileName + "."+ filetype, new AsyncTaskCallback() {
            @Override
            public void onSuccess(String filePath) {
                //HERE I NEED THE RESULT FROM ASYNCTASK AND WAIT TILL DOWNLOAD COMPLETES
                //THEN SET THE VIEWS WITH RETURN RESULT FROM ASYNCTASK

                if (filePath != null) {
                    File file = new File(filePath);
                    long sizeFile = file.length() / 1024; //In KB
                    holder.Doc_FileName.setText(filePath);
                    holder.Doc_FileSize.setText(String.valueOf(sizeFile));
                } else {
                    Log.d(TAG, "DOWNLOAD FILE PATH IS NULL");
                }
            }
        }).execute();
    }

A: You could use a callback.
public interface FileDownloadCallback {
    void onSuccess (String filePath);
    void onFailed ();

}

Pass that in to your AsyncTask and call it from onPostExecute.


text:
Q: Can't set custom validator messages in Zend_Form I just can't figure it out how to set custom validator messages in Zend_Form object. Here is an example code.
$this->addElement('password', 'password', array(
        'label'      => 'Password',
        'decorators' => array('ViewHelper'),
        'filters'    => array('StringTrim'),
        'validators' => array(
            array('Digits', false, array('messages' => array('notDigits' => 'Only digits are allowed here')))
        ),
        'required'   => true

    ));

When I try to validate the form entering invalid data  a message saying  "notDigits" appear.  I tried to change 'notDigits'  to  Zend_Validate_Digits::NOT_DIGITS, but it still doesn't work as expected.
Any help is greatly appreciated!

A: I found my error. I was recieving the 'notDigits' message, because in the controller I used $form->getErrors() method instead of  $form->getMessages().  The first one returns only the error codes, without the messages.

A: Your syntax for setting the custom message is correct.  In the code example you posted, the only decorator for that element is ViewHelper so the error message will not be displayed.
At the very least, add the Errors decorator if you want to see the error message.  Try this:
$this->addElement('password', 'code', array(
    'label'      => 'Code',
    'decorators' => array('ViewHelper', 'Errors'),
    'filters'    => array('StringTrim'),
    'validators' => array(
        array('Digits', false,
            array('messages' => array('notDigits' => 'Only digits are allowed here')))
    ),
    'required'   => true
);

The only change was adding the Errors decorator to the stack.

A: Try this validator syntax.
$this->addElement("text", "fullname", array(
                        'label' => 'Your Full Name: ',
                        'required' => 'true',
                        'validators' => array(
                            array('validator' => 'StringLength', 'options' => array('min'=>5, 'max'=>250, 'messages' => array('stringLengthTooShort' => 'The name is too short.')))
                        ),
                        'filters' => array('StringTrim'),
                        'decorators' => array("signup")
                    ));


text:
Q: How can one evaluate the following series: $$\sum_{k=1}^{\infty} (-1)^{k}\frac{(\ln{k})^{2}}{k} \space\space\space ?$$
From $\sum_{n\geq 1}\frac{(-1)^n \ln n}{n}$
it has been answered that
$$ \sum_{k=1}^{\infty} (-1)^{k} \frac{\ln{k}}{k} = \space \gamma \cdot \ln{2} \space - \space \frac{{(\ln{2})^{2}}}{2} \space \space \space ,  $$
where $\gamma$ is the Euler-Mascheroni constant.
$ \\ $

A: Hint. From the standard relation
$$\sum_{n\geq 1}\frac{(-1)^n }{n^s}=\left(\frac{1}{2^{s-1}}-1\right)\zeta(s)$$ one may differentiate twice and set $s \to 1^+$ using the Laurent series of the Riemann zeta function.


text:
Q: python for loop with if loop and output a file my first time writing python script. I had read through many questions and answers in stack overflow, but still didn't figure out where I got wrong in my code. Probably I could ask for help?
I have a file file.txt as below, with uncertain number of column in each line. "\t" is the tab delimiter
$ head file.txt
AA:d23\tBB:4r3w\tCC:e5t
BB:435\tCC:w4w
AA:w4r\tCC:2342
AA:34534\tBB:e5\tCC:7uf
BB:e4t4

I would like to turn it into a data_frame like .txt file, which has three columns in each row by adding NA for the missing column. Also, I would like to eliminate the rows that only have one entry (e.g. only AA or only BB or only CC). So expected output like below:
AA:d23\tBB:4r3w\tCC:e5t
AA:NA\tBB:435\tCC:w4w
AA:w4r\tBB:NA\tCC:2342
AA:34534\tBB:e5\tCC:7uf
#(the 5th line is omitted here because it only has one entry)

After studying many examples on the forum,I mimicked some codes, and wrote my own code as below:
#!/usr/bin/env python3

#into_data.py
import csv
import fileinput

def into_data(a_file):
  output=[]
  for row in a_file:
     if "AA:" in row and "BB:" in row and "CC:" in row:
        output.append(row)
     elif "AA:" not in row and "BB:" in row and "CC:" in row:
        output.append("AA:NA" + row)
     elif "AA:" in row and "BB:" not in row and "CC:" in row:
        output.append(row.split("\t")[0] + "CB:NA" + row.split("\t")[1])
     elif "AA:" in row and "BB:" in row and "CC:" not in row:
        output.append(row + "CC:NA")

reader = csv.reader(fileinput.input(), delimiter="\t")
print(into_data(reader))

#outside python script
python3 into_data.py file.txt > output.txt

But I get "None" in my output.txt. I don't really understand why. Could you please be so kind to point my error out? Thanks a lot in advance!

A: Your function doesn't have a return statement. Therefore it defaults to returning None.
You need to return the output at the end of the function like this:
def into_data(a_file):
  output=[]
  for row in a_file:
     if "AA:" in row and "BB:" in row and "CC:" in row:
        output.append(row)
     elif "AA:" not in row and "BB:" in row and "CC:" in row:
        output.append("AA:NA" + row)
     elif "AA:" in row and "BB:" not in row and "CC:" in row:
        output.append(row.split("\t")[0] + "CB:NA" + row.split("\t")[1])
     elif "AA:" in row and "BB:" in row and "CC:" not in row:
        output.append(row + "CC:NA")
  return output

To edit the rows as you specify, you can try this:
def into_data(a_file):
  output = []
  for row in a_file:
     if len(row) <= 1:
         continue
     if "AA:" not in row[0]:
        row.insert(0, "AA:NA")
     if "BB:" not in row[1]:
        row.insert(1, "BB:NA")
     if len(row) < 3:
        row.insert(2, "CC:NA")
     output.append(row)
  return output

A: Here's a pretty straight forward way that should handle all cases.
# a_file is a csv.reader
def into_data(a_file):
    output = []
    for row in a_file:
        if len(row) <= 1: continue
        if not row[0].startswith("AA"):
            row.insert(0, "AA:NA")
        if not row[1].startswith("BB"):
            row.insert(1, "BB:NA")
        if len(row) < 3:
            row.append("CC:NA")
        output.append(row)
    return output

This creates a list of lists. If you want a list of strings, change the line output.append(row) to
output.append('\t'.join(row))

A: Since you evoke dataframes/pandas, here is a proposition :
# Code :
import pandas as pd
import numpy as np

df = pd.read_csv('test.txt', header=None, sep=r'\\t', engine='python')

m = df.notnull().sum(axis=1).eq(1)
#does the row has a single entry ?

df = df.loc[~m]

out = (df.stack().reset_index(name='val')
   .assign(col=lambda x: x['val'].str.slice(0,2))
   .pivot(index='level_0', columns='col', values='val')
   .reset_index(drop=True)
)

out[:] = np.where(out.isna(), [out.columns + ':NA'], out)

out.columns = df.columns

out.to_csv('final.txt', sep='\t', header=None, index=False)

# Output :
print(out)

          0        1        2
0    AA:d23  BB:4r3w   CC:e5t
1     AA:NA   BB:435   CC:w4w
2    AA:w4r    BB:NA  CC:2342
3  AA:34534    BB:e5   CC:7uf


text:
Q: insert data to SQL with default data I set 3 columns: id(auto increment), names, age(default = 15).
Now if I want to insert data to SQL I can use this below line:
INSERT INTO shoppinglist (name,age) VALUES(?,?)

The first ? = alex and second ? = 22
which will find in the database that the id=1, the name=alex and age=22
Now what I want that if the user inserts only the name without the age, I would like from the age to get the default value, like if the user insert only the name with David, and submit it, I would like to e in DB like id=2 name =David age=15(default)
So is there a way to make the age to get the default if the user didn't insert the age or the age was 0?

A: create shoppinglist (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`age` int default 15
)

when you make the insertion, it would be like this:
INSERT INTO shoppinglist (name) VALUES ("Alex");

Or
INSERT INTO shoppinglist VALUES (Null, "Alex", DEFAULT);

A: INSERT INTO shoppinglist (name) VALUES(?)

this query inserts just name and puts the default value 15 for the age

A: You can use IFNULL function in query:
INSERT INTO shoppinglist (name,age) VALUES(?, IFNULL(?, 15));

The PHP code may look as:
$query = "INSERT INTO shoppinglist (name,age) VALUES(?, IFNULL(?, 15));";
$stmt = $pdo->prepare($query);
$stmt->execute(['Alex', 30]);
$stmt->execute(['Jane', null]);

PHP PDO online fiddle


text:
Q: Parsing a document with BeautifulSoup while not-parsing the contents of  tags I'm writing a blog app with Django. I want to enable comment writers to use some tags (like , a, et cetera) but disable all others.
In addition, I want to let them put code in  tags, and have pygments parse them.
For example, someone might write this comment:
I like this article, but the third code example could have been simpler:

#include <stdbool.h>
#include <stdio.h>

int main()
{
    printf("Hello World\n");
}

Problem is, when I parse the comment with BeautifulSoup to strip disallowed HTML tags, it also parses the insides of the  blocks, and treats <stdbool.h> and <stdio.h> as if they were HTML tags.
How could I tell BeautifulSoup not to parse the  blocks? Maybe there are other HTML parsers better for this job?

A: The problem is that  is treated according to the normal rules for HTML markup, and content inside  tags is still HTML (The tags exists mainly to drive CSS formatting, not to change the parsing rules).
What you are trying to do is create a different markup language that is very similar, but not identical, to HTML. The simple solution would be to assume certain rules, such as, " and  must appear on a line by themselves," and do some pre-processing yourself.

*

*A very simple — though not 100% reliable — technique is to replace ^$ with <![CDATA[ and ^$ with ]]>. It isn't completely reliable, because if the code block contains ]]>, things will go horribly wrong.

*A safer option is to replace dangerous characters inside code blocks (<, > and & probably suffice) with their equivalent character entity references (<, > and &). You can do this by passing each block of code you identify to cgi.escape(code_block).

Once you've completed preprocessing, submit the result to BeautifulSoup as usual.

A: From Python wiki
>>>import cgi
>>>cgi.escape("<string.h>")
>>>'<string.h>'

>>>BeautifulSoup('<string.h>',
...               convertEntities=BeautifulSoup.HTML_ENTITIES)

A: Unfortunately, BeautifulSoup can not be blocked to parse the code blocks.
One solution to what you want to achieve is too
1) Remove the code blocks
soup = BeautifulSoup(unicode(content))
code_blocks = soup.findAll(u'code')
for block in code_blocks:
    block.replaceWith(u'')

2) Do the usual parsing to strip the non-allowed tags.
3) Re-insert the code blocks and re-generate the html.
stripped_code = stripped_soup.findAll(u"code", u"removed")
# re-insert pygment formatted code

I would have answered with some code, but I recently read a blog that does this elegantly.

*

*http://iboris.com/page/add-source-code-syntax-highlighting-your-django-content-pygments.html

A: EDIT:
Use python-markdown2 to process the input, and have users indent the code areas.
>>> print html
I like this article, but the third code example could have been simpler:

    #include <stdbool.h>
    #include <stdio.h>

    int main()
    {
        printf("Hello World\n");
    }

>>> import markdown2
>>> marked = markdown2.markdown(html)
>>> marked
u'
I like this article, but the third code example could have been simpler:
\n\n
#include <stdbool.h>\n#include <stdio.h>\n\nint main()\n{\n    printf("Hello World\\n");\n}\n
\n'
>>> print marked

I like this article, but the third code example could have been simpler:

#include <stdbool.h>
#include <stdio.h>

int main()
{
    printf("Hello World\n");
}

If you still need to navigate and edit it with BeautifulSoup, do the stuff below.
Include the entity conversion if you need the '<' and '>' to be reinserted (instead of '<' and '>').
soup = BeautifulSoup(marked,
                     convertEntities=BeautifulSoup.HTML_ENTITIES)
>>> soup

I like this article, but the third code example could have been simpler:

#include <stdbool.h>
#include <stdio.h>

int main()
{
    printf("Hello World\n");
}

def thickened(soup):
    """

    blah blah <entity> blah
        blah

    """
    codez = soup.findAll('code') # get the code tags
    for code in codez:
        # take all the contents inside of the code tags and convert
        # them into a single string
        escape_me = ''.join([k.__str__() for k in code.contents])
        escaped = cgi.escape(escape_me) # escape them with cgi
        code.replaceWith('%s' % escaped) # replace Tag objects with escaped string
    return soup

A: If  element contains unescaped <,&, > characters inside the code than it is not a valid html. BeautifulSoup will try to convert it to a valid html. It is probably not what you want.
To convert the text to a valid html you could adapt a regex that strips tags from an html to extract the text from a  block and replace it with cgi.escape() version. It should work fine if there is no nested  tags. After that you could feed sanitized html to BeautifulSoup.


text:
Q: htaccess capture all domains + subdirectories except one and redirect I would like to capture all domain names pointing to my server and redirect them to my main domain. This answer helped me part of the way in capturing all domains that aren't the main domain, but i would also like to capture all the sub directories and point them to the home page, for example:
a) old.com => example.com
b) old.com/test => example.com
c) old.com/variable/1/2/3/4 => example.com
my current code only works for point a)
RewriteCond %{HTTP_HOST} !.*example\.com$ [NC]
 RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]

A: This seemed to do the trick.
RewriteCond %{HTTP_HOST} !.*example\.com$
RewriteCond %{HTTP_HOST} ^(?:www\.)?([a-z0-9-]+\.[a-z]+) [NC]


text:
Q: How to filter data from mongo collection subarray with subarray data of other collection Baiscally making a node.js, mongodb add friends functionality where having the option of list user to add in friends list, sent friends request, accept friends request, delete friends request, block friends request.
Register Collection
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

let Register = new Schema(
    First_Name:{
        type: String,
        required: true
    },
    Last_Name: {
        type: String
    },
    Email: {
        type: String,
        unique: true,
        lowercase: true,
        required: true
    },
    Friends:[{type: String}],
});

module.exports = mongoose.model('Register', Register);

Friends Collection
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ObjectId = require('mongodb').ObjectID;
let Friends = new Schema({
    Requester: {
        type: ObjectId,
        required: true
    },
    Recipients: [{Recipient:{type:ObjectId},Status:{type:Number}}],

});
module.exports = mongoose.model('Friends', Friends);

Inside Node.js Post API
var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res)
{
let Email="example@example.com";

Register.findOne({ Email : Emails }, function(err, user) {

Friends.findOne({ Requester :user._id  }, function(err, user1) {

Register.find({$and:[{Friends:{$nin:[user._id]}},{_id:{$ne:user1.Recipients.Recipient}}]},function(err, user2) {

console.log("user2",user2);

//Here User2 data is not coming

//How to get data so can able to list user that is not added yet in FriendList

//Mainly user1.Recipients.Recipient this is not working because //Recipients is array so how can match all data with array, if i am //using loop then find return data scope ends on inside find closing //braces only.

//Any suggestion

 });

 });
});

A: So if I have it correct, you want to do the following:

*

*Find a registration based on a given email

*Find the friends related to this user

*Find registrations that are not yet in the friend list of the user

Also, given what you've typed, I'm assuming A can be the friend of B, but that doesn't mean B is the friend of A.
While the data structure you currently have may not be optimal for this, I'll show you the proper queries for this:
var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res) {
    const email = "example@example.com";

    Register.findOne({ Email: email }, function(err, user) {
        if (err) {
             console.error(err);
             return;
        }

        Friends.findOne({ Requester: user._id }, function(err, friend) {
            if (err) {
                console.error(err);
                return;
            }

            const reciptientIds = friend.Recipients.map(function (recipient) {
                return recipient.Recipient.toString();
            });

            Register.find({Friends: { $ne: user._id }, {_id: { $nin: recipientIds }}, function(err, notFriendedUsers) {
                if (err) {
                    console.error(err);
                    return;
                }

                console.log(notFriendedUsers);
            });
        });
    });
});

P.S. This "callback hell" can be easily reduced using promises or await/defer

A: Finally able to solve it, below is the solution
var Register = require('../models/register.model');
var Friends =require('../models/friends.model');

router.post('/getdata',function(req,res)
{
let Emails="example@example.com";

 Register.findOne({$and:[{ Email : Emails}] }, function(err, user) {
              if (err) {
                   console.error(err);
                   return;
              }

              Friends
              .findOne({ Requester: user._id },
                    { _id: 0} )
              .sort({ Recipients: 1 })
              .select( 'Recipients' )
              .exec(function(err, docs){
                  docs = docs.Recipients.map(function(doc) {
                    return doc.Recipient; });
                  if(err){
                      res.json(err)
                  } else {
                    console.log(docs,"docs");
                      Register.find({$and:[{Friends: { $ne: user._id }},{_id: { $nin: docs }},{_id:{$ne:user._id}}]}, function(err, notFriendedUsers) {
                        if (err) {
                            console.error(err);
                            return;
                        }

                        console.log(notFriendedUsers);
                    });

                  }
              })
            });