text:
Q: How to read second array from json arrays in Android I'm trying to read two json arrays from same request
JSON FILE:
{
"items": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}
{
"items1": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}

and the code I use to read is:
 //Convert JSON to String and gets our app version
    private String getJSON(String JSON_STRING){

        try {
            //Objects
            jsonObject=new JSONObject(JSON_STRING);
            jsonArray=jsonObject.getJSONArray("items");
            //Variables
            int count=0;
            String tempTitle, temAuthor;

            while (count<jsonArray.length()){

                //Reads Row by Row
                JSONObject JO= jsonArray.getJSONObject(count);
                tempTitle= JO.getString("title");
                temAuthor= JO.getString("author");

                //If our App found
                if (Constants.Title.equals(tempTitle)){

                    return temAuthor;
                }

                count++;

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return "Not Found!";
    }

but when I call to read the second table like items1 it says no table found?
I tried to add a (,) between tables but same, I'm newbie in both php and android so its hard for me to change the code, so it is any easy way for me, I mean any way to change less code to make it work, or I have to change my android method completely ?

A: Try the below JSON code,
{
  "items": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
  ,
  "items1": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}

You can check the validity of your JSON code in any of the online parser such as http://json.parser.online.fr/

A: I found the easiest way for me, @Michael Jaison answer works too, but I fount the easiest way, I just read all joined both json tables like

{table1}###{table2}

then in android I read all file then I split string:
String[] splitedResult = result.split("###");

so I got to tables
splitedResult[0] = { "items": [...
splitedResult[1] = { "items1": [...

Then just passed strings to method to read it :) and whoala it works :)


text:
Q: What is the word for "trappy"? Suppose a person has been accused of doing something wrong and a cunning policeman is questioning him. Suppose the police is asking questions in such a way that it is very likely that the accused person is likely to be found out if he, in fact, had done something wrong.
What can we say about the type of questions the policeman is asking. I am looking for an adjective like "trappy", if there were such a thing, meaning "full of traps". Are there any words like this?
EDIT- I would like to point out that please don't take my example as if the word could be used with Police procedure only. That was mere an example to let you understand the scenario. The word may describe conversation by anybody. Even one of my friends can also ask such questions of me if he/she has some doubts about me.

A: You could continue the trap metaphor with trap-laden.

A: I would say he is asking penetrating or pointed questions.

penetrating : Keenly perceptive or understanding; acute
pointed : cutting or incisive

Or for a more poetic take on it:
His line of questioning laid out an impenetrable minefield for the guilty.

A: Police interrogation techniques include the use of loaded and suggestive questions.

Unethical or unskilled police officers can use suggestive questioning in interrogation rooms. Such interrogators use different kinds of techniques and questions in order to get people to confess. They use response framing when getting people to falsely confess. This is when they purposely limit certain answers and suggest others. For example, they would ask someone if they were at the house at 1, 2, or 3 o'clock, forcing them to think it had to have been one of those choices. It causes people to recall things from the prompt instead of their memories. Also, interrogators use stereotype induction, which is when they tell the witness only negative characteristics of the alleged perpetrator. Part of stereotype induction is the incriminating condition where everything the witness says is labeled as bad. The detective would slightly shake his head or tell the witness to try again. This contrasts with another interrogating option of using a neutral interview technique, which includes both the bad and good aspects of the perpetrator.

Neither of these techniques is considered to be ethically sound for reasons similar to those provided by Bill Franke in the comments in respect to entrapment.
In addition to Jim's penetrating and pointed, you could also use the word probing to describe the questions asked during an interrogation.

A: I think pointed questions and loaded questions are two excellent candidates, put forth by Jim and coleopterist, respectively.
I'd like to add one more to the list: leading questions. From NOAD:

leading question (n.) a question that prompts or encourages the desired answer

Leading questions are sometimes considered to be an unfair interrogation technique. One website mentions:

Leading questions are those that nudge, push or shove the other person towards a particular answer and away from other answers. They are a very common form of bias.

Also, the difference between leading questions and loaded questions is discussed some on Wikipedia.

A: I rather like the word "ensnaring" for something like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't spin 3d cube I'm coding a cube but can not get it to rotate properly, could anybody help me out? I have tried everything. Link to my code is below:
Codepen Link

@keyframes spin {
  from {
   transform: rotateY(0deg);
 }
  to {
   transform: rotateY(360deg);
 }
}
 body .cube {
  overflow: visible;
  perspective: 800px;
  perspective-origin: 100px 100px;
  margin-top: 50px;
  margin-left: 200px;
  position: relative;
  animation: spin 10s linear infinite;
  transform-origin: 150px 150px;
  transform-style: preserve-3d;
  transform-box: fill-box;
}
 body .cube h1 {
  text-align: center;
  transform: translateY(350%);
}
 body .cube .frontside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: green;
  transform: translateZ(150px);
}
 body .cube .backside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: black;
  transform: translateZ(-150px);
}
 body .cube .leftside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background: purple;
  transform: translateX(-150px) rotateY(90deg);
}
 body .cube .rightside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: midnightblue;
  transform: translateX(150px) rotateY(90deg);
}
 body .cube .topside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: yellow;
  transform: translateY(-150px) rotateX(90deg);
}
 body .cube .bottomside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background: red;
  transform: translateY(150px) rotateX(90deg);
}

Hello1

Hello2

Hello3

Hello4

Hello5

Hello6

A: If this is not what you want, modify the question

@keyframes spin {
  from {
   transform: rotateY(0deg);
 }
  to {
   transform: rotateY(360deg);
 }
}
 body .cube {
    overflow: visible;
    perspective-origin: 100px 100px;
    margin-top: 50px;
    margin-left: 200px;
    position: relative;
    transform-origin: 150px 150px;
    transform-style: preserve-3d;
    transform-box: fill-box;
    height: 200px;
    width: 200px;
    -webkit-animation: spin 15s infinite linear;
}

 body .cube h1 {
  text-align: center;
  transform: translateY(350%);
}
 body .cube .frontside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: green;
  transform: translateZ(150px);
}
 body .cube .backside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: black;
  transform: translateZ(-150px);
}
 body .cube .leftside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background: purple;
  transform: translateX(-150px) rotateY(90deg);
}
 body .cube .rightside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: midnightblue;
  transform: translateX(150px) rotateY(90deg);
}
 body .cube .topside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background-color: yellow;
  transform: translateY(-150px) rotateX(90deg);
}
 body .cube .bottomside {
  width: 300px;
  height: 300px;
  position: absolute;
  margin: 0;
  opacity: 0.5;
  background: red;
  transform: translateY(150px) rotateX(90deg);
}

<!DOCTYPE html>

 <link rel="stylesheet" href="1.css">

Hello1

Hello2

Hello3

Hello4

Hello5

Hello6


text:
Q: Help in Creating a Legend for a Block Diagram in Tikz I have a block diagram finished, but I need help in creating a legend for it.
I'm trying to create a legend that looks like that picture below. I want to be able to 1st create this type of graphic and also be able to x & y shift the entire graphic in my block diagram.

I'm new to TeX, but I manged to learn a lot in the past few days. Yet, I looked for a way to implement this, but no luck.

A: There are likely many ways of doing something like that. Here's a quick hack. As this is for an existing diagram, you probably want to use styles for the different legend entries and corresponding arrows etc.

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix, fit}
\begin{document}
\begin{tikzpicture}
 \matrix [draw,
          matrix of nodes,
          column sep=4mm
          ]
          (m) at (1,1) {
  Legend 1 & Legend 2 \\
  \draw [blue, ->] (-.25,0) -- (0.25,0) node[minimum height=5pt]{}; &
  \draw [red, ->] (-.25,0) -- (0.25,0); \\
 };

\node [left=-\pgflinewidth] (leg) at (m.west) {Legend};

\node [draw, inner sep=-0.5\pgflinewidth,fit=(leg)(m.north west)(m.south west)] {};

\end{tikzpicture}
\end{document}


text:
Q: Display problems when booting into Linux I bought a new Samsung monitor and booted into Linux and the display was horrible (extremely bright and poor contrast). I tried to change settings but I was not satisfied with the ouput. I then booted back into windows and used Samsung's Magictune and the display was excellent. I booted back into LInux and the display is a mess again. I believe this could be with the X subsystem but I don't know the fundamentals to tweak X. Can someone provide the high-level guidelines to troubleshoot this issue.
I run openSuse with XFCE.
External monitor : Samsung 22''

A: There seems to be a newer DDC Control version you can try (guide).
If you have a nvidia graphics card you might need a workaround.


text:
Q: Xubuntu 13.10: disabling suspend on lid being closed I'm having trouble with configuring my home server. I have an old lenovo x200 laptop that runs Xubuntu 13.10.
My problem is that after closing the lid the laptop is begin suspended despite changing all lid-related options in power management to "nothing". How to disable all actions (except turning the screen off) on lid close?

A: I had the same problem, affecting the power button as well. This worked for me:
https://wiki.archlinux.org/index.php/xfce#xfce4-power-manager
/etc/systemd/logind.conf
HandlePowerKey=ignore
HandleSuspendKey=ignore
HandleHibernateKey=ignore
HandleLidSwitch=ignore


text:
Q: c# datarow comparing DBNull.Value for DateTime vs null for string I have the following code that seems to work:
DataRow row = <result of a query>;
string strVarName = (row["VarName"]??"").ToString();

I can also use something like this - and it also works:
string strVarName = row["VarName"]==null ? "" : row["VarName"].ToString();

I would like to use the same form to get a date.  Intellisense informs me that the nullable operator does not like working with dates, so I am trying something similar, I have to make
string strVarName = row["VarName"]==DBnull.Value ? "" : row["VarName"].ToShortDateString();

