text:
Q: image open with wallpaper app i am creating a simple wallpaper app in which i have a image_view and a button.
image-view is showing a image, now what i want: i want to open image with wallpaper app on button click.
when i click button it should show all installed wallpaper app so i can choose any of them
to better understand see screenshot: this should happen when i click button

this is my code:
package com.example.wallpaper_test;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class WallpaperScreenActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wallpaper_layout);

        // image resource
        ImageView img = (ImageView) findViewById(R.id.imageView1);
        img.setImageResource(R.drawable.pop);

        // call installed wallpaper app to set wallpaper on button click
        Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View vx) {

            }
        });

    }
}

A: This question has been answered here
    Uri uri = Uri.parse("URI_OF_YOUR_IMAGE");

    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setDataAndType(uri, "image/jpeg");
    intent.putExtra("mimeType", "image/jpeg");
    this.startActivity(Intent.createChooser(intent, "Set as:"));


text:
Q: How to catch all exceptions as soon as they occur by just one rescue statement I know how to catch the exceptions but what we do is to put "rescue" after a suspicious section of a code. what if you had a lot functions sending a query to mysql through mysql2 gem and you want to catch their exceptions. One thing you can do is to put a "rescue" statement in each of them. but i want to do that just by one rescue statement. So I put a "rescue" in end of code and put all of code in a "begin" and "end" but it didn't work.
Here is my code and as you see there is a problem in mysql query and just because of "rescue" being end of file, it doesn't catch the exception but when I put it after that query it works.
    require 'mysql2'
require 'colored'

begin

def log(string)
  p "["+string.cyan+"]"
end

def err
  p "["+"FAIL".red+"]"
end

def done
  p "["+"DONE".red+"]"
end

class SqlClient
  def initialize()
    log "SqlClient/initialize"
    puts "Host: \n"
    @host = gets.strip
    puts "User: \n"
    @user = gets.strip
    puts "Pass: \n"
    @pass = gets.strip
    @client = Mysql2::Client.new(host: @host , username: @user , password: @pass)

  end

  def list_databases()
    puts "We are listing your databases(not just projects) \n \n \n "
    @client.query("ELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA").each do |row|
      p row["SCHEMA_NAME"]
    end

    puts "\n \n \n"

  end

end

    rescue Mysql2::Error
    err
    abort

end

    `query': You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'ELECT SCHEMA_NAME FROM
INFORMATION_SCHEMA.SCHEMATA' at line 1 (Mysql2::Error)

I'm not looking for something like:
begin
  # my code
rescue # this line is right after the code which is going to have problem and we catch it.

end

I'm looking for something like this:
begin
  # first method
  # second method
  # thrid method
  # rest of code and etc ...
  # now this is end of file:
rescue
end

but as you saw in my code, it didn't work.
UPDATE: I found a similar question here and it seems there will be no answer :| maybe this is a sort of ruby Weakness.

A: if you want to see ANY error just use e for example
begin
  # your call to a method of Mysql2 gem. for example:
  client = Mysql2::Client.new(:host => "localhost", :username => "root", etc...)

rescue => e
  puts e.message
  puts e.backtrace.inspect

end

In order to catch every exception you'd need to wrap each method call with a begin rescue end. When an exception is raised it bails out of the execution so it wouldn't hit the next methods.
To catch all errors I guess I'd do something like this. Keep in mind, this is ugly and I'd recommend for you NOT to do this, but... if you want to try, maybe try something like this:
all_errors = []

# first method you call
begin
  # some error might happen here
  first_response = Mysql2::Client.new(:host => "localhost", :username => "root", etc...)
rescue => e
  all_errors << e
end

# second method you call
begin
  # some error might happen here
  second_response = Mysql2::Client.new(:host => "localhost", :username => "root", etc...)
rescue => e
  all_errors << e
end

puts all_errors.inspect

After a quick search I've found: (http://coderrr.wordpress.com/2008/11/07/the-simple-way-to-print-exceptions-in-ruby/)
# catch all exceptions (anything that derives from Exception)
begin
  ...
rescue Exception
  puts $!, $@
end

A: You could use an at_exit handler, which has access to the last exception in  $!
like
 at_exit {
   puts "the exception that killed us is", $!
 }

If you want to catch Exceptions "as soon as they occur" (not after they're caught) you could use ruby's "debug mode" (which outputs messages when they occur to the console) or ruby-debug see Is there any way to start the Ruby debugger on exception?

A: Just wrap all your code in:
begin

   #yourcode
   #as much as you want
rescue

end

A: Nobody seemed to notice it but using rescue without a class will catch all StandardError and there are so much more.
If you want to catch ALL exceptions you need to do
begin
  # your code where you call SqlClient.new etc
rescue Exception => e
  puts "error raised"
  puts [e, e.backtrace].flatten.join("\n")
end

List of all error classes:

Exception
 NoMemoryError
 ScriptError
   LoadError
   NotImplementedError
   SyntaxError
 SignalException
   Interrupt
 StandardError
   ArgumentError
   IOError
     EOFError
   IndexError
   LocalJumpError
   NameError
     NoMethodError
   RangeError
     FloatDomainError
   RegexpError
   RuntimeError
   SecurityError
   SystemCallError
   SystemStackError
   ThreadError
   TypeError
   ZeroDivisionError
 SystemExit
 fatal

A: have you tried adding an at_exit method in your class? This would allow you to do something when ruby is exiting. like in this article.
Ruby at_exit
or
From Ruby 2.0 API Docs
However beware of cleverly rescuing from an exception!
You'll start pulling your hair out down the road (or another dev will) when you try to figure out why your code isn't failing when it should be failing. I prefer to fail massively with a bright shiny sign saying the code failed here! hehe.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing a string as a const char* I have access to a class (not written by me) that takes a const char* as a parameter in the constructor. If I have a string that I want to pass the value of as a parameter, what is the safe way to pass it, keeping in mind that the string and the class object may have different scopes?
I don't have access to the source code for the class, so don't assume it's doing something sane like copying the string into a class member.
As a concrete example, this doesn't work:
#include <iostream>
#include <string>

class example {
public:
    example(const char*);
    const char* str;
};

example::example(const char* a) : str(a) {}

int main() {
    std::string* a=new std::string("a");
    example thisDoesntWork(a->c_str());
    std::cout << thisDoesntWork.str << std::endl;
    delete a;
    std::cout << thisDoesntWork.str << std::endl; //The pointer is now invalid
    a=new std::string("b");
    std::cout << thisDoesntWork.str << std::endl;
}

Replacing the constructor with this works (so far as I can tell) but is clearly pretty awful:
example thisDoesWorkButIsAwful((new const std::string(*a))->c_str()); //Memory leak!

Similarly:
char* buffer=new char[a->size()+1];
strcpy(buffer,a->c_str()); //with #include <string.h> added up top
example(buffer);

But again, this is prone to memory leaks.
My main idea at the moment is to make a wrapper class around example that copies the string into a char * buffer and deletes the buffer when it goes out of scope, but that seems a little heavy-handed. Is there an easier/better way?

A: Fundamentally, something needs to hold on to the memory - either you do it yourself or have it done automatically.
One way to do it automatically:
class SuperThatHoldsIt
{
    std::string mString ;
    SuperThatHoldsIt ( std::string const& str )
    :   mString ( str ) { }
} ;
class HoldingExample
:   private SuperThatHoldsIt
,   public example
{
    holdingExample ( std::string const& string )
    :   SuperThatHoldsIt ( string )
    ,   example ( mString.c_str() )
    { }
} ;

Then create it in a std::shared_ptr (or boost::shared_ptr) which will hold on to it.
std::string myString ( "Hello, world!" ) ;
std::shared_ptr<HoldingExample> value = std::make_shared<HoldingExample> ( myString ) ;

Now this holds onto the memory AND the structure.
Notes:
The reason HoldingExample derives from two supers is to that the order of constructors will work out because superclasses are always initialized before local variables. This means we have to construct example before our own member variables, but we can always initialize a superclass's and use its member variables.
If you pass this into a function, like
callFunction ( *value ) ;

If they hold on to that const char* after you've let go of your value, then you'll still have a leak and you really can't get around that.


text:
Q: How to get a markdown text in React Native? I have a question about writing dynamically text with markdown. I'm not sure how to get it so if you will help me It will be wonderful. I know that there are a few plugins when I can get a finished this effect about that but I want to learn something new for me and I don't want to use plugins into this.
So I have a TextInput with specific functions when I start writing something in this input, there will show a filtered list with suggesting options (it looks like Autocomplete ) and that's it. I would like to make font-weight bolder ( or change color etc. ) when letters from TextInput match in the list option suggestion. I tried to do with regex/replace but It's not working correctly.
To illustrate my problem:
Text in input: Al
Text showing in the list:
Alabama
California
Alaska
Img from emulator
Img with searched element from input in the list children
elements is an array where I have strings with names of States ( it's just an example ).
  const mapData = elements.map((text: string, i: number) => {
    const regexValue = new RegExp(inputValue, 'g');
    const changeColor = <Text style={{color: 'red'}}>{inputValue}</Text>;
    const showResult = text.replace(regexValue, changeColor);

    return (
      <KeyboardAvoidingView key={text + i}>
        <TouchableOpacity
          style={styles.itemListStyle}
          onPress={() => changeText(text, false)}
          disabled={isDisabled}
          activeOpacity={1}>
          <Text
            style={StyleSheet.flatten([
              styles.textItem,
              {textAlign: textAlignList},
              {...listElementsStyles},
            ])}>
            {text}
            {/* showResult */}
          </Text>
        </TouchableOpacity>
      </KeyboardAvoidingView>
    );
  });

Do you have any advice on what should I do?

A: I figured it out.
There is a little piece of code about that what I did.
  const mapData = elements.map((text: string, i: number) => {
  const hlStyles = {color: 'red', fontWeight: 'bold', fontSize: 20};

    return (
      <TouchableOpacity
        key={text + i}
        style={itemListStyle}
        onPress={() => changeText(text, false)}
        disabled={isDisabled}
        activeOpacity={1}>
        <Text
          style={StyleSheet.flatten([
            textItem,
            {textAlign: textAlignList},
            {...listElementsStyles},
          ])}>
          {hlText(text, inputValue, hlStyles)}
        </Text>
      </TouchableOpacity>
    );
  });

I created a new function called hlText:
   export const hlText = (text: string, value: string, ...styles: object) => {
      const index = text.toLowerCase().indexOf(value.toLowerCase().trim());

      const substringText = (index: number, endIndex: number) => {
        return text.substring(index, endIndex);
      };

      if (index > -1) {
        return [
          <Text key="text1">{substringText(0, index)}</Text>,
          <Text key="text2" style={styles}>
            {substringText(index, index + value.length)}
          </Text>,
          <Text key="text3">{substringText(index + value.length)}</Text>,
        ];
      }
    };

and it's working so maybe this post is gonna help someone!
Working img


text:
Q: pyod for EEG outlier detection I have segments of EEG data as 19 epochs:
np.shape(epoch)
Out: (19, 2)

For ith epoch, epoch[i][0] is the data and epoch i is the time. So,
np.shape(epoch[0][0])
Out: (5, 127501)

is the data from five EEG channels corresponding to time array
np.shape(epoch[0][1])
Out: (127501,)

I want to run a for loop 19 times in which I perform outlier detection on each epoch. I am new to this, so I simply tried the first method recommended on the documentation:
clf = ECOD()
clf.fit(epoch[0])

# get outlier scores
y_train_scores = clf.decision_scores_

However, I get the error:
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

I wanted to know how can I pass my data to clf.fit(). Also, is there a particular method (other than ECOD) that one would recommend for EEG outlier detection?


text:
Q: Java to introduced the temporary objects I am not able to see any major GC is getting triggered in my application server. This is because, I have assigned more memory which is 4GB. And maximum it is going upto 1GB. I just want to see a Full GC to be happened.
To triggered a Full GC , I need to full the heap memory which is not possible while my application is running. So, Planning to put some temporary object while starting the server and fill the Heap at lease 3.5GB.
Can anybody help me out to give me some approach?
Thanks in advance

A: Here is the simple code for temporary object creatation . Hope , it may help you.
for(int i=0;i<100000;++i){
map.put(UUID.randomUUID(),UUID.randomUUID());
}

declare the map as a global variable and on each request execute this loop.

A: You can trigger GC from the code by: System.gc()
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#gc()

A: You can perform
jmap -histo:live {pid}

and this will trigger a full collection in any Java application.

A: Here is the required gist where the above scenarios has been replicated and tested using visualVM.
https://gist.github.com/cooligc/eb9ba490e14a10d939147bd9c914afdd

A: When the GC is triggered it only cleans the objects that you do not have access to any more (their references point to null);
So make sure to assign null to objects' references after completing using them
SomeObject obj = new SomeObject();
  /*
     use obj
  */
  obj = null;

That's how the GC knows that the object needs to be cleaned.
You can also take a look on soft reference and weak reference.


text:
Q: Vector error correction model output I'm struggling with the interpretation of one of my course examples.
Here is the R output
 library(urca)
    rates.co <- ca.jo(data_rate, type = "eigen", ecdet = "const", K = 2, spec = 'transitory', season = NULL)

    summary(rates.co)
##
## ######################
## # Johansen-Procedure #
## ######################
##
## Test type: maximal eigenvalue statistic (lambda max) , without linear trend and constant in cointegration
##
## Eigenvalues (lambda):
## [1]  2.839734e-01  1.863156e-01  1.390916e-01  7.538804e-02  3.502591e-02
## [6] -5.514428e-17
##
## Values of teststatistic and critical values of test:
##
##           test 10pct  5pct  1pct
## r <= 4 |  7.56  7.52  9.24 12.97
## r <= 3 | 16.62 13.75 15.67 20.20
## r <= 2 | 31.75 19.77 22.00 26.81
## r <= 1 | 43.71 25.56 28.14 33.24
## r = 0  | 70.82 31.66 34.40 39.79
##
## Eigenvectors, normalised to first column:
## (These are the cointegration relations)
##
##                cofi.l1  X1ycmt.l1  X5ycmt.l1 primeRate.l1 X3mTbill.l1
## cofi.l1       1.000000  1.0000000  1.0000000     1.000000  1.00000000
## X1ycmt.l1    -5.016228  2.8868596  2.3696681     1.613084  2.44060485
## X5ycmt.l1     1.447589 -0.9385606 -1.3010429    -1.864387 -3.90107940
## primeRate.l1  1.798685  0.2357253  0.9647242    -3.533503 -2.05938244
## X3mTbill.l1   1.274463 -3.3546732 -3.1195849     2.575369 -0.04422163
## constant     -7.582615 -0.2506138 -2.4391828    13.674437 20.63481751
##                constant
## cofi.l1       1.0000000
## X1ycmt.l1    -0.9501416
## X5ycmt.l1     0.6813733
## primeRate.l1 -2.7068548
## X3mTbill.l1   2.2016130
## constant      3.7872633
##

## Weights W:
## (This is the loading matrix)
##
##                 cofi.l1    X1ycmt.l1    X5ycmt.l1 primeRate.l1
## cofi.d      -0.03002766 -0.025996453  0.001132855 -0.005679920
## X1ycmt.d    -0.02895731  0.034635064 -0.021423063 -0.005731646
## X5ycmt.d    -0.02949078  0.000379748  0.041174443  0.018020526
## primeRate.d -0.04390107  0.028939965 -0.066368855  0.007284998
## X3mTbill.d  -0.04602132  0.113886433 -0.017776290 -0.011264136
##               X3mTbill.l1      constant
## cofi.d      -2.078558e-05  4.181518e-17
## X1ycmt.d     9.894523e-03  1.014418e-16
## X5ycmt.d     1.145797e-02 -4.228840e-16
## primeRate.d  5.813215e-04  1.985921e-16
## X3mTbill.d   5.261185e-03  1.341192e-16

    library(tsDyn)
    vecm<-VECM(data_rate, lag=2-1, include = 'const', estim = 'ML', r=4)
    summary(vecm)

## #############
## ###Model VECM
## #############
## Full sample size: 214    End sample size: 212
## Number of variables: 5   Number of estimated slope parameters 50
## AIC -4907.008    BIC -4725.753   SSR 26.22101
## Cointegrating vector (estimated by ML):
##             cofi         1ycmt         5ycmt     primeRate    3mTbill
## r1  1.000000e+00 -8.326673e-17  0.000000e+00  1.110223e-16 -0.9659268
## r2 -2.081668e-16  1.000000e+00 -1.110223e-16 -5.551115e-17 -1.0839784
## r3 -2.775558e-17  1.110223e-16  1.000000e+00  0.000000e+00 -1.0269771
## r4  5.551115e-17  0.000000e+00  5.551115e-17  1.000000e+00 -0.9514607
##
##
##                    ECT1                ECT2
## Equation cofi      -0.0606(0.0138)***  0.0690(0.0404).
## Equation 1ycmt     -0.0198(0.0517)     0.1848(0.1518)
## Equation 5ycmt     0.0320(0.0623)      0.2752(0.1830)
## Equation primeRate -0.0738(0.0295)*    0.1585(0.0867).
## Equation 3mTbill   0.0397(0.0405)      0.4991(0.1190)***
##                    ECT3                ECT4
## Equation cofi      -0.0097(0.0160)     -0.0389(0.0162)*
## Equation 1ycmt     -0.0362(0.0604)     -0.0501(0.0610)
## Equation 5ycmt     -0.1307(0.0727).    -0.0836(0.0735)
## Equation primeRate -0.0184(0.0345)     -0.1624(0.0348)***
## Equation 3mTbill   -0.1295(0.0473)**   -0.0363(0.0478)
##                    Intercept          cofi -1
## Equation cofi      0.1527(0.0593)*    0.2211(0.0647)***
## Equation 1ycmt     0.2005(0.2230)     -0.0020(0.2434)
## Equation 5ycmt     0.3884(0.2687)     -0.2470(0.2933)
## Equation primeRate 0.5904(0.1273)***  0.1548(0.1390)
## Equation 3mTbill   0.2179(0.1747)     0.1439(0.1907)
##                    1ycmt -1            5ycmt -1
## Equation cofi      -0.0422(0.0569)     0.0006(0.0319)
## Equation 1ycmt     -0.0086(0.2141)     0.2610(0.1200)*
## Equation 5ycmt     0.1253(0.2580)      0.3309(0.1447)*
## Equation primeRate -0.0946(0.1223)     0.0696(0.0686)
## Equation 3mTbill   -0.1980(0.1678)     0.1649(0.0941).
##                    primeRate -1        3mTbill -1
## Equation cofi      0.0630(0.0329).     0.0856(0.0494).
## Equation 1ycmt     -0.0642(0.1237)     0.1667(0.1857)
## Equation 5ycmt     -0.0211(0.1491)     -0.2666(0.2239)
## Equation primeRate -0.0156(0.0707)     0.3743(0.1061)***
## Equation 3mTbill   -0.0234(0.0970)     0.3131(0.1456)*

    round(vecm$model.specific$coint, 3)

##               r1     r2     r3     r4
## cofi       1.000  0.000  0.000  0.000
## 1ycmt      0.000  1.000  0.000  0.000
## 5ycmt      0.000  0.000  1.000  0.000
## primeRate  0.000  0.000  0.000  1.000
## 3mTbill   -0.966 -1.084 -1.027 -0.951

So from what I understood, I got 4 cointegrating vectors since my test rejected $r \leq 3$ and accepted $r \leq 4$ at 5% critical level.
At the very end I have 4 cointegrating vectors written in a column, which, from what I understood, form a matrix for $\beta$ in the VECM.
What I do not understand though is how to derive the $\alpha$ matrix from this output or, generally speaking, how do I write my final equation for the ECM in a matrix form.

A: The first r columns of the loading matrix gives you $\alpha$.
You can also get all the coefficients for the VECM easily with the cajorls() function:
vecm <- cajorls(rates.co)
vecm$rlm$coefficients
vecm$beta

The VECM in matrix form is: $\Delta X_{t} = \alpha(\beta' X_{t-1} - \mu) + \Gamma_{1} \Delta X_{t-1} + \epsilon_{t}$ where $\alpha$ is the first four columns of the loading matrix and indicates how quickly the rates converge to the equilibrium relationship.  $\beta$ contains the weights on the rates in the co-integrating relationships while the constant terms for the relationships go in $\mu$.  $\Gamma_{1}$ is not show in the ca.jo summary output but can be shown with ca.jorls().


text:
Q: MT2002 Missing reference in Xamarin Forms IOS When I am trying to deploy the application to device I am getting this strange error. Any idea how to fix it?
/***/MTOUCH: Error MT2002: Failed to resolve "System.Void Xamarin.Forms.Log::Warning(System.String,System.String)" reference from "Xamarin.Forms.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" (MT2002) (Project.iOS)

Its working fine in iOS simulator and on Android Device

A: Try to erase the bin/obj folders from your project and do a clean and rebuild.
Do you have the latest Xamarin.Forms packages updates?
It looks like a reference is missing so it may be a few things like the build configuration of your project or the NuGet packages itself I hope this helps.


text:
Q: How to stop alert once it had been successfully triggered? I am working with Javascript with D3, and firebase. Not XML Http request.
The difficulty I am having is how to introduce a while loop and boolean to alert my message once it has been successfully executed.
In other words, when they pass the 20% mark, it should alert them once, when I refresh the page, it should not alert them again. I used alert as a reference guide because as a beginner, that is the only novice function I can use. If there alternatives way to achieve the results without alert() function but can alert(notify) users, that would be great.
I am thinking
var boolean = true
while  (...)  <--not sure how
boolean = false; after my alert is triggered.  Since I am a beginner in javascript, the for loop is required because the data is read and put into D3 javascript chart.
My question is how do I introduce a while loop to check the conditions and booleans but still have the for loop inside. SAFE and shouldn't go to infinite loop.
I tried a variety, but debugging is difficult.
  var data = snapshot.val();
  var dataArray = [];

  for (var number in data)
  {
    var percentage = data[number].Percentage;

    dataArray.push({valorX: data[number].Team, valorY: percentage});
        if(percentage >="0.2" && percentage <= "0.39")
        {
            alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
        } else if (percentage >= "0.4" && percentage <= "0.59")
        {
           alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
        }
        else
        {
            console.log(percentage);

  }
  }

A: Use variable to store the status. Use browser storage to persist status.
var data = snapshot.val();
var dataArray = [];

var status = window.localStorage.getItem('status') ? JSON.parse(window.localStorage.getItem('status')) : {};

for (var number in data)
{
  var percentage = data[number].Percentage;
  // set team name as key
  var key = data[number].Team;
  var current = status[key] ? status[key] : {}

  dataArray.push({valorX: data[number].Team, valorY: percentage});
    if(percentage >="0.2" && percentage <= "0.39" && !current.twenty2fourty)
    {
        alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
        current.twenty2fourty = true;
        window.localStorage.setItem('status', JSON.stringify(status));
    } else if (percentage >= "0.4" && percentage <= "0.59" && !current.fourty2sixty)
    {
       alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
       current.fourty2sixty = true;
       window.localStorage.setItem('status', JSON.stringify(status));
    }
    else
    {
        console.log(percentage);
    }
  }

Then status then should have a format of:
{
  "team1": {"twenty2fourty" : true},
  "team2": {"fourty2sixty" : true},
  "team3": {"twenty2fourty" : true, "fourty2sixty": true}
}

A: var alertObj = {};

for (var number in data)
    {
        var percentage = data[number].Percentage;
        var key;

        dataArray.push({valorX: data[number].Team, valorY: percentage});
                if(percentage >="0.2" && percentage <= "0.39")
                {
                        key = data[number].Team + "--20%"
                        if(!alertObj[key]){
                            alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
                        }
                        else {
                            alertObj[key] = true;
                        }

                } else if (percentage >= "0.4" && percentage <= "0.59")
                {
                        key = data[number].Team + "--40%"
                        if(!alertObj[key]){
                            alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
                        }
                        else {
                            alertObj[key] = true;
                        }

                }
                else
                {
                        console.log(percentage);

    }
    }

key will be in format "{teamname}--20" in case of 20%.
this way you can keep track of which team is notified of which mark.


text:
Q: Best practices implementing Security in multiple Web application We are using Spring Security and it is working fine in the single web application. Now, I need to create another Web application with Spring security. In the first application the user can sell his/her stuff (e.g. EBay). The second app which I am creating now, it is for general users where he can save his general preferences, searches, save some items he looked at etc. He may/may not be the existing user. So the difference between the two users are:
User 1 (existing user): Can post his stuff for sale.
User 2: He/she should be able to login. Save his general activities etc. & if he/she wants to sell his/her item, he/she needs to go thru the additional steps for verification.
All this cannot be done in just one application due to some reasons. My question is on how to handle the security? Should I create separate security filters for each applications or is there a way to use common security implementation who can manager both of these application. Please provide your feedback, I would really appreciate it.

A: if you wrap both components in two different webapps, each will have his own spring security web filter infrastructure.
So in principle there will be a security session for each web application, to be backed by whatever authentication system you use.
If you use JDBC then the user would have to login twice.
If you want your customers to only login once, you can for example use a token based system.
When you cross link from webapp 1 to webapp 2, you could hook the links up to a redirect servlet.
The servlet then generates a token, persists it in a database and forwards the user with the token in the url to the other webapp.
In spring security you can then implement your own PRE_AUTH_FILTER which reads out the token, verifies if it is persisted in the Database.
For security reasons you should make these tokens only one use.


text:
Q: Scala Curly braces with and without return statement I am trying to understand the basics of scala curly braces and with/without return statement.
def method(a:Int):Int = {
           if(a == 10 ) 10
           if(a == 11 ) {11}
           if(a == 12 ) { return 12 }
           if(a == 13 ) return {13}
           1}

Method Call
Output

method(10)
1

method(11)
1

method(12)
12

method(13)
13

From the above we can note that

*

*the output of calls to method(12) & method(13) are as expected.

*Whereas the output of calls to method(10) & method(11) we see the value returned is 1 which is confusing given return keyword is not required for scala.

Another thing I noted was that :
def method(a:Int) = {
           if(a == 10 ) 10
           if(a == 11 ) {11}
           if(a == 12 ) {12}
           if(a == 13 )  {13}
           }

Method Call
Output

method(10)
()

method(11)
()

method(12)
()

method(13)
13

The above two method statements seems confusing.
Kindly help to clarify the above why there is difference in values returned.
Thanks in advance.

A: The curly braces are irrelevant in this code; they can all be omitted without any effect on the result.
As far as return goes, do not use it unless you know what it does (which isn't what you think it does).
The value of a function is the value of the last expression in the function, so you need to make the if statements into a single if/else expression:
def method(a: Int) =
       if (a == 10) 10
       else if(a == 11) 11
       else if(a == 12) 12
       else if(a == 13) 13
       else 1

In practice a match is a better choice for this sort of code.


text:
Q: How to use DarkSky API request with $.loadJSON? My weather app needs to use weather info, so I used DarkSky to give me that info. I decided to use jQuery's $.loadJSON to fetch weather data from the API. Why is the code below not working?
I've tried looking at the jQuery documentation but found no errors. I've swapped $.loadJSON() for $.ajax() and $.get(). I have tested that the longitude and latitude are correct. I've made sure there are no console errors.

let latitude = place.geometry.location.lat();
let longitude = place.geometry.location.lng();
let api = `https://api.darksky.net/forecast/[API Key]/${latitude},${longitude}`;