Get that?  For strings I compare to null, but for dates I compare to DBnull.  The date string will not work consistently with a comparison to null.  I'm okay with this ... and it may be that the string comparison would work if I tried to compare it to DBNull.Value .  I'm just curious why it seems I must use DBNull.Value when comparing to a DateTime field of a DataRow, whereas I may use null when comparing to a string field.

A: DateTime is a value type and can not be null, hence you can't compare it to null (just like you can't compare int to null).


text:
Q: How can i disable an input text box based on dropdown selection value using AngularJS? I have the following in JavaScript for AngularJS
$("#listOptionFruit").kendoDropDownList({
    autoBind: true,
    filter: 'contains',
    dataSource: $scope.listOptionFruitList,
    select: $scope.listOptionFruitSelect
});

$scope.listOptionFruitSelect = function (e)
{
   $scope.listOptionFruit = e.dataItem;
   if ($scope.listOptionFruit === 'Strawberry') {
       $scope.enableMe = true;
   }
   else
   {
       $scope.enableMe =  false;
   }
}

and the cshtml side is as follows:
Fruits
<input id="listOptionFruit" name="listOptionFruit"  required />

MyValue
<input type="text"  id="myValue" ng-disabled="enableMe"  />

So the value is correct for enableMe , but the text box doesn't seem to be disabled or the action doesn't seem to take effect.
So if the user selects Strawberry from the list then the text box is disabled , else it is enabled

A: Since the event happens outside the AngularJS framework, it needs to be bound with $apply:
$("#listOptionFruit").kendoDropDownList({
    autoBind: true,
    filter: 'contains',
    dataSource: $scope.listOptionFruitList,
    select: function (ev) {
        $scope.$apply(function() {
            $scope.listOptionFruitSelect(ev);
        });
    }
});

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

For more information, see

*

*AngularJS Developer Guide - Integration with the browser event loop


text:
Q: Crop the region inside the rectangular face detection box using the top-left corner and bottom-right corner of rectangle I want to crop faces which are boxed using cv2.rectangle.
I tried :
faces = face_cascade.detectMultiScale(gray_image, 1.25, 6)

but this code is detecting only 1 face for this image but when I used another code :
boxes = face_recognition.face_locations(rgb,model="hog")

it returned me 3 faces with values top,right,bottom,left but I dont know how to crop an image using these values(top,right,bottom,left). Any help will be appreciated.
I am using:
Python- 2.7
OpenCv- 3.1.0

A: In the question, boxes have the top, right, bottom, left values of the detected face, so to crop that area with the given top, right, bottom, left values I used PIL.Image.crop():
Then the code will be like this:
    from PIL import Image
    img = Image.open("path/to/file")
    crop_pic = img.crop( ( left, top, right, bottom ) )
    crop_pic.show()


text:
Q: Shebang conflict with doxygen Does doxygen doesn't work properly on python script with a shebang?
I tried one python script with shebang to my company's tool directory and ran doxygen.
It was not able to display namespace (functions) at all.
Please share if you guys faced similar experience.

A: enable EXTRACT_ALL to YES in the config file, doxygen will generate proper desired results.
But the question still remains, why doxygen failed to generate documentation file for python with EXTRACT_ALL = NO.
Anyone with better answer can help me here.

A: that sounds to me like a scripting problem and not like a conflict between Shebang and doxygen


text:
Q: In magento, update customer entity if customer has at least one order I have created a custom attribute is_buyer for user which will be set to 1 after order post event.
Now I want to set 'is_buyer' to 1 for old users which have at least one order.
I can do this using foreach loop but I want to do this with a single query.
Any body knows how to write query for mentioned task using magento.
I have already written one time script using loop.
    <?php
    set_time_limit(0);
    $customers = Mage::getModel('customer/customer')
            ->getCollection()
            ->addAttributeToSelect('entity_id')
            ->addAttributeToFilter(array(array('attribute' => 'is_buyer', 'null' => true)), '', 'left');

    $orders = Mage::getSingleton('sales/order')->getCollection()
        ->addAttributeToSelect('customer_id');

    foreach ($customers as $customer) {
        $orders->addFieldToFilter('customer_id', $customer->getId());
        if ($orders->count() > 0) {
            $customer->setData('is_buyer', 1);
        } else {
             $customer->setData('is_buyer', 0);
        }
        $customer->save();
}

A: You can use this slow approach to set the old users one time. And use an observer
to set the customer information ad hoc for new orders. So you only need to run the above script once. You can actually do some performance tuning...save and load in foreach is bad practice, but as you only need to run the script one it might not matter...
$customers = Mage::getModel('customer/customer)->getCollection();

foreach ($customers as $_customer){

        $_orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id',$_customer->getId());
        if ($_orders->count()){
            $customer->setIsBuyer();
            $customer->save();
        }
}

The event is:
<sales_order_place_after>
    <observers>
       <your_observer>
         <type>singleton</type>
         <class>YOUR_CLASS</class>
         <method>YOUR_METHOD</method>
       </your_observer>
     </observers>
 </sales_order_place_after>

The actual observer method (proof of concept but slow):
public static function YOUR_METHOD($observer) {
    $event = $observer->getEvent();
    $order = $event->getOrder();
    $order->getCustomerId();
    $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
    $customer->setIsBuyer();
    $customer->save();
}

A: So here is installer code which can do this in one query instead of loop.
/** @var Mage_Customer_Model_Entity_Setup $setup */
$setup = $this;
$setup->startSetup();

$setup->addAttribute('customer', 'is_buyer', array(
    'type' => 'int',
    'input' => 'boolean',
    'label' => 'Is Buyer',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'user_defined' => 0,
    'default' => '0',
    'visible_on_front' => 0,
    'position' => 200
));
$attributeId = $this->getAttributeId('customer', 'is_buyer');
$setup->run("
     INSERT INTO customer_entity_int (`entity_type_id`, `attribute_id`, `entity_id`, `value`)
    SELECT 1, {$attributeId}, c.entity_id, 1
    FROM customer_entity c
    WHERE c.entity_id IN (
       SELECT s.customer_id FROM sales_flat_order s
        WHERE s.customer_id IS NOT NULL
        GROUP BY s.customer_id
   )
   ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);
");


text:
Q: UIButton image not changing I have 4 UIButtons that I want to flash a lighter colour image for one second in a random sequence. So obviously I want to change the buttons images programatically. As you can see in the  XCode Project method: showSequence, it tries to set the image to the lighter one, then back again, but it doesn't show on the simulator.
Code Snippet:
- (void) showSequence:(NSMutableArray *)sequenceArray {

    for(int i = 0; i < [sequenceArray count]; i++){

        int sequenceNumber = [[sequenceArray objectAtIndex:i] intValue];

        switch (sequenceNumber) {
           case 1: {
              NSLog(@"green");
              [self.greenButton setBackgroundImage:[UIImage imageNamed:@"green_active.png"] forState:UIControlStateNormal];
              sleep(1);
              [self.greenButton setBackgroundImage:[UIImage imageNamed:@"green_inactive.png"] forState:UIControlStateNormal];
              break;
           }

           case 2: {
              NSLog(@"red");
              [self.redButton setBackgroundImage:[UIImage imageNamed:@"red_active.png"] forState:UIControlStateNormal];
              sleep(1);
              [self.redButton setBackgroundImage:[UIImage imageNamed:@"red_inactive.png"] forState:UIControlStateNormal];
              break;
           }

          case 3: {
             NSLog(@"yellow");
             [self.yellowButton setBackgroundImage:[UIImage imageNamed:@"yellow_active.png"] forState:UIControlStateNormal];
             sleep(1);
             [self.yellowButton setBackgroundImage:[UIImage imageNamed:@"yellow_inactive.png"] forState:UIControlStateNormal];
             break;
          }

          case 4: {
             NSLog(@"blue");
             [self.blueButton setBackgroundImage:[UIImage imageNamed:@"blue_active.png"] forState:UIControlStateNormal];
             sleep(1);
             [self.blueButton setBackgroundImage:[UIImage imageNamed:@"blue_inactive.png"] forState:UIControlStateNormal];
             break;
        }

        default:
            break;
       }
    }
}

Thanks in advance (btw, dont tap the start button during the sequence it will break (im still working on it))

A: you can do this by simply adding imageView to Button & assign NSArray to imageView.animationImages property. NSArray must contain the images as per your sequence
see below code
 imageView.animationImages = [NSArray arrayWithObjects:
                                        [UIImage imageNamed:@"myImageFrame1.gif"],
                                        [UIImage imageNamed:@"myImageFrame2.gif"],
                                        [UIImage imageNamed:@"myImageFrame3.gif"],
                                        [UIImage imageNamed:@"myImageFrame4.gif"], nil];

        imageView.animationDuration = 2.0;
        imageView.animationRepeatCount = 1; // for showing only once, otherwise set to 0
        [imageView startAnimating];
[self.button addsubView:imageView]

A: Check

*

*Images added and named correctly

*See if image is added on button,then background image is not visible.

*IBoutlets are connected

*Instead of setBackgroundImage: Try setImage:


text:
Q: Keycloak Federated Users - Trigger Password Reset Email in Custom SPI We implemented a keycloak SPI to perform lookups/updates on an external user database.
One of the features we wanted to implement is to trigger an email when users reach a certain number of login attempts. This is something we did in pre-keycloak version of our application and attempting to implement this feature.
The guidance is to use the execute-actions-email admin REST end point by supplying the "UPDATE_PASSWORD" required action along with other inputs. But I consistently get a 403 response.
I was looking around if in the custom SPI there is a way to use the Keycloak Java  API instead. I found an implementation of the executeActionsEmail method in UserResource. But this needs some additional initializations (mostly admin privileges I think). I'm stuck here as well.
I'm looking for any working example(s) that would help me understand how to implement this use case. Postman, Java API any thing would be highly appreciated.
Thank you,

A: This is the final solution:
    private boolean triggerExecuteActionsEmailAdminClient(RealmModel realm, UserModel user) {
    boolean executed = false;
    try {
        KeycloakContext context = keycloakSession.getContext();
        UriInfo backendUriInfo = context.getUri(UrlType.BACKEND);

        String backendBaseUri = backendUriInfo.getBaseUri().toString();
        log.info(String.format("backendBaseUri: %s", backendBaseUri));

        Keycloak keycloak = KeycloakBuilder.builder().serverUrl(backendBaseUri).realm("master")
                .clientId("admin-cli").grantType("password").username("admin").password("******")
                .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();
        String realmName = realm.getName();
        String userId = user.getId();

        keycloak.realm(realmName).users().get(userId).executeActionsEmail(Arrays.asList("UPDATE_PASSWORD"));
        executed = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return executed;
}

standalone.xml in jboss:domain:ee subsystem
        <global-modules>
            <module name="org.keycloak.keycloak-core"/>
            <module name="org.keycloak.keycloak-admin-client"/>
        </global-modules>

In lieu of the above, I added the dependencies in the jboss deployment descriptor of the installed custom SPI jar file
<jboss-deployment-structure>
<deployment>
    <dependencies>
        <module name="org.springframework.security" />
        <module name="com.oracledatabase.oracle" />
        <module name="org.keycloak.keycloak-core"/>
        <module name="org.keycloak.keycloak-server-spi"/>
        <module name="org.keycloak.keycloak-server-spi-private"/>
        <module name="org.keycloak.keycloak-services"/>
        <module name="org.keycloak.keycloak-saml-core-public"/>
        <module name="org.keycloak.keycloak-admin-client"/>
        <module name="org.jboss.logging"/>
    </dependencies>
</deployment>

Installing the keycloak-admin-client module, make sure keycloak-admin-client-14.0.0.jar  is available in /tmp
sudo $KEYCLOAK_HOME/bin/jboss-cli.sh --command="module add --name=org.keycloak.keycloak-admin-client --resources=/tmp/keycloak-admin-client-14.0.0.jar --dependencies=org.keycloak.keycloak-core,org.keycloak.keycloak-common,org.apache.httpcomponents,javax.ws.rs.api,org.jboss.resteasy.resteasy-jaxrs"


text:
Q: logical OR bitwise OR interchangeable? Say I have 2 comparison
if ((length >= 524288) | (length == 0))
{
      //do something...
}

vs
if ((length >= 524288) || (length == 0))
{
      //do something...
}

are these the same thing since when you bitwise OR 0001 0000 it turns into 1?
Also is there any particular reason to use bitwise OR in this situation?

A: In that case bitwise = logical since both tests return 0 or 1.
The only difference with single | is that both parts of the test will be executed whatever the result of the first test => use || here.


text:
Q: proxy http request with node I have a nodeJs front end on one domain and a rest back end server on another domain.
I would like to be able to perform ajax requests from the front to the back. So, i intend to use a reverse proxy for that, in order to bypass the same origin policy restriction.
My back end Rest server will be secured with Basic auth or OAuth. I would like to know, if i use node-http-proxy if it is possible to send an Authorization header in the http request before proxying it, and how.
Thanks a lot.

A: You have plenty of ways to accomplish that:

*

*You can use node-http-proxy middlewares to set the auth headers in the reverse proxy: http://blog.nodejitsu.com/http-proxy-middlewares

*You can require the http-proxy module, create a new instance and then use all the available events.

*Fork node-http-proxy and patch your version http-proxy.js to include custom basic_auth;

*Roll your own reverse proxy. With node.js it's quiet easy, check this post:
http://www.catonmat.net/http-proxy-in-nodejs/
Best Regards,


text:
Q: support 540x960 resolution in my android application I want to support 540x960 screen resolution in my android application.
How can I support this screen? Any suggestion will be appreciated.

A: You don't develop to specific resolutions on Android. You write layouts which automatically scale to different sizes and aspect ratios. Make use of classes such as RelativeLayout to define how elements should be placed relative to each other, and allow them to adapt to the available space. You can also use Fragments to design for different orientations and physical sizes (e.g. tablet vs phone).
Take a look at this document:
http://developer.android.com/guide/practices/screens_support.html

A: put inside AndroidManifest.xml
<supports-screens android:anyDensity="true"></supports-screens>

Or take a look bellow links.
Android Multiscreen Support in android : 540x960 issue
OR
How to support all the different resolutions of android products

A: res/layout-long-port-hdpi-960x540/layout.xml
height shold be come first


text:
Q: What is wrong with this vector integral?
If $\vec{F}=\frac{y\hat i-x\hat j}{x^2+y^2}$ then evaluate $\int_c \vec{F}\cdot\vec{r} $ where C is the circle $x^2+y^2=1$ traversed in counter clockwise direction.

My trial: using Green's theorem over XY-plane
$$\int_c\vec{F}\cdot d\vec{r}=\int_c\left(\frac{y\hat i-x\hat j}{x^2+y^2}\right)\cdot d\vec{r}$$
$$=\int_c\left(\frac{y\hat i-x\hat j}{x^2+y^2}\right)\cdot (\hat idx+\hat jdy)$$
$$=\int_c\left(\frac{y}{x^2+y^2}\right)dx-\left(\frac{x}{x^2+y^2}\right)dy$$
$$=\int\int_R\left(\frac{\partial}{\partial x}\left(\frac{-x}{x^2+y^2}\right)-\frac{\partial}{\partial y}\left(\frac{y}{x^2+y^2}\right)\right)dxdy$$
$$=\int\int_R\left(\left(\frac{x^2-y^2}{(x^2+y^2)^2}\right)-\left(\frac{x^2-y^2}{(x^2+y^2)^2}\right)\right)dxdy$$
$$=0$$
my book suggests that the answer is $-2\pi$ but i don't know how. Am I wrong if yes then please explain or help solve this problem. thanks.


text:
Q: Import functions/subroutine into subclass I'm using Moops and I'd like something like this to work:
use Moops;

class A {
  fun f {
    print "yay,f!\n";
  }
}

class B extends A {
  fun g {
    f();
  }
}
B->g(); # should print 'yay, f!'

Instead this yields:
Undefined subroutine &B::f called at static-functions-lexical-scope.pl line 11.

I can "fix" this by inheriting from Exporter in A and a use statement in B like so:
class A extends Exporter {
  our @EXPORT = qw(f);
  fun f {
    print "yay,f!\n";
  }
}

class B extends A {
  use A;
  fun g {
    f();
  }
}

This seem a bit unwieldy, but it gets worse if A is defined in another file. Then I'd have to add a second use A (require won't do) outside of B like so:
use  A;
class B extends A {
  use A;
  fun g {
    f();
  }
}

Is there a way to make lexical inclusion (of exported) functions work more elegantly?

A: First, thanks for using Moops! :-)
Second, it's probably a bad idea to name classes "B" in tests and examples. There's a module called B that comes with Perl, and Moops actually uses it!
Coming to your actual question, generally speaking with classes, you should be thinking method rather than fun. Method calls respect inheritance; function calls don't.
use Moops;

class AAA {
  method f {
    say "yay,f!";
  }
}

class BBB extends AAA {
  method g {
    $self->f;
  }
}

BBB->g;

Outputs:
yay,f!

If you want a library of convenience functions to be available in both AAA and BBB then, split those convenience functions into a separate package:
use Moops;

namespace MyUtils {
  use Exporter::Shiny qw( f );
  fun f {
    say "yay,f!";
  }
}

class AAA {
  use MyUtils -all;
  method m1 {
    f();
  }
}

class BBB extends AAA {
  use MyUtils -all;
  method m2 {
    f();
  }
}

BBB->m1;
BBB->m2;

Outputs:
yay,f!
yay,f!

You can even go a bit further and extend Moops from within. The following example defines a :utils trait that can be added to classes:
use Moops;

namespace MyUtils {
  use Exporter::Shiny qw( f );
  fun f {
    say "yay,f!";
  }
}

role Moops::TraitFor::Keyword::utils {
   around generate_package_setup {
     return (
       $self->$next(@_),
       'use MyUtils -all;',
     );
   }
}

class AAA :utils {
  method m1 {
    f();
  }
}

class BBB extends AAA :utils {
  method m2 {
    f();
  }
}

BBB->m1;
BBB->m2;

Same output as previous example.


text:
Q: HTTP Client capable of logging in and maintaining a session in production I am trying to build a bot that uses credentials to log in and activate some javascript elements on the page.
The site that I am botting does not have an API that I can use and the site itself is very JS heavy.
Is it possible using something like, Tesla to log in as a user and interact with a browser, much like Watir and Capybara do, but in a production environment?
I am new to Elixir, but I imagine I would use a long running GenServer that would login on init. Most of the users use 2FA, which can be authorized when the user logs in, but if the bot wants to run days from the time the user logged in, it would have to store the auth session/token.
I have built the bot successfully using Watir, the testing framework. It open a browser and physically logs in. Then it proceeds with the bot successfully. But if I switch to a headless driver the JS doesn't execute properly.
Is it possible to put something like this into production?

A: You can use Hound or Wallaby to do this. They are pretty similar. I think Wallaby is a little closer to Capybara in syntax. It's a little dated, but here's a discussion on the difference between Wallaby and Hound.
I have used Hound for this before, and it worked well. I did have to use Chromium though instead of PhantomJS, because, like you, the pages I was visiting were js heavy, and some things just didn't work in PhantomJS. I used the non-headless (headed?) Chromium to develop so I could see what was going on, then switched to headless without issue once I got everything setup.
In regards to running it in production, I only ran the bot locally, but I see no reason why you couldn't get it working locally then deploy to an EC2 instance with the same setup and run it.


text:
Q: Numerical solution of a system of two exponential equations I need to solve this two equations for x and y:
(sum ((i^2)e^(-x i - y i^2)), i = 1 to 6)/sum (e^(-x i - y i^2)), i = 1 to 6) = 12