$.getJSON(api, (data, status, xhr) => {
    alert("API called.");

    let locationElement = document.querySelector("[data-location]");
    let statusElement = document.querySelector("[data-status]");
    let temperatureElement = document.querySelector("[data-temperature]");
    let humidityElement = document.querySelector("[data-humidity]");
    let windElement = document.querySelector("[data-wind]");

    locationElement.innerHTML = place.formatted_address;
    statusElement.innerHTML = data.currently.summary;
    temperatureElement.innerHTML = data.currently.temperature;
    humidityElement.innerHTML = data.currently.humidity;
    windElement.innerHTML = data.currently.windSpeed;
});

My expected result is that the code would edit all the labels on the page to the weather information. The actual result is that nothing happened. The labels stayed at their default state.

A: You should get console errors. If you don't, then you might have an additional problem.
There is little point in trying to solve that though. As they explain in their FAQ, they do not permit client-side cross-origin requests for security reasons.

Why do I get the error No 'Access-Control-Allow-Origin' header is
  present on the requested resource when I try to call the API? We take
  security very seriously at Dark Sky. As a security precaution we have
  disabled cross-origin resource sharing (CORS) on our servers.
Your API call includes your secret API key as part of the request. If
  you were to make API calls from client-facing code, anyone could
  extract and use your API key, which would result in a bill that you'd
  have to pay. We disable CORS to help keep your API secret key a
  secret.
To prevent API key abuse, you should set up a proxy server to make
  calls to our API behind the scenes. Then you can provide forecasts to
  your clients without exposing your API key.


text:
Q: проблемы с отображением, при создании сапера c++ sfml Итак, я рисую двумерный массив (19 на 19) карты сапера, если рисовать весь двумерный массив, то приходится выводить каждый элемент массива. Но это слишком медленно и из-за этого событие мыши происходит не сразу (т.е ячейка открывается с маленькой задержкой).
Есть еще один вариант - это рисовать определенную ячейку, но он у меня тоже не получился т.к при рисовании определенной ячейки другие пропадают и остается только эта ячейка, (пропадают все кроме тех на которые я нажал), но после второго нажатия ячейки появляются итак по кругу.
все ячейки

первый клик

второй клик

третий клик

сам код
sf::Texture draw_grid_element(char element)
{
    sf::Texture texture;

    switch (element)
    {
    case 'p':
        texture.loadFromFile("images/plite.jpg");
        return texture;
    case '0':
        texture.loadFromFile("images/pass.jpg");
        return texture;
    case 'b':
        texture.loadFromFile("images/bomb.jpg");
        return texture;
    case '1':
        texture.loadFromFile("images/one.jpg");
        return texture;
    case '2':
        texture.loadFromFile("images/two.jpg");
        return texture;
    case '3':
        texture.loadFromFile("images/three.jpg");
        return texture;
    case '4':
        texture.loadFromFile("images/four.jpg");
        return texture;
    case '5':
        texture.loadFromFile("images/five.jpg");
        return texture;
    case '6':
        texture.loadFromFile("images/six.jpg");
        return texture;
    case '7':
        texture.loadFromFile("images/seven.jpg");
        return texture;
    case '8':
        texture.loadFromFile("images/eight.jpg");
        return texture;
    default:
        break;
    }
}