(sum ((i)e^(-x i - y i^2)), i = 1 to 6)/sum (e^(-x i - y i^2)), i = 1 to 6) = 3

I've tried to use NSolve and find real solutions for x and y
NSolve[
  {Sum[k E^(k^2*(-y) - k x), {k, 1, 6}]/Sum[E^(k^2*(-y) - k x), {k, 1, 6}] == 3,
   Sum[k^2*E^(k^2*(-y) - k x), {k, 1, 6}]/Sum[E^(k^2*(-y) - k*x), {k, 1, 6}] == 12}, {x, y}, Reals]

but I got the message:

NSolve: Requested precision R is not a machine-sized real number between MinPrecision and MaxPrecision"

How do I proceed?

A: A few problems with your code:

*

*Curly braces {} can't be used as parentheses ().

*You need a space or * between k and x to multiply them, otherwise Mathematica thinks it's a new variable kx.

*The syntax of NSolve has a list of equations as the first argument, and a list of unknowns -- {x,y} here -- as the second argument.

The following seems to work:
NSolve[{
 Sum[k E^(k^2*(-y) - k x), {k, 1, 6}]/Sum[E^(k^2*(-y) - k x), {k, 1, 6}] == 3,
 Sum[k^2*E^(k^2*(-y) - k x), {k, 1, 6}]/Sum[E^(k^2*(-y) - k*x), {k, 1, 6}] == 12},
 {x, y}, Reals]
(* {{x -> 0.440365, y -> -0.0399564}} *)


text:
Q: How can I keep the MediaRecorder keeps recording after an orientation change Can you please tell me how can I keep the MediaRecorder keeps recording after an orientation change? I try looking into source code of  packages/apps/SoundRecorder/src/com/android/soundrecorder/Recorder.java, I don't see it handles that cases.
Thank you.

A: This might be because by default the system destroys and recreates the Activity when the orientation changes. You can tell the system that your app handles changes like these by modifying the activity's tag in the manifast like this:
<activity android:name=".UIActivity"
                  android:configChanges="orientation|keyboardHidden"
                  android:label="@string/app_name"> ...
</activity>

This way you can react to these changes overriding this method:
 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //---code to redraw your activity here---
        //...
    }

Here, you can redraw your views to support landscape mode, or do simply nothing.


text:
Q: How Does sizeof(Array) work How does c find at run time the size of array? where is the information about array size or bounds of array stored ?

A: sizeof gives the size of the variable, not the size of the object that you're pointing to (if there is one.) sizeof(arrayVar) will return the array size in bytes if and only if arrayVar is declared in scope as an array and not a pointer.
For example:
char myArray[10];
char* myPtr = myArray;

printf("%d\n", sizeof(myArray)) // prints 10
printf("%d\n", sizeof(myPtr)); // prints 4 (on a 32-bit machine)

A: sizeof(array) is implemented entirely by the C compiler. By the time the program gets linked, what looks like a sizeof() call to you has been converted into a constant.
Example: when you compile this C code:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv) {
    int a[33];
    printf("%d\n", sizeof(a));
}

you get
    .file   "sz.c"
    .section        .rodata
.LC0:
    .string "%d\n"
    .text
.globl main
    .type   main, @function
main:
    leal    4(%esp), %ecx
    andl    $-16, %esp
    pushl   -4(%ecx)
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %ecx
    subl    $164, %esp
    movl    $132, 4(%esp)
    movl    $.LC0, (%esp)
    call    printf
    addl    $164, %esp
    popl    %ecx
    popl    %ebp
    leal    -4(%ecx), %esp
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 4.1.2 (Gentoo 4.1.2 p1.1)"
    .section        .note.GNU-stack,"",@progbits

The $132 in the middle is the size of the array, 132 = 4 * 33. Notice that there's no call sizeof instruction - unlike printf, which is a real function.

A: sizeof(Array) is looked up at compile time, not at run time.  The information is not stored.
Are you perhaps interested in implementing bounds checking?  If so, there are a number of different ways to go about that.

A: sizeof is pure compile time in C++ and C prior to C99. Starting with C99 there are variable length arrays:
// returns n + 3
int f(int n) {
    char v[n + 3];

    // not purely a compile time construct anymore
    return sizeof v;
}

That will evaluate the sizeof operand, because n is not yet known at compile time. That only applies to variable length arrays: Other operands or types still make sizeof compute at compile time. In particular, arrays with dimensions known at compile time are still handled like in C++ and C89. As a consequence, the value returned by sizeof is not a compile time constant (constant expression) anymore. You can't use it where such a value is required - for example when initializing static variables, unless a compiler specific extension allows it (the C Standard allows an implementation to have extensions to what it treats as constant).

A: sizeof() will only work for a fixed size array (which can be static, stack based or in a struct).
If you apply it to an array created with malloc (or new in C++) you will always get the size of a pointer.
And yes, this is based on compile time information.


text:
Q: Python pandas: Mean on dataframe with uint16 gives wrong result Using the mean method on a dataframe with a uint16 column gives the wrong answer. When I add a  duplicate column with the int16 dtype then both columns give the correct mean. What's going on? I added an issue at github. https://github.com/pydata/pandas/issues/7976
 Python 2.7.7 |Anaconda 2.0.1 (x86_64)| (default, Jun  2 2014, 12:48:16)
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: import random

In [4]:

In [4]: np.__version__
Out[4]: '1.8.1'

In [5]: pd.__version__
Out[5]: '0.14.0'

In [6]:

In [6]: y = np.array([random.randint(1900,2000) for x in range(0,2000)])

In [7]: y.mean()
Out[7]: 1950.0115000000001

In [8]: y.astype(np.uint16).mean()
Out[8]: 1950.0115000000001

In [9]:

In [9]: d1 = pd.DataFrame()

In [10]: d1['y'] = y.astype(np.uint16)

In [11]: d1.mean()
Out[11]:
y    16.6995
dtype: float64

In [12]:

In [12]: d1['x'] = y.astype(np.int16)

In [13]: d1.mean()
Out[13]:
y    1950.0115
x    1950.0115
dtype: float64


text:
Q: AWS API Gateway - What is the Recommended Design Patter to Split DEV / PROD Environments? Option 1 - Create Stage Variables and link it to the Lambda Functions by adding Lambda ${stageVariables.changePassword}. Create different stages depending on the environment.
But the problem with this approach is that If we have different Authorizers for different environments then we need to have different deployments for different stages. That adds an operational overhead.
Option 2 -  Create Different APIs and split the environments completely so that different authorizers can be created and they stay isolated.
Which would you use and why?


text:
Q: Why might Node perform different regex matching inside a script vs the repl? I'm seeing some very strange behaviour with a little script I'm writing (and running with Node v6). If I place the following line in a script, say index.js:
console.log((/autonom.*/ig).test('autonomy'))

and run it with node index.js, I'm seeing false. Unexpected!
Stranger still is that if I open an interactive shell with node, and run:
> (/autonom.*/ig).test('autonomy')
true

I get true, as expected. Is there any reason why the code in the script would have a different effect to that in the repl?
Edit the regex had a little bit of spice for no real reason. I see the same behaviour even with the trivial:
console.log((/^autonomy$/).test('autonomy'))

Edit the plot thickens hugely:
console.log((/autonom\S*/i).test('autonomy'))
console.log((/autonom\S*/i).test('autonomy'))

node index.js with this file prints:
true
false

A: I've finally got to the root of the problem, and thought I'd share an answer to the question!
Why might Node be behaving strangely in this situation?
The problem lies in where i took my original strings from - which happened to be to copy and paste from a PDF article. Let's take the string 'autonomy' for an example.
In Atom, my editor, this looked exactly like 'autonomy'. As it did when I pasted it to SO in the original question.
However, if I take the one in-editor and output it as a hex buffer, I see:
6175746f6e6f6d01

For comparison, the string 'autonomy', if typed out manually, is:
6175746f6e6f6d

Herein lies the problem. The reason it worked for all of you lot, and the reason it worked for me in the REPL, is that most of the places I pasted it (SO, bash, ...) didn't understand / threw out that final 01, leaving you seeing the "proper" string 'autonomy' as it looks.
FYI, the ASCII character 01 is SOH: Start of Header. SHRUG!


text:
Q: Moving data from a database to Azure blob storage I'm able to use dask.dataframe.read_sql_table to read the data e.g. df = dd.read_sql_table(table='TABLE', uri=uri, index_col='field', npartitions=N)
What would be the next (best) steps to saving it as a parquet file in Azure blob storage?
From my small research there are a couple of options:

*

*Save locally and use https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-blobs?toc=/azure/storage/blobs/toc.json (not great for big data)

*I believe adlfs is to read from blob

*use dask.dataframe.to_parquet and work out how to point to the blob container

*intake project (not sure where to start)

A: $ pip install adlfs
dd.to_parquet(
    df=df,
    path='absf://{BLOB}/{FILE_NAME}.parquet',
    storage_options={'account_name': 'ACCOUNT_NAME',
                     'account_key': 'ACCOUNT_KEY'},
    )


text:
Q: jQuery: Declare a Variable Using Dynamic Content I'm trying to figure out how to create a variable based on a random (dynamic) number, and append one of two variables (GT5K or LT5K) if it's greater than or less than 5000.
The JS Fiddle below contains my entire script--most of which is working, with the following exception:
var welcomePointsValue = jQuery('.welcomePointsValue').html();
var GT5K = '
Redeem your points and save money today.
';
var LT5K = '
Add bonus points to your room below and start earning more rewards.
';

if (welcomePointsValue < 5000) {
    //append var to ID if less than 5000 points
    jQuery('#posMsgWrapperCont').append(LT5K);
} else {
    //append var to ID if greater than 5000 points
    jQuery('#posMsgWrapperCont').append(GT5K);
}

I'm relatively green when it comes to using variables, so feel free to point out any issues I may be overlooking.
View my JS Fiddle here...see line 37
Thanks in advance for your help!