void draw_game_grid(sf::RenderWindow &window)
{
    sf::Sprite tile;
    for (int i = 1; i < TILE_HEIGHT_COUNT; i++)
    {
        for (int j = 1; j < TILE_WIDTH_COUNT; j++)
        {
            sf::Texture texture = draw_grid_element(draw_grid[i][j]);
            tile.setTexture(texture);

            tile.setPosition((i * TILE_SIZE) - TILE_SIZE, (j * TILE_SIZE) - TILE_SIZE);
            window.draw(tile);
        }
    }
}

window.display();
while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();

        if (event.type == sf::Event::MouseButtonPressed)
        {
            if (event.mouseButton.button == sf::Mouse::Left)
            {
                int mouse_x = event.mouseButton.x / TILE_SIZE + 1;
                int mouse_y = event.mouseButton.y / TILE_SIZE + 1;

                draw_grid[mouse_x][mouse_y] = game_grid[mouse_x][mouse_y];
                draw_element(window, mouse_x, mouse_y);
                window.display();
            }
        }

    }

}


text:
Q: Resolve a circular static reference I have 2 static initializers trying to call each other:

*

*one in a Configuration class, that reads configuration parameters from a properties file;

*one in a LoggerFactory class, which sets up the default logging parameters.

The problem is they reference each other:

*

*the Configuration class needs the logger to log potential I/O issues when reading the properties file.

*the LoggerFactory needs the Configuration file to setup the log file name, log patterns and default log level.

This is obviously not right and I get some NPE here and there.
Is there a standard way of dealing with that kind of situation?

A: Use a default logger that requires no configuration and is replaced when the configurable logger is loaded. That way you can resolve the circular dependency with ease in a simple manner.

A: You can separate the configuration for the logger and have it initialize before the configuration class. Even though this is not ideal, I've seen this done on several projects.

A: You should create a logger that loads when the program starts but then have it later overridden when the logger than can be configured is created.


text:
Q: Log Sequence Numbers in Full BackUp and Log Backup My full back-up starts daily at 02:00 AM. It takes about 3 hours.
I also take T-Log back-ups every 15 minutes (at 15,30,45 and 00 hours).
I can verify the LSN sequences of T-log backups when I "restore headeronly".
However, there seem to be a gap between the last LSN of the full backup and the T-log backup taken immediately after backup had started (i.e 02:15)
Below is restore headeronly output from the full backup started at 02:00
FirstLSN: 76583000073086500011
LastLSN: 76595000084143900001
...and this is the restore headeronly output from the log backup started at 02.15
FirstLSN: 76570000086250400001
LastLSN:  76571000009693900001
Shouldn't the last LSN of the full back up and first LSN of log back up be the same?
I compared the LSNs of the log back up taken at 05:15 and 05:00 (when the full back up has finished) but there is no sequence again.
I also checked RESTORE FILELISTONLY of the full backup and CreateLSN, DropLSN of log file is 0.
What is it that I might be missing here?
Thank you.