A: You need to get the number properly.
var welcomePointsValue =
Number(jQuery('.welcomePointsValue > span').text().replace(/\D/g,""));

You can simplify your if to ternary if you want.
jQuery('#posMsgWrapperCont').append(welcomePointsValue > 5000 ? GTFK : LT5k);

P.S It will be more than good if you store it in data-value attribute and then use it like .data('value') to get it.


text:
Q: Rails: Calling to_json method in HTML How would I call .to_json on data-filters below?
data-filters="<%= t.AB_filterRules %>"

The reason I ask is because I have the data-filters attribute in my HTML ERB file, and it displays the database attributes. Example below:
data-filters="[[{" noun":"app","comparison":"was","value":"opened in the last two days"},{"noun":"deliverable","comparison":"is","value":"push notification"}]]"

However, when I view the value of the data-filters attribute in console, it only shows:
"[[{"

I'd really like it all to be displayed, so calling .to_json would be very helpful here!
Thanks

A: The key thing to bear in mind thinking about this is: If this is destined to be read by a javascript function, and converted back into a javascript object, then it can be rendered out onto the page in any way whatsoever, as long as that can be translated back again in the javascript function.
We'll be doing the "object to string" translation in ruby, and the "string to object" translation in javascript, so we'll need to pick some translation system which works in a standard way in both languages.  I'm going with URI.escape in ruby, and decodeURIComponent for the reverse in javascript.  URI.escape is a standard system (meaning the rules should be the same across different languages) and is web-safe, meaning the result shouldn't have any characters that will break a url or html tag.
in the erb template:
<% @rules = [[{" noun" => "app","comparison" => "was","value" => "opened in the last two days"},{"noun" => "deliverable","comparison" => "is","value" =>"push notification"}]] %>

<div id="data-filters-test" data-filters="<%= URI.escape(@rules.to_json) %>">

Obviously you can replace @rules with your own method that reads the data from the database or whatever: the above is just my version so i could test it.
resultant html:

Your final step will be to translate this back from the URI.escape'd string into an object, in your javascript.  I would do this like so: (the following lists the results of each step, for explanation)
//get the string
var escapedString = $("#data-filters-test").data("filters");
// => "[[%7B%22value%22:%22opened%20in%20the%20last%20two%20days%22,%22%20noun%22:%22app%22,%22comparison%22:%22was%22%7D,%7B%22noun%22:%22deliverable%22,%22value%22:%22push%20notification%22,%22comparison%22:%22is%22%7D]]"

//reverse the URI.escape, to get it back to json
var json = decodeURIComponent(escapedString);
// => "[[{"value":"opened in the last two days"," noun":"app","comparison":"was"},{"noun":"deliverable","value":"push notification","comparison":"is"}]]"

//convert the json string to a javascript object
var filter = JSON.parse(json);
// => <Object>

Obviously you could wrap this all up in a single step if you wanted, or, even better, a function, eg
function uriEscapedToObject(escapedString){
  return JSON.parse(decodeURIComponent(escapedString));
}

Now in your js to handle this element you can write
var filters = uriEscapedToObject($("#data-filters-test").data("filters"));


text:
Q: What is the difference between @jit and @vectorize in numba? When should I use @vectorize?
I tried @jit and show that part of the code below,
from numba import jit

@jit
def kma(g,temp):
    k=np.exp(-(g+np.abs(g))/(2*temp))
    return k

but my code didn't accelerate the algorithm. Why?

A: @vectorize is used to write an expression that can be applied one element at a time (scalars) to an array. The @jit decorator is more general and can work on any type of calculation.
There is a detailed discussion of the other benefits in the docs:
http://numba.pydata.org/numba-doc/latest/user/vectorize.html

You might ask yourself, "why would I go through this instead of compiling a simple iteration loop using the @jit decorator?". The answer is that NumPy ufuncs automatically get other features such as reduction, accumulation or broadcasting.

The reason why your code isn't being sped up (I see almost identical performance between jitted and non-jitted code), is that the operation you're performing is already being entirely handled by the low-level compiled code sitting behind the numpy vectorized operations.
You might get some savings if you unroll the implicit loops to avoid the creation of intermediate arrays, but typically numba really excels for operations that aren't easily vectorized in numpy.


text:
Q: Прочитать весь текст из socket asyncio Server Этот код ждет только 1024 байт, потому что больше - не работает:
import asyncio

async def handle_client(reader, writer):
    data = await reader.read(1024)
    data2 = await reader.read(1024)
    writer.write("hello from server".encode())
    await writer.drain()
    writer.close()

loop = asyncio.get_event_loop()
loop.create_task(asyncio.start_server(handle_client, 'localhost', 4782))
loop.run_forever()

Client Генерация 1024байтов и отправка:
import socket
sock = socket.socket()
sock.connect(('localhost', 4782))
sock.sendall(("".join([str(i)[-1:] for i in range(1024)])).encode())
data = sock.recv(1024)
sock.close()

Проблема: сервер замораживает клиент из-за того, что ждет еще 1024 байтов, в библиотеке socket возвращает просто b'', тут же, я не разобрался как это сделать, прошу о помощи.

A: b'' не всегда обозначает конец передачи особенно если передача не законченна. Для потоков надо обозначить конец передачи обрывом соединения или изобретайте протокол на TLV.
Поведение с которое Вы хотите в асинкио можно получить с помошью протоколов:
import asyncio

class EchoServerProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        message = data.decode() # -- пакет прилетевший с sendall, уже эвейтнутый
        self.transport.write("hello from server".encode())
        self.transport.close()

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    server = await loop.create_server(
        lambda: EchoServerProtocol(),
        '127.0.0.1', 4782)

    async with server:
        await server.serve_forever()

asyncio.run(main())

Но при больших объемах лучше использовать стримы.


text:
Q: Input function for multiple values in python a,b=int(input("Enter two numbers").split())

print(a+b)

I have written this code to add two numbers while taking input using input() function.
It is giving an error.
I know we can convert to int using map function but how about this method?
What is the error here?
[The pic depicts th error which it gives]

A: split returns a list of strings, so you need to call int on each of the items in that list. It doesn't make sense to call int on a list. For example
>>> a, b = [int(x) for x in "1 2".split()]
>>> a
1
>>> b
2
>>>

A: You could try this (Using map function).
a,b=map(int, input("Enter two numbers").split())

print(a+b)

A: x, y = input("Enter two values: ").split()

print(int(x)+int(y))


text:
Q: How to restrict users in my AWS account from accessing public AMIs I want the users want to use the private [shared from another account] or owned AMIs only. I've tried searching in the AWS documentation and stckoverflow. Does any one know if this can be done?
Thanks

A: You cannot restrict permissions for specific users within the specified AWS account. All users in the AWS account that you've specified can use the AMI or snapshot. http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html

A: I believe you can restrict to certain AMIs by following this document:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html#ex5
The 2nd example includes a policy that specifies a list of AMIs that can be launched, while the 3rd example show how to restrict to just Amazon AMIs.


text:
Q: Can I redirect alerts from a single DataDog monitor to different Slack channels? So I've got a DataDog monitor and its query is roughly similar to:
trace-analytics("service:foo-service @http.status_code:403").rollup("count").last("10m") > 1000

and under "Notify your team" section of DD monitor I setup my team's channel on Slack and we receive quite a lot of alerts as a result.
That said, we'd be interested to redirect those errors to relevant teams (e.g., if the route /abc throws a 403 we'd like to post it to another #abc-team Slack channel, /cde to #cde-team etc). How can we do it? I was thinking I could write a Slack bot or something since I didn't find such an option on DataDog.

A: You would need some kinda of tag that is an exact string match on some part of the slack channel (so the tag would need to be route:abc not route:/abc)
then you would be able to write something like @slack-{{route.name}}-alerts. which automatically dereferences the tag and sends it out to the appropriate group.

https://www.datadoghq.com/blog/tagging-best-practices/#create-automatic-dynamic-alerts-for-your-team
If for some reason you can't get a tag that matches any part of your slack handle onto the data, you could make a giant if else conditional
{{#is_match "route.name" "/abc"}}
  @slack-abc
{{/is_match}}
{{#is_match "route.name" "/whoever"}}
  @slack-whoever
{{/is_match}}
{{#is_match "route.name" "/turtle"}}
  @slack-turtle
{{/is_match}}
{{^is_match "route.name" "/abc" "/whoever" "/turtle"}}
  please make sure that this endpoint is configured to forward to the proper team's channel inside this monitor
  @slack-backup-alert-channel
{{/is_match}}

https://docs.datadoghq.com/monitors/notifications/?tab=monitors#conditional-variables
the first option is much cleaner and scales way better obviously. but i've seen people use the second one.

A:  I am not much aware about the DataDog functionality, but I can help you with Slack Bot.
The bot you can develop will have following flow:

*

*All the alerts will be sent to common channel #all-alerts

*The bot will also be invited to this channel

*Subscribe the bot to message event

*Process the received event(message), determine which team it belongs to.

*Post the processed message/alert to relevant team.


text:
Q: android baseAdapter weird error as mentioned in some other threads i'm a having trouble to setText inside a Textview from my BaseAdapter.
whenever i'm trying to set hebrew string inside it, i get a stackoverflow error.. when setting english string - works perfectly
i'm trying to find out where exectly the error is, so i've break apart each piece of my code and this is what i've found:
when my text view is nested inside a new view - the stackoverflow appears..
in this XML there is stackoverflow (only in hebrew string):
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableRow>

        <include
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_gravity="center_vertical"
            android:layout_margin="4dp"
            layout="@layout/list_profile_picture_green"
            android:padding="4dp" />

        <TableLayout android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        </TableLayout>

    </TableRow>

</TableLayout>

this XML shows hebrew perfectly:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableRow>

        <include
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_gravity="center_vertical"
            android:layout_margin="4dp"
            layout="@layout/list_profile_picture_green"
            android:padding="4dp" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </TableRow>

</TableLayout>

this is my stacktrace:
06-24 00:48:02.565: E/AndroidRuntime(20483): FATAL EXCEPTION: main
06-24 00:48:02.565: E/AndroidRuntime(20483): java.lang.StackOverflowError
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.lang.StringBuilder.append(StringBuilder.java:312)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.lang.StringBuilder.append(StringBuilder.java:44)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.util.Formatter.outputCharSequence(Formatter.java:1114)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.util.Formatter.doFormat(Formatter.java:1086)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.util.Formatter.format(Formatter.java:1062)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.util.Formatter.format(Formatter.java:1031)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.lang.String.format(String.java:2183)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at java.lang.String.format(String.java:2157)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.text.Styled.drawDirectionalRun(Styled.java:266)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.text.Styled.drawText(Styled.java:362)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.text.Layout.drawText(Layout.java:1546)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.text.Layout.draw(Layout.java:380)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.TextView.onDraw(TextView.java:4417)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6933)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.AbsListView.dispatchDraw(AbsListView.java:1648)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.ListView.dispatchDraw(ListView.java:3217)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.AbsListView.draw(AbsListView.java:3030)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.FrameLayout.draw(FrameLayout.java:357)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.FrameLayout.draw(FrameLayout.java:357)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.FrameLayout.draw(FrameLayout.java:357)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1644)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.FrameLayout.draw(FrameLayout.java:357)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.drawChild(ViewGroup.java:1646)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.view.View.draw(View.java:6936)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at android.widget.FrameLayout.draw(FrameLayout.java:357)
06-24 00:48:02.565: E/AndroidRuntime(20483):    at com.android.internal.policy.impl.P

any idea why ???

A: There is no error with the text itself. When using this exact code (sans the include), I have no errors with English, nor with Hebrew, with either XML layout.
The issue here is that you have too many nested layouts. I suspect this TableLayout is included in something else, which is from something else, etc...
You have to reduce the amount of nested layouts; I suspect the reason this is presenting itself as a StackOverflow error is because Hebrew reads right-to-left and also takes up more space to represent, so it's what's pushing the memory over the limit.
I believe you have the same issue listed here and here.
Reduce the amount of nested layout items you have and this should go away. (As general practice, for example, a TableLayout within another TableLayout is bad practice.) This may help.


text:
Q: Generating a constant-amplitude triangle wave from a square wave I have designed a circuit that can generate sawtooth and arbitrary duty cycle pulse waves controlled by some variable DC current source \$I_0\$, giving a frequency proportional to this current.
The sawtooth is generated by charging a capacitor with \$I_0\$ and discharging it rapidly when it reaches some voltage \$V_0\$, controlled through a 555 timer.
I can then use that to generate a square wave by putting the sawtooth output through a comparator. The duty cycle can be adjusted by adjusting the reference voltage of the comparator. (I know this is not the most efficient way to generate pulse waves, but it's how I designed it to have frequency proportional to \$I_0\$ in the same way as the sawtooth.)
I now want to use this same circuit to generate a triangle wave with the same frequency as the other two oscillators. The obvious way to do that would be using an integrator on the square output, but that will give me an ever decreasing amplitude with frequency, and that's not something I want. I need amplitude independent of frequency.
If the text is too confusing, I can draw a schematic once I get home.

A: One solution is to turn the circuit around.  Rather than generate a square wave and then try to convert it to a triangle wave, generate the triangle wave with an integrator and comparator.  As you vary the integrator time constant, the square and triangle outputs track and both amplitudes are constant.  The R and C for the integrator set the frequency, and adjusting the trip point for the comparator changes the symmetry of the square wave.  The comparator hysteresis sets the amplitude of the triangle wave.
A quick search for 'triangle generator circuit' found this:

(Image source: Bill Bowden)
For a given frequency, the slope of the ramp in a saw wave is 1/2 that of the slopes in a triangle wave.  If you want all three waveforms available simultaneously and have them track with a single adjustment, there is no simple circuit.


text:
Q: IntelliJ external library dependence within packages Within an IntelliJ project, I have set up a dependence on an external library (project structure -> Modules -> Dependencies -> Add -> Library). This library appears in the "External Libraries" tab on the left.
For classes which are placed directly in the src directory this works fine.
However, for packages I create within the project, IntelliJ doesn't recognize functions from the external library (I get a red line and a "cannot resolve symbol").
How should I set up the external library so that this issue is resolved?

A: *

*Open the Project Structure dialog (e.g. Ctrl+Shift+Alt+S).

*In the left-hand pane of the dialog, select Modules.

*In the pane to the right, select the module of interest.

*In the right-hand part of the dialog, on the Module page, select the Dependencies tab.

*On the Dependencies tab, click add and select Jars or directories.

*In the dialog that opens, select the necessary files and folders. These may be individual .class, .java, .jar and .zip files, and the directories containing such files. Click OK.

*If necessary, select the Export option and change the dependency scope.
8.Click OK in the Project Structure dialog.
Source


text:
Q: Showing $\sigma$-additivity and a measurable function Let $F: \mathbb R \rightarrow \mathbb R$  increasing and left-continous.
$\mu([a,b)):= F(b)-F(a) \quad$and  $\quad \mathbb I := \{[a,b) | \quad a,b \in \mathbb R , a \leq b \}$.
1) Show that $\mu(\overset{.}{\cup}A_i) = \sum_{i} \mu(A_i)$ for disjointed $A_i \in \mathbb I$
I am not sure if $\mu([a_1,b_1) \overset{.}{\cup} [a_2,b_2)) = F(b_1)-F(a_1) + F(b_2)-F(a_2)$ because $\mu$ isnt defined for unions which is confusing me.
Then I tried to let $A_k = [a_k,b_k) $ and then search for the $\min\{a_k,b_k\}= b_l$ and $\max\{a_k,b_k\}=a_j$ to get the biggest interval possible of the unions over $A_i$, so that $$\mu(\overset{.}{\cup}A_i) = F(a_j)-F(b_l) = ...$$ but that doesnt seem to be the right way.
2) Is it always possible to extend $\mu$ to a measure on the borel set of $\mathbb R$ ?
Totally clueless here
Any help is appreciated. Thanks


text:
Q: Let $\langle G,*\rangle$ be an abelian group with identity element $e$. Prove that $H = \{x ∈ G | x ∗ x = e\}$ is a subgroup of $G$ Let $\langle G,*\rangle$ be an abelian group with identity element $e$.
Prove that $H = \{x \in G | x ∗ x = e\}$ is a subgroup of $G$.

A: Hint: As G is abelian, all subgroups' elements commute with each other. Can you see how to apply this to the problem at hand?

A: Note that in an abelian group $x\mapsto x^2$ is a homomorphism since $(ab)*(ab) = (a*a)*(b*b)$. But then you can just recognize your set as the kernel of this homomorphism, hence a subgroup.

If you've never seen that kernels are subgroups, it's easy, if $x,y\mapsto e$ under a map $\phi$, then note that

$$\phi(x*y^{-1}) = \phi(x)*\phi(y)^{-1} = e*e = e$$

And since clearly $e\in\ker \phi$ is non-empty, this proves it is a subgroup.


text: Q: Auto transition in Jira issue in integration with Swarm I have integration of Jira and Swarm where the code is sent for review and I would like to find any opportunity for auto transition of status in JIRA issue from Open/In Progress to In Review as soon as code review in Swarm starts. And when this code review is done and the task in Swarm is closed I would like to have in JIRA linked issue auto transition to status Resolved. It seems to me that the solution should be easy but I cannot find any ready plugin or solution for this problem. Please could anybody help me?


text:
Q: Changing CSS element on selection I know there is a simple way to do this but I can't seem to find it.  I have a drop down box, which has a list.  Once you hover your mouse over any one of the items on the list, it's encircled by a border.  This is great.
What I want is for when a user selects an item from this list.  It will automatically change the background colour to #ddd.
If the user selects another item from the list, it will deselect the other item items background.
So, I have a class called 'hi'.
My CSS is like so:
#changer a{
    padding:3px;
    border: solid 1px #fff;
}
#changer a.hi{
    background:#ddd;
}
#changer a:hover{
    border: solid 1px #ddd;
    text-decoration:none;
}

I've added this script but it just selects the item from the list but it doesn't deselect the other one.  It just toggles the background colours.
<script type="text/javascript">
$(function() {
  $("a").click(function() {
    $(this).toggleClass("hi");
  });
});
</script>

Any help would be mostly appreciated.
Cheers,
Jonny

A: Try this:
$("a").click(function() {

    // remove existing "hi"s on other links
    $("a.hi").not(this).removeClass("hi");

    // toggle "hi" on this
    $(this).toggleClass("hi");
});

If you want the links to behave like mutually-exclusive checkboxes (can only select one, but can also deselect current) then use the above code, but if you want them to behave like a set of radio buttons (can only select one, but can't deselect current), use the following instead.
$("a").click(function() {

    // remove existing "hi"s on other links
    $("a.hi").not(this).removeClass("hi");

    // add "hi" to this
    if (!$(this).hasClass('hi'))
        $(this).addClass("hi");
});

A: you can use :active on this write like this:
#changer a:active{
    background:#ddd;
}


text:
Q: How to create Excel document with proper cell alignment using Ireport? I can able to create Excel document using Jasper Report but the problem is that fields are not properly aligned in the cells of excel sheet and all the data are populated in the plain surface without any cells.i.e) I cannot see any cells in the data populated area.Can u please give me suggestion to make proper Excel document with cell alignment.

A: I had this same struggle and came up with the following. At the time, I was using iReport (3.0.0) and was able to generate a good xls file.  It may be easier in newer versions of iReport and/or JasperReports. Here's what I did:

*