A: LastLSN + 1 of the Full database backup will fall in between the FirstLSN and LastLSN of its subsequent transaction log backup.
(http://www.mssqltips.com/sqlservertip/3209/understanding-sql-server-log-sequence-numbers-for-backups/)

A: A transaction log contains transaction details for many parallel  both transactions that are (a) completed or (b) still processing.
A transaction log backup is intended to harden the log file with all data needed to restore the database to the point in time that includes the last completed transaction.  This also includes all the transactions still in process, even though they have no known state until they either commit or rollback.
Therefore, the FirstLSN of a log backup needs to include the oldest incomplete transaction so as to be able to cover all cases of committed or rolled back transactions.
Note: That also explains why a long running open transaction may make the database log file grow excessively.  The log file must continue to maintain all of the LSNs that contain transactions back to the oldest still open transaction.


text:
Q: How to check configurable product have size option? If the configurable product has size, I want to add a size guide for it. But how can I check that product have the size or not?

A: Try this
  //check product is configurable

  if ($product -> getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){
      //if product is configurable

      $product -> hasData('size');
          //OR
      $product  > hasSize();

  }

Hope this help you, Thanks

A: Option 1:
$size = $_product->getResource()->getAttribute('size')->getFrontend()->getValue($_product);

Option 2
$size = $_product->getSize();

Then you just need to check it exists and output your block
if($size) {
      $this->getLayout()
          ->createBlock('Magento\Cms\Block\Block')
          ->setBlockId('size_guide')
          ->toHtml();
}

A:  use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

 class yourclass{
  const CONFIGURABLE = "configurable";

   protected $_productCollection;

   public function __construct(

    CollectionFactory $collectionFactory,
    ) {
      $this->_productCollection = $collectionFactory;
    }

    public function yourfunction
    {
      $products = $this->_productCollection->create();
      foreach($products as $product){
       if ($product->getTypeId() == self::CONFIGURABLE ) {
       if($product->getOptions()){
         // if options are their
         // do your rest of work
      }else{
       //if no options are their
        }
       }
     }
}

A: Thank you all, you guys. I have checked it by this code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');

$data = $product->getTypeInstance()->getConfigurableOptions($product);

$show_size = false;
foreach ($data as $key => $value) {
     if($value['0']['attribute_code'] == 'size')
     {
         $show_size = true;
         break;
     }
}

Hope this helps someone!


text:
Q: Data.Typeable cast and Maybe pattern match behavior in Haskell Based on this QA;
A new type for all a (normal value) and nothing in Haskell?
Here's the first working code:
import Data.Typeable (Typeable, cast)

data None = None

none :: None
none = None

f :: Typeable a => a -> a
f = \x ->
  case (cast x :: Maybe None) of
    Just None -> undefined
    Nothing -> x

test :: IO ()
test = do
  print $ f (5 :: Int)  --5
  pure $ f none
  print "done"

This code works as I intended.
Now, I want to make this optionMap and here is the non-working code with an error:
import Data.Typeable (Typeable, cast)

data None = None

none :: None
none = None

optionMap :: Typeable a => (a -> b) -> a -> b
optionMap = \f -> \x ->
  case (cast x :: Maybe None) of
    Just None -> undefined
    Nothing -> f x

test :: IO ()
test = do
  print $ optionMap (\a -> a + 1) (5 :: Int) -- 6
  pure $ optionMap (\a -> a + 1) none
  -- No instance for (Num None) arising from a use of '+'
  print "done"

Surely, I understand the meaning of the error, however, I expect it pattern-matched as Just None as the first working example, then the value should be undefined.
Is it possible to fix?

A: Well, I specifically said in my answer to your other question that Typeable isn't a good tool to address this goal. But sure, let's see if we can fix it.
For starters, this is pretty silly:
optionMap :: Typeable a => (a -> b) -> a -> b
optionMap = \f -> \x ->
  case (cast x :: Maybe None) of
    Just None -> undefined
    Nothing -> f x

If the function f can handle arguments of type a, and we have an x of type a, there's no need to check for None at all; f x is valid. If you really want optionMap, you don't want it to have this type.
To see why, let's look at the way you were calling it. With optionMap (\a -> a + 1) none you need all these types to unify:
(\a -> a + 1) :: Num t =>   t -> t
none ::                                None
optionMap :: Typeable a => (a -> b) -> a    -> b

I've lined them up (and use globally unique names for type variables) to make it clear what type inference is going to happen. We're going to decide that a ~ t, and b ~ t, but also that a ~ None. If any of these facts were not true, we would have a type error. So GHC assumes they are all true, but that gives us as a combined type of optionMap:
optionMap :: (Typeable None, Num None) => (None -> None) -> None -> None

Not very helpful! The whole point of None was that the function wouldn't be applied if it was None, so we don't want any of the constraints from the function to end up as constraints on the a when we pass a None in that position. The only way we can achieve that is by having the type of the function parameter's parameter be a different type variable from the second parameter of optionMap. So:
optionMap :: (Typeable a, Typeable a') => (a' -> b) -> a -> b

But now optionMap accepts any type a, not just the a' values that can be passed to its function parameter. What we need is to then use cast the other way around from the way you used it; check if it's safe to pass x to f and handle that specially (by returning f x), and put our do-nothing case in the branch where the cast failed. Something like:
optionMap :: forall a a' b. (Typeable a, Typeable a') => (a' -> b) -> a -> b
optionMap f x =
  case (cast x :: Maybe a') of
    Just x' -> f x'
    Nothing -> undefined

Note that doing that requires the ScopedTypeVariables extension (otherwise in the cast x :: Maybe a' the a' is a new local type variable, not a reference to the a' from optionMap's signature), and requires we explicitly introduce the type variables with forall (that's how you declare a larger-scope type variable that can be referenced from more than one signature, with ScopedTypeVariables).
Lets try it:
{-# LANGUAGE ScopedTypeVariables #-}

import Data.Typeable

data None = None
none = None

optionMap :: forall a' a b. (Typeable a, Typeable a') => (a' -> b) -> a -> b
optionMap f x =
  case (cast x :: Maybe a') of
    Just x' -> f x'
    Nothing -> undefined

main :: IO ()
main = do
  print $ optionMap (\a -> a + 1) (5 :: Int)
  pure $ optionMap (\a -> a + 1) none
  print "done"

Unfortunately we get a bunch of messages like:
foo.hs:17:3: warning: [-Wdeferred-type-errors]
    • Ambiguous type variable 'a0' arising from a use of 'print'
      prevents the constraint '(Show a0)' from being solved.
      Probable fix: use a type annotation to specify what 'a0' should be.

With the Typeable constraints, GHC is no longer willing to default the ambiguous types to Integer. Plus we've disconnected the type of the function parameter and the other paramter to optionMap, so the explicit annotation in (5 :: Int) tells us nothing about the type of the function (which we need to know in order for cast to tell us whether 5 :: Int is the same type!), so it' probably good that GHC won't default types of the functions or it would have picked Integer -> Integer, which doesn't match. I frequently try to use Bool or Char in these small test programs rather than numbers, for exactly this reason; Num and defaulting just make everything a little more complicated. But ets try that again with more types:
{-# LANGUAGE ScopedTypeVariables #-}

import Data.Typeable

data None = None
none = None

optionMap :: forall a' a b. (Typeable a, Typeable a') => (a' -> b) -> a -> b
optionMap f x =
  case (cast x :: Maybe a') of
    Just x' -> f x'
    Nothing -> undefined

main :: IO ()
main = do
  print $ optionMap (\a -> a + (1 :: Int)) (5 :: Int)
  pure $ optionMap (\a -> a + (1 :: Int)) none
  print "done"

Great it compiles, and if we run it:
❯ runhaskell foo.hs
6
"done"

But there's a problem:
main :: IO ()
main = do
  print $ optionMap (\a -> a + (1 :: Int)) (5 :: Int)
  pure $ optionMap (\a -> a + (1 :: Int)) 'a'
  pure $ optionMap (\a -> a + (1 :: Int)) True
  pure $ optionMap (\a -> a + (1 :: Int)) (5 :: Integer)
  pure $ optionMap (\a -> a + (1 :: Int)) (print False)
  print "done"

All of these also happily take the non-equal types path. We haven't written optionMap so that it accepts either None or the type that matches the function's argument, we've made it accept any type at all, and applies the function if the types happen to match. Which means the type checker is completely unable to detect any mistakes we make. Any mistake where we intended the types to match but we messed up will be silently ignored.
We can try explicitly handling None:
optionMap :: forall a' a b. (Typeable a, Typeable a') => (a' -> b) -> a -> b
optionMap f x =
  case (cast x :: Maybe a') of
    Just x' -> f x'
    Nothing ->
      case (cast x :: Maybe None) of
        Just None -> undefined
        Nothing -> error "what do we put here?"

But no matter how many layers deep of cast and case we go, we're going to be left with that final "it could be absolutely anything else" case; we don't end up with a clean optionMap that accepts the correct type to apply the function or None, and nothing else.
What we need is a way to make a type for that second parameter that isn't just a universal a, but rather is a specific type for None or a'. That's exactly what you asked the other question about, and is exactly what I said Typeable wouldn't really help you do.
Haskell of course has an extremely uncomplicated and easy way of representing the choice between two types: discriminated unions, AKA algebraic data types with multiple constructors. That's exactly what you have already rejected because "the complication that deliver to code is far from justified at least for my purpose".

Before I address how you can actually address your need, I need to come back to another problem with your attempt: why are you using undefined? undefined does not "do nothing"; it isn't a neutral value can use when you haven't got what you need, as null is often used in other programming languages. When Haskell hits a place you've written undefined it terminates the program with an error message. I suspect you know that, because you didn't write print in the line of your test program that was supposed to handle the none example of using optionMap, you wrote pure.
pure of course wraps up the result in an IO Int, but because we do anything with it nothing actually happens. We'd get exactly the same result from:
main :: IO ()
main = do
  print $ optionMap (\a -> a + (1 :: Int)) (5 :: Int)
  pure $ error "didn't run"
  print "done"

So it's a pretty pointless test of optionMap. What actually happens if we try to use it, changing the pure to a print:
❯ runhaskell foo.hs
6
foo.hs: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at foo.hs:12:16 in main:Main

Using optionMap _ none isn't a type error, but if it ever actually gets evaluated it terminates the program with an error. If we were happy with that we could skip this whole attempt and just use:
print $ (\a -> a + 1) 5
print $ (\a -> a + 1) undefined

Because undefined is a member of every type (along with infinite loops, and error "whatever", and a whole host of other ways of writing the bottom value), we can already just pass a "wrong" value when we haven't got a real one, if we're happy with this "error out at runtime" behaviour (which I personally am not).
So even if we could put in even more work and somehow get a type for optionMap that works the way you want, it still doesn't give you the ability to feed in a none to a computation expecting some other type and have the program ignore it. To do that you'd need to also have some way of "mapping" print across your "might be nothing, might be a value"; making it apply print (or any other IO action) if the value is there, and just do nothing if the value was None. Something like:
main :: IO ()
main = do
  print `ioOption` optionMap (\a -> a + 1) (Some 5)
  print `ioOption` optionMap (\a -> a + 1) None
  print "done"

Where I've just swapped out the $ operator, which was directly applying print to the result of optionMap, for some new ioOption that applies print to the result of optionMap only if it is not None. You'll have just as much trouble implementing that as you do implementing optionMap.

Now, I know you said that using discriminated unions just added too much complexity to your code for you to bother with for your present purposes (although you seem to be willing to put in far more effort to avoid Maybe than you are to put into using it). But for completeness, I am going to show how these problems are solved using discriminated unions, in all their horrible "complexity":
data Option a = Some a | None

optionMap :: (a -> b) -> Option a -> Option b
optionMap _ None = None
optionMap f (Some x) = Some (f x)

ioOption :: (a -> IO ()) -> Option a -> IO ()
ioOption _ None = pure ()
ioOption f (Some x) = f x

main :: IO ()
main = do
  print `ioOption` optionMap (\a -> a + 1) (Some 5)
  print `ioOption` optionMap (\a -> a + 1) None
  print "done"

And running this:
❯ runhaskell bar.hs
6
"done"

Things to note here:

*

*The types are much simpler, and say exactly what they do; we still get the full power of Haskell's error checking (try changing Some 5 to Some True)

*The implementation of optionMap is much simpler than any of our attempts with Typeable; we just write a case for None and a case for Some and we're done, which is about the minimal number of moving parts it would be possible to use

*That's just about the only possible implementation we can give for optionMap. Haskell is (almost) forcing us to write correct code. (The only other things we could do that would pass the typechecker are return Nothing even in the Some case, return bottom/undefined, return bottom/undefined inside the Some constructor, or start messing with unsafe functions; all of those are obviously incorrect, so it's not hard to avoid accidentally writing any of them)

*No extensions needed

*We don't have to explicitly type annotate our numbers; Haskell's normal defaulting mechanism just works for us again

Of course, everything above (other than main) is already implemented for you. So you don't even need to write Option, optionMap, or ioOption. Option is Maybe, of course, optionMap is fmap, and ioOption is mapM_ from Data.Foldable (or traverse_ - they're the same thing only traverse_ has a more general type; they both exist for historical reasons). So we can just write:
import Data.Foldable

main :: IO ()
main = do
  print `mapM_` fmap (\a -> a + 1) (Just 5)
  print `mapM_` fmap (\a -> a + 1) Nothing
  print "done"

Basically, whatever complexity you think you're avoiding by avoiding Maybe (or other discriminated unions), I guarantee you the alternatives are more complicated. You may just be not seeing how you can use the interfaces of Maybe (and other types) to write simpler code, in which case I'd be happy to answer further questions here. If you really just don't like writing constructor tags so much that things along the lines of our attempts at optionMap here seem preferable (if they could work), then you're really not going to enjoy using Haskell; it is a fundamental part of the language.

For the sake of completeness, I did think of one way to get an optionMap that really accepts "a function and either a value that can be passed to the function or None". It's not pretty, but it does work:
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeFamilies #-}

data None = None

type family OptionResult a b
  where OptionResult None _ = None
        OptionResult _ b = b

class OptionMap a b a'
  where optionMap :: (a -> b) -> a' -> OptionResult a' b

instance OptionMap a b None
  where optionMap _ _ = None

instance (OptionResult a b ~ b) => OptionMap a b a
  where optionMap f x = f x

class OptionTraverse a a'
  where optionTraverse :: Applicative f => (a -> f ())-> a' -> f ()

instance OptionTraverse a None
  where optionTraverse _ _ = pure ()

instance OptionTraverse a a
  where optionTraverse f x = f x

main :: IO ()
main = do
  (print :: Int -> IO ()) `optionTraverse` optionMap (\a -> a + (1 :: Int)) (5 :: Int)
  (print :: Int -> IO ()) `optionTraverse` optionMap (\a -> a + (1 :: Int)) None
  print "done"

The problem with this approach is it destroys type inference. GHC needs to know the type of everything very precisely in order to resolve the instance and type family we're using. GHC won't use the input and output types of the various function's we're using to constrain each other's types because we don't directly connect them with each other; if their types were wrong we wouldn't get a type-mismatch error, we'd get an error about it being unable to resolve the type class. And thus any polymorphic thing (like print) can't have its type resolved by connecting with something else; we have to explicitly provide a type annotation.
So this approach is not something I recommend. Programming with it with any scale will be very difficult. I include it only to show you the lengths you have to go to get your idea of how this should be done to work in Haskell, as compared to the extremely simple example using Maybe that does what you want, just not How you wanted it to work. (I would argue that the "how" of the Maybe approach is also a better way for it to work, but that is subject to taste, so I won't say that is definitive; I think you will have to agree it is simpler and easier to use, however)


text:
Q: MonoDevelop "The compiler appears to have crashed. Check the build output pad for details." I have MonoDevelop 2.4.2, MonoTouch 3.2.6 and XCode 3.2.6.
In MonoDevelop, whenever I have a syntax error, the only error I have in my error list is "The compiler appears to have crashed. Check the build output pad for details.".  The build log does contain the actual compiler errors so I am able to fix them and get a successful compilation.  However, my coworker demonstrated that his compiler does not crash and the compiler errors listed in the build log actually are parsed and displayed in the error list window.  Also his MonoDevelop IDE then displays the message bubbles pointing out the errors in the code.  Mine does not do this.
Does anyone know how I can get the compiler to quit crashing and the IDE to be able to parse the errors and warnings from the build log like normal?

A: I've discovered the problem.  The path in which I had my source code stored had parenthesis.  When I pulled down source code from another repository into a path on my system without parenthesis, I got compiler errors in the list instead of just a compiler crash.  I confirmed this was the problem by relocated the other source code that I was having the problem with.
This also solved another one of my issues.  When I was adding files, the path in the .csproj file would be relative paths but they would go up several levels and back down messing it up for the next developer.  (So instead of having Views/file.cs I'd have ../../../MySourceCodeRoot/Application/Project/Views/file.cs or something close to that.)  Adding files with my source code root renamed without parenthesis works correctly now.

A: Send the error to monotouch support team
May be they can help you.
May be you have installed all the staff not in the right order


text:
Q: How to get Infromation Link query from Spotfire Library Database I am new to Tibco Spotfire and I am working on a query to retrieve the query used by/generated by Spotfire while designing an information link.
I have access to the Library DB which saves the metadata of all the items/elements used in dashboards and stuff like that. I have been able to locate the information link items in the DB but I can't find the actual query that is used by the information link.
I need a solution that can be implemented from the DB, UI solutions are already in use and I am looking to automate that manual process of going to each info-link and clicking the "SQL" button in the Information Designer tool
so far I have come across [this link] (https://support.tibco.com/s/article/How-to-find-the-manually-modified-SQL-query-used-by-a-particular-Information-Link) on Tibco's community forum but it doesn't show the autogenerated queries (only the manually modified queries).
Any and all help on this will be much appreciated
Thanks

A: This should be in the SQL logs on the server.  Attempt to open the info link.  Then, log into the server.  Go to the folder where your spotfire installation is and find a folder that looks like this...
\Tibco\tss\10.3.6\tomcat\logs
...and you want the SQL.txt file.  Search for your user name.


text:
Q: CSS changer using PHP not working Yo. I'm a beginner at PHP but I wanted to make a CSS changer for my website (tbex.info). I found a nice looking script on about.com which basically says I should put this in the head tags:
<link rel="stylesheet" type="text/css" href="<?php echo (!$style)?'main':$style ?>.css" />

And then a form on the page that looks like this:
<form action="changestyle.php" method="post">
<select name="choice">
<option value="main" selected>Classic View</option>
<option value="small">Smaller (for smaller resolutions)</option>
</select>
<input type="submit" value="Go">
</form>

And then the form loads this script:
<?php
  $Year =31536000 + time();
  setcookie('style', $_GET['choice'], $year);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
?>

I am currently working in Dreamweaver. When I typed all this up, the styling in Dreamweaver disappeared (as expected, since it's PHP) then I uploaded it to my server for beta tests. The code is supposed to load the default CSS and then when a user changes it by using the form, the PHP script is supposed to write a cookie and then reload the page. Then, the code in the head tags would read the cookie and change the CSS accordingly. So far, every SEEMS to have worked, other than the writing of cookies. I went into my browser setting (Google Chrome) and viewed all of my cookies. There was none that had come from my website. I've checked various forums and not found any real help. If anyone can help me fix this, or even help me write a CSS changing code (I'm looking for something a bit like the one on 4Chan.org), it would be very much appreciated. Thanks in advance!

A: If you don't need to use cookies, you can do this quite easily in a few different ways:
1. Use Session Variables
Have your form post to a page with code like this:
<?php

    session_start();
    $_SESSION["css"] = $_POST["choice"];

?>

And then to retrieve it in your header:
<link rel="stylesheet" type="text/css" href="<?php
    session_start();
    if(isset($_SESSION["css"]))
        $style = $_SESSION["css"];
    else
        $style = "main";
    echo $style; ?>.css" />

2. Use $_GET Variables
Your form script:
<?php

    header("Location:".$_SERVER["HTTP_REFERER"]."?css=".$_POST["choice"]);

?>

And then to access it:
<link rel="stylesheet" type="text/css" href="<?php
    $style = $_GET["css"];
    echo (!$style)?'main':$style ?>.css" />

Some Clarification for a Beginner's Understanding:
Option #1 stores the string chosen in the form in what is called your "session." This is a short term variable maintained by your server during the user's activity period. Most servers have sessions set to expire after ~20 minutes of inactivity, but this can be changed to any number.
It should be noted that sessions are innately cookies, but PHP manages it for you, and all you need to do to access or change a variable in a session is $_SESSION["var_name"]. The great thing about sessions is that they are propagated to any PHP page on your website that implements session_start();. The not-so-great (in your case) aspect is that they are temporary, and will not remain on the user's device after an inactivity period.

When using $_GET variables, as in option #2, you are sending each page individually the variable. This is what you see when you get a URL like this:
http://www.example.com/index.php?someVar=blah

This provides your page index.php with a $_GET variable named "someVar" with a value of "blah." To retrieve this, you simply use $_GET["someVar"]. The great thing about this is that it can be sent and retrieved in a relatively easy fashion, through direct URLs or AJAX calls, but the bad thing is that it has to specified on every URL. It is not automatically shared between all PHP pages. In many cases this is a good thing, for instance, if you wanted to specify different CSS on each page or an ID number specific to each page, but in your case, this is not the easiest option to implement.

Therefore:
I would use session variables. They are easy to access, modify, and share between all pages.
Cookies are an animal to deal with. If I were you, I would stick to something more simple like this. If you need to store the choice over the long term, e.g. between sessions, I would use an SQL database to hold the data, rather than a cookie.

A: This can be the script that the form loads.
<?php
session_start();
$_SESSION['choice'] = $_GET['choice'];
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>

And this can be your link.
<?php session_start(); ?>
<link rel="stylesheet" type="text/css" href="<?php echo (!isset($_SESSION['choice']))?'main':$_SESSION['choice'] ?>.css" />

I also am a php beginner so just tell me if I made any mistakes in my answer.


text:
Q: Task Scheduler is not executing exe in windows server 2008 R2 I have configured a Task scheduler which is supposed to run exe, but its not working.

 Exe is working fine as a stand alone & also in these cases :

*

*When we enable option "Run only when the user is logged on".

*Under "Change User or group" when we select Administrators.

Task Scheduler is not working when I try to run it as a Local Account i.e, the account with which I am logging in.

I have tried most of the option present in blogs like setting Start In paramaeter,executing via cmd.exe.

I tried to add Local Account to the Administrators group also but still no luck.

A: Have you selected the "Run whether user is logged-in or not" check box? You will then be asked to supply the account credentials. Note that the job won't run if it requires network resources and you've selected the check box "Do not store password". More details here.
I normally use the LocalService or NetworkService account.
You might also want to look at the Windows event log to see if either the executable or the Task Scheduler itself produced an exception. Additionally the Scheduled Task viewer has a "Last Result" column with a result value.


text:
Q: How to be able to write in a file inside a docker image? I have a docker image created with the following Dockerfile
FROM ubuntu

RUN useradd -ms /bin/bash seltest
RUN mkdir /home/seltest/output
RUN touch /home/seltest/output/test.out
WORKDIR /home/seltest
RUN chown -R seltest:seltest .
COPY script.sh /home/seltest
USER seltest

CMD ["bash", "script.sh"]

which essentially creates a new user seltest and then executed the script script.sh:
echo 'test' > /home/seltest/output/test.out

I create the docker image with the following command
docker build -f Dockerfile -t testimage  .

and run it on the host with the following command:
docker run --rm  -it  -v ${PWD}/output:/home/seltest/output testimage

but I get an error
script.sh: line 1: /home/seltest/output/test.out: Permission denied

The local folder I created beforehand named output is empty.
Why do I get this error? How to set up a shared folder that the docker user seltest can write to? What am I doing wrong here?

A: You mount /home/seltest/output/ from your host OS, so it is has permissions and ownership from host OS. Make it writable for everyone and you won't have a problem in the container:
$ chmod 777 ${PWD}/output
$ docker run --rm  -it  -v ${PWD}/output:/home/seltest/output testimage

Of course, safer option will be, when you configure write permission with better granularity, not write for all. It can be a problem, because user seltest exists only in the container. Better option will be if you define also user id, when you are creating seltest user, so you will be to allow write access for that user id on the directory ${PWD}/output level.

A: I changed your dockerfile to the one below
FROM ubuntu

RUN useradd -ms /bin/bash seltest
RUN mkdir /home/seltest/output
RUN touch /home/seltest/output/test.out
WORKDIR /home/seltest
COPY script.sh /home/seltest
RUN chmod +x /home/seltest/script.sh
RUN chown -R seltest:seltest .
USER seltest

CMD ["bash", "script.sh"]

What did I do?
Set the script copy before you change the owner of the home sub contents. This to avoid permission problems on the script.
Still permission denied
After running this you will still have a permission denied problem executing
docker run --rm  -it  -v ${PWD}/output:/home/seltest/output testimage

Reason and possible solution
This is because your user inside your container has no write access to the folder that you are mounting from the host system.
To solve this you can:

*

*Give chmod 643 ${PWD}/output

*Create the user on the host system and than create the user inside the container with the same UID

*Give the user that has the UID 1000 on you host system write access to the folder: RUN useradd -u ${UID} -ms /bin/bash seltest

*Use the user nobody in the container and set the group rights from the host folder to nobody. Setting the rights on the host can be done by jenkins or by a docker preparation image that starts up, change group, shutdown


text:
Q: beanShell json body for post method on Jmeter can anyone help to add escape quotation marks with slash like \" on this son body:
    {
  "firstName": "teo",
  "lastName": "leo",
  "companyName": "abc",
  "restaurantId": "54d34443e4b0382b3208703d",
  "phones": [
    {
      "label": "Mobile",
      "value": "123456789",
      "countryCode": "+123",
      "isPrimary": true
    }
  ],
  "addresses": "haha"
}

i've tried with this one but beanShell PreProcessor can't accept it
String formvalues = "{\"firstName\": \"teo\",\"lastName\": \"leo\",\"companyName\": \"abc\",\"restaurantId\": \"54d34443e4b0382b3208703d\",\"phones\": [{\"label\":\"Mobile\",\"value\": \"123456789\",\"countryCode\": \"+123\",\"isPrimary\": true}],\"addresses\": \"haha\"}"

thanks you so much!

A: If you want to keep formatting:
String formvalues = "{\n" +
        "  \"firstName\": \"teo\",\n" +
        "  \"lastName\": \"leo\",\n" +
        "  \"companyName\": \"abc\",\n" +
        "  \"restaurantId\": \"54d34443e4b0382b3208703d\",\n" +
        "  \"phones\": [\n" +
        "    {\n" +
        "      \"label\": \"Mobile\",\n" +
        "      \"value\": \"123456789\",\n" +
        "      \"countryCode\": \"+123\",\n" +
        "      \"isPrimary\": true\n" +
        "    }\n" +
        "  ],\n" +
        "  \"addresses\": \"haha\"\n" +
        "}";

If you want single line (mind that Content-Length will be different)
String formvalues = "{\"firstName\":\"teo\",\"lastName\":\"leo\",\"companyName\":\"abc\",\"restaurantId\":\"54d34443e4b0382b3208703d\",\"phones\":[{\"label\":\"Mobile\",\"value\":\"123456789\",\"countryCode\":\"+123\",\"isPrimary\":true}],\"addresses\":\"haha\"}";

Full code to generate the body and add it as parameter:
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.util.HTTPArgument;

String formvalues = "{\n" +
           "  \"firstName\": \"teo\",\n" +
           "  \"lastName\": \"leo\",\n" +
           "  \"companyName\": \"abc\",\n" +
           "  \"restaurantId\": \"54d34443e4b0382b3208703d\",\n" +
           "  \"phones\": [\n" +
           "    {\n" +
           "      \"label\": \"Mobile\",\n" +
           "      \"value\": \"123456789\",\n" +
           "      \"countryCode\": \"+123\",\n" +
           "      \"isPrimary\": true\n" +
           "    }\n" +
           "  ],\n" +
           "  \"addresses\": \"haha\"\n" +
           "}";

Arguments arguments = new Arguments();
arguments.addArgument(new HTTPArgument("",formvalues));
sampler.setArguments(arguments);

JavaDoc on relevant classes:

*

*Arguments

*HTTPArgument

*HTTPSamplerProxy (shorthand for sampler)

See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on Beanshell scripting in JMeter.


text:
Q: smooth rounded corners in swift How can I create a UIButton with rounded corners that are smooth?
The standard apple rounded corners are much nicer than the standard rounded corners.
If I design a button in sketch, I can toggle "smooth corners" which toggles the corners of a shape from Apple rounded corners (smooth) to standard rounded corners.
Here is a comparison:

How can I toggle this in swift?
showContentButton.layer.cornerRadius = 20 rounds the corners, however, I don't really know if this rounded corners are "smooth corners" or "standard rounded corners". And I don't know how to toggle this. Any ideas?

A: Starting iOS 13.0, you can just use this property in addition to setting the cornerRadius:
sampleButton.layer.cornerCurve = .continuous

This is also easily animatable, which previously resulted in problems using a UIBezierPath.
See more at https://developer.apple.com/documentation/quartzcore/calayer/3152596-cornercurve

A: Just use this extension
extension CALayer {

   func roundCorners(radius: CGFloat) {
       let roundPath = UIBezierPath(
           roundedRect: self.bounds,
           cornerRadius: radius)
       let maskLayer = CAShapeLayer()
       maskLayer.path = roundPath.cgPath
       self.mask = maskLayer
   }

}

and use it like this
cell.layer.roundCorners(radius: 18)

A: Prior to iOS 13
To get that effect you can use UIBezierPath

Edit:
Usage in UIView
class MyView: UIView {

    let myButton UIButton = UIButton()

    override func layoutSubviews() {
        super.layoutSubviews()

        // your roundPath code here
    }

}

Edit 2:
Use this approach for rounding specific corners:
let roundPath = UIBezierPath(
    roundedRect: bounds,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: 10, height: 10)
)

Source

A: For SwiftUI, you can try this:
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))

Example:
Rectangle()
    .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
    .padding()

or use extension:
extension View {
    func smoothCornerRadius(_ x: CGFloat) -> some View {
        return self
            .clipShape(RoundedRectangle(cornerRadius: x, style: .continuous))
    }
}

Result here


text:
Q: How does the React library require its source libraries directly? I was looking through the source code of Facebook's React and saw that throughout the source of the project they don't specify relative paths for loading its own modules. For example, instead of doing var foo = require('../bar/foobar') the library uses var foo = require('foobar') as if the module was loaded in node_modules already for CommonJS to read.
I was just wondering how they managed to do this? I tried looking through their build steps through Grunt but couldn't see any packages that directly accomplish this.
For a more concrete example of the technique I"m talking about, here the library calls the flattenChildren module which exists in a different directory altogether without specifying the path.

A: React uses a tool called commoner.  Their configuration of it matches up the lines that look like this:
* @providesModule ReactChildReconciler

To require('ReactChildReconciler') calls.  They also put everything in a single directory, so the paths end up as require('./ReactChildReconciler').
The source code is organized in a structured way, but the module names are globally unique to the repo (and all of facebook's internal code, I think
[citation needed]).  This means there's no ambiguity in what it points to.

On the subject, there are also some other magical things in react's code.
The calls to invariant(assertion, explanation, ...) and the similar warning calls are transformed for the production build by removing the arguments after the first one to save space.  Warning calls are stripped entirely, because they're wrapped in the next piece of magic: development only blocks.
if (__DEV__) {
   ...
}

Which compiles to:
if (process.env.NODE_ENV !== 'production') {
   ...
}

Which, via envify, compiles to this (in development), and the code runs:
if ('development' !== 'production') {
   ...
}

And this in production:
if ('production' !== 'production') {
   ...
}

Which minifies to this:


text:
Q: How do Python developers manage Javascript/CSS library dependencies? Coming from C#, management of -all- dependencies was done using NuGet. In Python, PIP is used to manage python packages. Is there any de facto standard for managing Javascript and CSS library dependencies?

A: python is the language, I guess you mean some web platform like django. however, there is no javascript / css management tool at part of the platform.

A: well javascript and css are their own languages ... so just use that(NuGet) to manage your js/css ... python jquery is the same as .net jquery ...  if you are just looking for a javascript package manager then JAM works i think http://jamjs.org/ ...
bower.io also seems to be a sort of manager for css/js  ... but the python bit was misleading ... these have nothing to do with python specifically ...

A: In the Python world, Fanstatic is probably the most widely used (framework-agnostic) solution for that purpose.


text:
Q: How to bind a Tooltip's content to an MVVM property within code? Due the nature of our software, we have to create our datagrid columns dynamically in code behind and add it then to the datagrid like this:
DataGridBoundColumn dataGridBoundColumn = new DataGridTextColumn
                                                          {
                                                              CellStyle = ...,
                                                              Header = header,
                                                              Binding = binding
                                                          };
reportDataGrid.Columns.Add(dataGridBoundColumn);

Now we need a tooltip on the columnheader:
ToolTipService.SetToolTip(dataGridBoundColumn, "ENTER VALUE");

Well that works fine too. However I need to bind the tooltip's value to a property on the ViewModel.  I know how to do this in the xaml, but no idea how to do that in code.
Any help would be appreciated,
UPDATE:
Thanks to Steve's answer I was able to fix this slightly differently:
Binding bindingBoundToTooltipProperty = new Binding()
                                   {
                                       Source = reportDataGrid.DataContext,
                                       Path = new PropertyPath("ToolTipSorting")
                                   };

BindingOperations.SetBinding(dataGridBoundColumn, ToolTipService.ToolTipProperty, bindingBoundToTooltipProperty);

if the DataGridColumnHeaderStyle was customized, make sure to add these lines to the template as well:
<Trigger Property="IsMouseOver" Value="True">
    <Setter Property="ToolTip" Value="{Binding Column.(ToolTipService.ToolTip), RelativeSource={RelativeSource Self}}"/>
</Trigger>

A: You should be able to set up a binding as below:
BindingOperations.SetBinding(dataGridBoundColumn,
    ToolTipService.ToolTipProperty,
    new Binding("Path.To.My.Property"));

Note: the DataContext of this will be the value of the Header property on the column
You want to bind to a property on the view model; assuming that your view model is the DataContext for the DataGrid you would want to change the binding to something like:
new Binding("DataContext.ToolTipSorting")
{
    RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor)
    {
        AncestorType = typeof(DataGrid)
    }
}

This attempts to locate the first parent object of type DataGrid and grab the value of its DataContext.ToolTipSorting property.


text:
Q: FBSDKAppEvents.activateApp() unrecognized selector sent to instance I'm trying to integrate facebook sdk in my app, I have completed all the info.plist and importing sdk steps. When ever I run my app, when first viewloads I'm getting this error
    2015-04-04 21:09:43.105 TestFBApp[1468:27977] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb0513d5e52c2fe43
2015-04-04 21:09:43.173 TestFBApp[1468:27977] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb0513d5e52c2fe43'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000103e55a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000105e5ebb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000103e5cd1d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x0000000103db49dc ___forwarding___ + 988
    4   CoreFoundation                      0x0000000103db4578 _CF_forwarding_prep_0 + 120
    5   TestFBApp                           0x00000001036fbe9c +[FBSDKGraphRequestPiggybackManager addPiggybackRequests:] + 108
    6   TestFBApp                           0x000000010371a165 -[FBSDKGraphRequestConnection start] + 231
    7   TestFBApp                           0x00000001036fdb9a +[FBSDKServerConfigurationManager _loadServerConfigurationFromServerForAppID:] + 236
    8   TestFBApp                           0x00000001036fda97 +[FBSDKServerConfigurationManager _loadServerConfigurationForAppID:] + 252
    9   TestFBApp                           0x00000001036fce28 +[FBSDKServerConfigurationManager loadServerConfigurationWithCompletionBlock:] + 319
    10  TestFBApp                           0x000000010372d663 -[FBSDKLoginTooltipView presentInView:withArrowPosition:direction:] + 260
    11  TestFBApp                           0x000000010372ecf5 -[FBSDKTooltipView presentFromView:] + 968
    12  TestFBApp                           0x00000001037274a4 -[FBSDKLoginButton _showTooltipIfNeeded] + 225
    13  Foundation                          0x00000001044d02e5 __NSFireDelayedPerform + 387
    14  CoreFoundation                      0x0000000103dbd6c4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
    15  CoreFoundation                      0x0000000103dbd285 __CFRunLoopDoTimer + 1045
    16  CoreFoundation                      0x0000000103d8059d __CFRunLoopRun + 1901
    17  CoreFoundation                      0x0000000103d7fbc6 CFRunLoopRunSpecific + 470
    18  GraphicsServices                    0x0000000107874a58 GSEventRunModal + 161
    19  UIKit                               0x0000000104b99580 UIApplicationMain + 1282
    20  TestFBApp                           0x00000001036c6c0e top_level_code + 78
    21  TestFBApp                           0x00000001036c6c4a main + 42
    22  libdyld.dylib                       0x000000010855e145 start + 1
    23  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

This is my appdelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
    }

    func applicationWillResignActive(application: UIApplication) {

    }

    func applicationDidEnterBackground(application: UIApplication) {

    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

        FBSDKAppEvents.activateApp()
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

When i remove FBSDKAppEvents.activateApp() It works fine.

A: This happened to me once, make sure FacebookAppId is set to string not number in info.pList


text:
Q: Any Ruby on Rails equivalent to Pinax? Pinax is:

An integrated collection of Django
  applications that provides the most
  commonly needed social networking
  features, including openID support,
  email verification, site
  announcements, user-to-user messaging,
  friend invitations, interest groups
  with discussions, wikis, and more.

Cloud27 is a demonstration of Pinax
Any equivalent in Ruby on Rails?

A: maybe you also want to take a look at the following entry on stackoverflow that has a similar topic: Social Network in Rails - which framework


text:
Q: Huge outline in winterbash page on Firefox Open a hat in the winterbash page on Firefox, e.g.
http://winterbash2016.stackexchange.com/i-am-your-father
Then click the close button. When focused, it receives an outline.
The problem is that the text-indent: -999em hack used to hide its text does affect the outline:

Just add overflow: hidden to fix

A: I could not repro locally, but I've added the fix proposed. Can you confirm it's fixed now?


text:
Q: Angular 2 excel export not working I have created sample project to export data in excel format using JExcelApi lib. Project has Angular 2 frontend and spring mvc(rest api) backend. If I deploy backend to tomcat and make request via browser then it is exporting excel file correctly but when i make same http call using angular 2(typescript) then it is writing url of my api in the excel file and it shows as corrupted excel file.
Project is located at following github location
NG2 Excel Export demo
Can someone please tell me what is wrong with my service or app.component.ts file?
Here is the codebase in app.component.ts, which I think is causing the issue
downloadExcel(){
console.log("Downloading excel from server....")
this.fileService.downloadFile()
    .subscribe(data => window.open(window.URL.createObjectURL(data)),
        error => console.log("Error downloading the file."),
        () => console.log('Completed file download.'));

}
and here is the service class which returns the data
 downloadFile(){
    let url = "http://localhost:9999/api/download";
    var headers = new Headers();
    headers.append('responseType', 'arraybuffer');
    return this._http.get( url)
        .map(res => new Blob([res],{ type: 'application/vnd.ms-excel' }))
        .catch((error : any ) => Observable.throw(error));
}

A: I have fixed the issue with FileSaver.js, just in case if someone had this problem. Look at the above github project

A: It is better to use window.location.assign(link); instead.


text:
Q: PowerShell - Test-path I have a script that gets the drives on the host and outputs to a text file. The text file will contain something like the below -
D:
E:
F:
G:

I need to test each drive for a path and, if true, assign it to a variable.
I have the following so far, but it is not working.
Get-WmiObject win32_logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" | Select DeviceID | Format-Table -HideTableHeaders > c:\DeviceID.txt -Force
$DeviceID = Get-Content C:\DeviceID.txt
$DeviceID | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > c:\DeviceID.txt

$DeviceID = Get-Content C:\DeviceID.txt
$Path = "$DeviceID\Apps\NetprobeNT\"
$PathExists = Test-Path $Path

ForEach-Object ($DeviceID in $DeviceID)
{
    If ($PathExists -eq $True)
    {
        $DeviceDrive = $DeviceID}
    Else
    {
        $DeviceDrive = "C:"
    }
}

I have come across another method that works:
$Folder = "Apps\NetprobeNT"
Get-PSDrive | Where-Object {
    $_.root -match "[C-Z]:\\" -and (Test-Path $(Join-Path $_.root $Folder))
}

What is the best method to use?

A: You're saving the result of Test-Path to the $PathExists-variable outside the loop, before $DeviceID exists. The result will always be false. The variable never changes so it will be false every time inside the loop. You need to run Test-Path inside the loop.
Also, you should avoid saving and reading the wmi-output to a file. Try:
$DeviceDrive = "C:"

Get-WmiObject win32_logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" |
Where-Object { Test-Path "$($_.DeviceID)\Apps\NetprobeNT\" } |
Foreach-Object {
    $DeviceDrive = $_.DeviceID
}

A: Wow, you are really doing it the hard way...
$drives = (Get-WmiObject Win32_Logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'" | Select -ExpandProperty DeviceID).TrimEnd()

$deviceDrive = "C:"
foreach ($drive in $drives) {
    if (test-path "$drive\Apps\NetprobeNT\") {
        $deviceDrive = $drive
    }
}

For PowerShell V2:
$drives = Get-WmiObject Win32_Logicaldisk -Filter "DriveType=3 AND DeviceID!='C:'"

$deviceDrive = "C:"
foreach ($driveEntry in $drives) {
    $drive = $driveEntry.DeviceId
    if (test-path "$drive\Apps\NetprobeNT\") {
        $deviceDrive = $drive
    }
}


text:
Q: Add DatePicker range in single column of jqgrid filter I've been able to add a datepicker into the filter toolbar of a jqgrid with the code below.  However, I'm wondering if there's a way to squeeze two datepickers into this single DateCreated column, so as to specify the range (From, To).  Any ideas?
function loadGrid() {
    $(tableID).jqGrid({
    …
    colModel: [
    …
    { name: 'DateCreated', index: 'DateCreated', width: 125, searchoptions:{dataInit:datePick, att:{title:'Select Date'}} },
    …
    })
…
}

datePick = function(elem) {
    $(elem).datepicker();
}

A: If you are open to adding in a plugin, I found the range picker from filament group to be very easy to work with.  In under an hour, I had the 3 files downloaded and installed into my project, and the range picker working.
link:filament group daterangepicker
Being that I'm using jquery 1.8 in my project, I ended up getting an updated version from
link:Github filament group daterangepicker jquery 1.8
daterangepicker is also able to take all of the options that datepicker supports, so you shouldn't have much trouble converting.  Let me know if you have questions and I'll see if I can help.
For reference, the plugin is dual licensed with MIT and GPL.  This is the same license structure as jqgrid, so I assume if you are able to use jqgrid, than this plugin should not be a problem.
UPDATE: Adding Code Example
The important part of this code is in the colModel for date.  You simply specify a dataInit function for the search options, then add the daterangepicker.  Be careful on the capitalization.  That got me more than once.  The beforeSelectRow is simply some modification I did in order to make my checkboxes along the side behave as a radio button.  It is not needed for daterangepicker to work.
$("#myGrid").jqGrid(
            {
                url:url,
                datatype: "json",
                colNames:['Version','Date'],
                colModel:[
                          {name:'version', search:true, stype:'text'},
                          {name:'date', search:true,stype:"text",searchoptions:{dataInit:function(el){
                              $(el).daterangepicker({dateFormat:'yy/mm/dd'});
                            }
                          }}
                          ],
                          toolbarfilter: true,
                          sortname: 'version',
                          sortorder: "desc",
                          pager: jQuery('#myPager'),
                          viewrecords: true,
                          gridview: true,
                          multiselect: true,
                          beforeSelectRow: function(rowId)
                          {
                              var selectedIds = jQuery('#myGrid').jqGrid().getGridParam("selarrrow");
                              jQuery("#myGrid").jqGrid().resetSelection();
                              if(selectedIds)
                              {
                                  var id = selectedIds[0]
                                  if(id != rowId)
                                  {
                                      jQuery("#myGrid").jqGrid().setSelection(rowId, false);
                                  }
                              }
                              else
                              {
                                  jQuery("#myGrid").jqGrid().setSelection(rowId, false);
                              }
                          }
            });

A: I had to do the very same thing, and Joseph's answer above got me 90% of the way there. So, most of the credit is due to him.  I had to modify some stuff to get it to work because the filament date range picker allows for single dates (the today option, the specific date option, etc).  I also had to add some code to trigger the search after you selected your date.  Here's my update...the meat of what I needed to add was in the beginRequest function:
$(document).ready(function() {
        var grid = jQuery('#list').jqGrid({
            url: '/myajaxurl',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['Reference #', 'CreatedOn', 'Product', 'Model Number', 'Quantity', 'Transaction Type', 'Created By'],
            colModel: [
                { name: 'InventoryTransactionLogId', index: 'InventoryTransactionLogId', align: 'center', sortable: true, search: false },
                {
                    name: 'CreatedOn',
                    search: true,
                    stype: 'text',
                    align: 'center',
                    formatter: 'date',
                    formatoptions: { newformat: 'm-d-y  H:i' },
                    sortable: true,
                    searchoptions: {
                        dataInit: function(el) {
                            $(el).daterangepicker({ dateFormat: 'yy/mm/dd', onChange: datePick });
                        }
                    }
                },
                { name: 'ProductName', index: 'ProductName', align: 'center', sortable: true, search: false },
                { name: 'ModelNo', index: 'ModelNo', align: 'center', sortable: true, search: true },
                { name: 'Quantity', index: 'Quantity', align: 'center', sortable: true, search: false },
                { name: 'Description', index: 'Description', align: 'center', sortable: true, search: false },
                { name: 'UserName', index: 'UserName', align: 'center', sortable: true, search: false }
            ],
            loadtext: "Retrieving Inventory Transaction Log...",
            rowNum: 50,
            rowList: [25, 50, 100],
            sortname: 'InventoryTransactionLogId',
            sortorder: 'asc',
            pager: '#pager',
            ignoreCase: true,
            viewrecords: true,
            height: 450,
            autowidth: true,
            scrollOffset: 45,
            caption: 'Inventory Transaction Log',
            emptyrecords: "No records",
            jsonReader: {
                root: 'rows',
                page: 'page',
                total: 'total',
                records: 'records',
                repeatitems: false,
                cell: 'cell',
                id: 'InventoryTransactionLogId',
                userdata: 'userdata'
            },
            beforeRequest: function () {
                var theGrid = jQuery("#list");
                var postData = theGrid.jqGrid('getGridParam', 'postData');
                if (postData != undefined && postData.filters != undefined) {
                    postData.filters = jQuery.jgrid.parse(postData.filters);
                    //Remove if current field exists
                    postData.filters.rules = jQuery.grep(postData.filters.rules, function(value) {
                        if (value.field != 'CreatedOn')
                            return value;
                    });

                    // Parse the range picker field into start/end date
                    var dateRangeString = $('#gs_CreatedOn').val();

                    if (dateRangeString.length > 0) {
                        var dateRange = dateRangeString.split(' - ');

                        if (dateRange.length == 1) {
                            startDate = dateRange[0] + ' 00:00:00';
                            endDate = dateRange[0] + ' 23:59:59.999';
                        } else {
                            startDate = dateRange[0] + ' 00:00:00';
                            endDate = dateRange[1] + ' 23:59:59.999';
                        }

                        var startDateFilter = { "field": "CreatedOn", "op": "ge", "data": startDate };
                        var endDateFilter = { "field": "CreatedOn", "op": "le", "data": endDate };

                        // Add new filters
                        postData.filters.rules.push(startDateFilter);
                        postData.filters.rules.push(endDateFilter);
                    }
                } else {
                    jQuery.extend(postData, {

                    });

                }

                if (postData != undefined && postData.filters != undefined) {
                    postData.filters = JSON.stringify(postData.filters);
                    postData._search = true;
                }
                return [true, ''];
            }
        });

        $('.date').datepicker();
        grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "bw" });
        grid.jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });

    });

    datePick = function() {
        var grid = $("#list");

        $("#list")[0].triggerToolbar();
        $("#list").trigger("reloadGrid", [{ page: 1 }]);
    }