*I created a new report using the new report wizard and chose a tabular template.  This creates a report with all of the fields in a line with no gaps between them. It is very key that fields are vertically aligned, that all the same height, and that there are no gaps between fields.

*I removed all of the extra objects created (title, extra lines) except for the fields and the headers.  I then collapsed all of the bands except the column header and detail bands.

*On the report properties, I checked "Ignore pagination"

*I changed the text color of the header fields, otherwise it ends up as white on white.

*The rest of the important options can be found by selecting Options -> Export Options from the menu and then scrolling down to the "XLS Exporter" section. I attached a screen shot of the options I chose. You can experiment with the settings, but I found (through trial and error) that the options I ended up with work pretty well. These options are not stored in the report def file, they are attributes of the thing generating the report.  iReport takes care of it when testing in that environment. We are using custom Java to generate the report in production and we set the attributes there.

XLS Exporter Dialog http://www.imagechicken.com/uploads/1270760205041768200.png


text:
Q: How to suppress Cannot Find Symbol error when compiling java? I'm using Dagger, Room and DataBinding to develop my application, these libraries generate massive codes. When something wrong happened in my code, these libraries stop generating codes and produce massive Cannot Find Symbol error, which is annoying.
And java compiler will only output first 100 errors, which makes situation worse, I can't even knows where is the error of my code! Because all errors are 'Cannot Find Symbol'.
Is there anyway to suppress these Cannot Find Symbol errors, or, at least, shows dagger or databinding errors before these errors?

A: You can increase Error Limit.
Just include below lines in your grade
Java
allprojects{
  afterEvaluate{
     tasks.withType(JavaCompile.class) {
       options.compilerArgs << "-Xmaxerrs" << "500"
     }
   }
 }

Kotlin
kapt {
    javacOptions {
        option("-Xmaxerrs", 500)
    }
}


text:
Q: Scala vs Java method invocation I had to write my own JDK dynamic proxy to provide the ability of dynamic interface implementation. Since I work with akka it has to be written in Scala. But I faced with some pretty strange behavior differs from Java:
object Main extends App {
    println(classOf[Message].getDeclaredMethod("msg")
                            .invoke(Message("Test"), null))
                          //throws IllegalArgumentException
}

case class Message(message: String){
  def msg() = message
}

StackTrace:
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at Main$.delayedEndpoint$Main$1(Main.scala:2)
    at Main$delayedInit$body.apply(Main.scala:1)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
    at scala.App$class.main(App.scala:76)
    at Main$.main(Main.scala:1)
    at Main.main(Main.scala)

DEMO
But I in Java it works fine:
public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(Message.class.getDeclaredMethod("msg")
              .invoke(new Message(), null)); //prints Message
}

public static class Message{
    public String msg(){
        return "Message";
    }
}

DEMO
Why does Scala throw exception? And how to fix it?

A: Hopefully I can demonstrate what is going on:
class TheClass {
  def theMethod:Unit = { println("It's me the method"); }
}

scala> classOf[TheClass].getDeclaredMethod("theMethod").invoke(new TheClass, null)
java.lang.IllegalArgumentException: wrong number of arguments
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

scala> classOf[TheClass].getDeclaredMethod("theMethod").invoke(new TheClass)
It's me the method
res1: Object = null

As expected, but now have a look at this:
scala> classOf[TheClass]
      .getDeclaredMethod("theMethod").invoke(new TheClass, Array.empty)
java.lang.IllegalArgumentException: wrong number of arguments

Versus this:
scala> classOf[TheClass]
       .getDeclaredMethod("theMethod").invoke(new TheClass, Array.empty : _*)
It's me the method
res4: Object = null

Notice the difference between the invokes: .invoke(new TheClass, Array.empty) vs .invoke(new TheClass, Array.empty : _*). What happens is that invokes second argument is a varargs, which should be turned into a array under the hood, when it's given a plain Array.empty or null scalac is replacing them with Array(Array.empty) and Array(null). When the argument is not provided it's actually Array.empty and when we use : _* it just telling the compiler that the argument we are proving is the varargs itself.


text:
Q: How do I escape the ampersand character (&) in cql? I am inserting a statement into a table that looks something like this:
insert into db.table (field1, field2) values (1, 'eggs&cheese')
but when i later query this error on our servers, my query returns:
eggs\u0026cheese instead.
Not sure whether to use \ or '
If anyone can help, that would be great. Thank you!

A: This doesn't appear to be a problem with CQL but the way your app displays the value.
For example, if the CQL column type is text, the unicode character is encoded as a UTF-8 string.
Using this example schema:
CREATE TABLE unicodechars (
    id int PRIMARY KEY,
    randomtext text
)

cqlsh displays the ampersand as expected:
cqlsh> SELECT * FROM unicodechars  ;

 id | randomtext
----+-------------
  1 | eggs&cheese


text:
Q: Is there a reason for splitting a mochajs test suite into multiple files if I am going to run it serially? I am currently working on my first test suite using selenium with mocha.js in node.js. I will also need to automate GUI outside of the browser in most of my test cases (I am doing this with robot.js) and because of that, I will run it serially on a local Jenkins instance on a dedicated PC just for automation.
I am wondering if in my case does it make any sense to split my test suite into multiple files? I can skip failed tests, I have failure reporting connected to slack webhook, so how would I benefit from having multiple files instead of a single well-refactored and commented file?


text:
Q: macOS preferences are not being saved Running macOS Sierra 10.12.5 (16F73).
After migration from my old machine to the new machine, I am experiencing an issue where some apps do not retain settings.
The migration was not trivial and I actually had to re-create the user account and then move all of the user directories by hand, including the Library directory, where the settings, I believe are stored.
The UID however did not change, so it doesn't appear to be a permission issue. I've checked the permissions and even chown'ed the entire Library dir just in case.
Notably, the following symptoms persist:

*

*Opening iTunes always displays a welcome screen and EULA, every time I open it.

*VLC always displays a welcome screen and none of the settings are saved

*Photos app displays the welcome screen, but then takes me to the correct library and shows most recent photos correctly.

And many other apps that tend to write to Library dir behave in this way. They all open as if for the first time.
However, some apps do work fine. Like Firefox and Chrome. And several others.
Any ideas what needs to be done to restore order?
Thanks.


text:
Q: SQL LIMIT return 'zero' - 0 - rows(IN PHP) I have an error in this query, when the query returns zero rows.

Error Number: 1064
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 '-20,20' at line 3
SELECT pl.name,pl.email FROM players pl JOIN players_bonus pl_b on pl.id = pl_b.id_player WHERE pl_b.id_bonus = 3 LIMIT -20,20

My method is:

    public function getPViews_num_rows($limit = array(0,20),$page_num = 1,$id) {
        $limit = "LIMIT {$limit[0]},{$limit[1]}";

    $sql = "SELECT pl.name,pl.email FROM players pl
            JOIN players_bonus pl_b on pl.id = pl_b.id_player
                WHERE pl_b.id_bonus = ? {$limit}";

    $where =  array($id);
    $query = $this->db->query ( $sql,$where );
    return $query->num_rows ();
}

I don't wanna do another query to count rows,before I do this query.
Thanks for the answers.

A: The OFFSET value of the LIMIT clause has to be a nonnegative integer constant. Quoting the MySQL Documentation:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

A: You can not specify negative value to LIMIT clause:
LIMIT -20,20

It means you want to return 20 rows starting from -20 which is wrong.

A: The limit cannot be negative.


text:
Q: Paypal IPN INCOMPLETE status cause I am new to the paypal api, but have integrated it into my site. Every transaction has 2 receivers using the adaptive payments api. Every once in awhile I get an ipn response with status of INCOMPLETE. Reading the documentation it says this status is because
 Some transfers succeeded and some failed for a parallel payment or, for a delayed chained payment, secondary receivers have not been paid

Why would only one transaction work? Only the first recipient is getting the money causing problems. What is the best way to handle this? Anyway to immediately refund the buyer with the first recipients payment?

A: You could reverse all payments if any of them in the request fail using the reverseAllParallelPaymentsOnError parameter.

xs:boolean (Optional) Whether to reverse parallel payments if an error
  occurs with a payment. Allowable values are: true – Each parallel
  payment is reversed if an error occurs false – Only incomplete
  payments are reversed (default)


text: Q: How to clear webbrowser memory in windows phone 8 programmatically in pivot control I want to clear the memory of web browser page by page on forward and backward navigation in pivot control .I'm beginner for this platform please help me.Is it posiible?


text:
Q: Как при помощи регулярных выражений оставить строки определенного формата Есть вот у меня такая строка
7(917) 123-16-23 7(927) 123-14-11 -     -      5

как в питоне при помощи регулярных выражений можно оставить только те цифры которые попадают под такой шаблон?
(цифра, скобка, цифра, цифра, цифра, скобка, пробел, цифра....)

A: Попробуйте:
import re

text = "7(917) 123-16-23 7(927) 123-14-11"

print(re.findall(r'\d\(\d{3}\) \d{3}-\d\d-\d\d', text))
# ['7(917) 123-16-23', '7(927) 123-14-11']

Если несколько шаблонов разделяйте их вертикальной чертой, пример:
pattern = r'\d\(\d{3}\) \d{3}-\d\d-\d\d|\+\d \d{3} \d{3}-\d\d-\d\d'
text = "7(917) 123-16-23 +7 927 123-14-11 7(927) 123-14-11"

print(re.findall(pattern, text))
# ['7(917) 123-16-23', '+7 927 123-14-11', '7(927) 123-14-11']


text:
Q: XMLBeans bounded Atom, setting content of entry This is a question that is similar to this one : xmlbeans - set content of a complex type but not quite the same. What I am trying to do is to set the content of a contentEntry in an atom feed.
Here is the atom xsd definition for contentType, i.e. the content tag for entry in an atom feed.
<xs:complexType name="contentType" mixed="true">
    <xs:annotation>
        <xs:documentation>
            The Atom content construct is defined in section 4.1.3 of the format spec.
        </xs:documentation>
    </xs:annotation>
    <xs:sequence>
        <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="src" type="xs:anyURI"/>
    <xs:attributeGroup ref="atom:commonAttributes"/>
</xs:complexType>

After compilation by xmlbean' scomp, I get a nice jar file that makes me able to do the following.
EntryType curEntry;
curEntry = atomFeed.addNewEntry();
ContentType curContent = curEntry.addNewContent();
curContent.setBase("base");
curContent.setLang("en-EN");
curContent.setSrc("none");
curContent.setType("none");

And this is outputted as
<content xml:base="base" xml:lang="en-EN" src="none" type="none"/>

I really don't want to mess with the official (as official as I could find) xsd for atom, but I am missing a method to be able to set the actual text representation of the curContent. Only other set functions are set(XmlObject object) and setNil().
How can I change this so that I can get :
<content xml:base="base" xml:lang="en-EN" src="none" type="none">Content of this entry</content>

Thanks

A: You need to drop into XmlCursor land to insert mixed content.  For example,
    ContentType content = x.addNewContent();
    content.setType("none");

    XmlCursor cur = null;
    try
    {
        cur = content.newCursor();
        cur.toFirstContentToken();
        cur.insertChars("Hello World");
    }
    finally
    {
        cur.dispose();
    }


text:
Q: Объединение sql запросов в один класс JDBC Для подключения к бд и работы с ней использую две библиотеки commons dbutils и commons dbcp2 (пул подключений к бд).
Есть три класса в которых прописаны запросы к бд. Все эти классы отвечают за свой функционал (не просто так разделил)^
DataBaseUser
public class DataBaseUser {

    private QueryRunner queryRunner;

    public DataBaseUser(BasicDataSource basicDataSource) {
        this.queryRunner = new QueryRunner(basicDataSource);
    }

    ...
}

DataBaseAdmin
public class DataBaseAdmin {

    private QueryRunner queryRunner;

    public DataBaseAdmin(BasicDataSource basicDataSource) {
        this.queryRunner = new QueryRunner(basicDataSource);
    }

    ...
}

DataBaseChat
public class DataBaseChat {

    private QueryRunner queryRunner;

    public DataBaseChat(BasicDataSource basicDataSource) {
        this.queryRunner = new QueryRunner(basicDataSource);
    }

    ...
}

Как видно конструктор у всех один, но методы разные (дубликатов нет).
Хотелось бы создать один класс который бы смог получить доступ ко всем методам этих трех классов. Как правильно такое сделать? сделать класс обертку который в себе будет хранить все три класса? или как.
Еще. использование этих классов сейчас выглядит таким образом:
BasicDataSource basicDataSource = Core.getDataSource();

DataBaseAdmin dbAdmin = new DataBaseAdmin(basicDataSource);
DataBaseChat dbChat = new DataBaseChat(basicDataSource);

...

basicDataSource.getConnection().close();

Тут я беру DataSource который предоставляет библиотека dbcp2 передаю в QuerryRunner который их DbUtils. Он же в свою очередь берет подключение из пула. В последней строке возвращаю подключение в пул свободных.

A: Именно так "сделать класс обертку который в себе будет хранить все три класса":
    class BusinessLogic {
        private BasicDataSource basicDataSource;
        private DataBaseUser dataBaseUser;
        private DataBaseAdmin dataBaseAdmin;
        private DataBaseChat dataBaseChat;

        public BusinessLogic(
                BasicDataSource basicDataSource,
                DataBaseUser dataBaseUser,
                DataBaseAdmin dataBaseAdmin,
                DataBaseChat dataBaseChat) {
            this.basicDataSource = basicDataSource;
            this.dataBaseUser = dataBaseUser;
            this.dataBaseAdmin = dataBaseAdmin;
            this.dataBaseChat = dataBaseChat;
        }

        public doLogic() {
            //DO MY LOGIC
            basicDataSource.getConnection().close(); //не очень хорошо закрывать подключение здесь, так как подключение должно закрываться там, где открывалось
        }
    }

Только добавить интерфейсы User, Admin, Chat вместо конкретных классов. И в классе использовать интерфейсы.
    class BusinessLogic {
        private BasicDataSource basicDataSource;
        private User user;
        private Admin admin;
        private Chat chat;

        public BusinessLogic(
                BasicDataSource basicDataSource,
                User user,
                Admin dataBaseAdmin,
                Chat dataBaseChat) {
            this.basicDataSource = basicDataSource;
            this.user = user;
            this.admin = admin;
            this.chat = chat;
        }

        public doLogic() {
            //DO MY LOGIC
            basicDataSource.getConnection().close(); //не очень хорошо закрывать подключение здесь, так как подключение должно закрываться там, где открывалось
        }
    }


text:
Q: Why did the Silence need a space suit? What was the whole purpose of producing the space suit for The Impossible Astronaut? Couldn't the Silence achieve their purpose in simpler methods?

(I saw all the episodes, feel free to spoiler in your answers)

A: Per my answer here;
The Silence needed the suit to physically control River Song. They're aware of the events surrounding his death (e.g. that he's shot by River Song at Lake Silencio on the date in question wearing an Apollo spacesuit) and must have been quite surprised to find that she had no intention of doing so.
Their reaction was to travel further back into time and guide the development of the human race to the point that they'd developed a space suit capable of being used as a physical control device, turning her into a 'people puppet'.
In the episode 'The Impossible Astronaut' River Song is later reported to have said to the Doctor (at the moment of his apparent death):

"I can't stop it - the suit's in control".

As to why they didn't try something less convoluted (e.g. altering the entirety of human history just to get hold of a space suit that they could have easily replicated themselves) the answer is that it's not been explained.

A: I also think the suit represents that Riversong is kind of in a controlled incubating machine or self preservation armour, being space themed it of course had to be an astronaught suit, it's also potentially the same suite that ages her or twisted her time line against The Doctors as a sort anti Doctor timeline, knowing that Amy and Rory are amongst The Doctors dearest friends, what better way to punish him then by using his friends child as a trained assasin to kill him. And by making sure they never meet properly there after the kill River was to meet him backwards so she new that her task was to kill him, but of course she lived him to much to do so, so the suite can never really control her, when she meets Amy in the suit she's trying to warn Amy, not hurt her.

A: In a later episode I believe it is stated that they needed to over load the suit to prevent River Song from regenerating and force all her R.E. along with the suits power supplying a single blast killing the doctor. Also the original design of a space suit is based off of a diving suit so it would keep River alive long enough under water to have to regenerate when the time comes; it can also be considered a clue to the time that the doctor needs to go to in order to try to save himself while a diving suit would be too mysterious.


text:
Q: Angular : Activate checkbox on some conditions throws ExpressionChangedAfterItHasBeenCheckedError I currently implement angular project which needs a term and conditions agreement. So I have created a scrollable div of 300 px in which I load the content from the database. We want to force the user to read all T&C before activating the checkbox.
It's working well when T&C are heavy. When T&C are light, the scrollable function is not called. So I want to initialize the disabled state of the checkbox at the end of the loading but angular throws ExpressionChangedAfterItHasBeenCheckedError.
Here is the stackblitz of my project : https://stackblitz.com/edit/angular-b9p6rx
I tried many solutions :

*

*replace the *ngIf by [hidden]

*use a fonction to evaluate the state

*check in the afterViewContentInit

*Use a setter on the div content

I want to avoid the setTimeout call to evaluate the state.
What solutions do you see ?
Is there a better way to implement this function ?
Thanks in advance.
app.component.html

Terms and conditions

        {{agreementHeader1}}

        I accept the terms and conditions

        <button type="button" class="btn btn-primary mx-2" >Annuler</button>
        <button type="submit" class="btn btn-primary mx-2" [disabled]="!areCGUAccepted">Valider</button>

app.component.ts
export class AppComponent  {
  public agreementHeader1: string;
    public cguContent: string;
    public hasContentBeenRead: boolean = false;
    public areCGUAccepted: boolean = false;
    public isNotUpToDateCGU: boolean  = false;

    private cguContainerRef: ElementRef;
    @ViewChild('cguContainer') set controlElRef(elementRef: ElementRef) {
      if (elementRef) {
        this.cguContainerRef = elementRef;
        this.checkReading();
      }
    }

    constructor(
        private confService: ConfigurationService,
    ) { }

    public ngOnInit(): void {
      this.confService.getConfiguration('./terms.json')
            .subscribe(result => {

                this.agreementHeader1 = 'You have to read all terms and conditions to accept them';

                // !!!!!!! invert the two lines to test with big terms
                // this.cguContent = result.bigTerms;
                this.cguContent = result.littleTerms;

                this.isNotUpToDateCGU = true; // load template
            });
    }

    public checkReading(): void {

        let element = this.cguContainerRef.nativeElement;

        // height of the div in css => height: 300px
        if (element.scrollHeight - element.scrollTop < 301) {
            this.hasContentBeenRead = true;
        }
    }
}

A:
This will only happen when app in dev mode. In your case this happen because after you set this.isNotUpToDateCGU = true; there is no new round of change detection happen until it might be triggered in future time. Therefore trigger change detection manually after your set this.isNotUpToDateCGU = true;
First import ChangeDetectorRef
import { ChangeDetectorRef  } from '@angular/core';

Then use it like below
constructor(
    private confService: ConfigurationService,
    private changeDetectorRef: ChangeDetectorRef
) { }

public ngOnInit(): void {
  this.confService.getConfiguration('./terms.json')
        .subscribe(result => {

            this.agreementHeader1 = 'You have to read all terms and conditions to accept them';

            // !!!!!!! invert the two lines to test with big terms
            // this.cguContent = result.bigTerms;
            this.cguContent = result.littleTerms;

            this.isNotUpToDateCGU = true; // load template
            this.changeDetectorRef.detectChanges();

        });
}

Working Demo
Hope this will help to you!