text:
Q: How parse HTTPHeader in Swift I would like to write a Swift script to authenticate against a Rest Server with digest authentication. I will not use URLSession, i would like to do it manually. I get an first response from the server like this one:
[
  ("Connection", "close"),
  ("Date", "Sun, 22 Dec 2019 07:36:50 GMT"),
  (
    "WWW-Authenticate",
    "Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"
  ),
  (
    "Cache-Control",
    "must-revalidate,no-cache,no-store"
  ),
  (
    "Content-Type",
    "text/plain;charset=utf-8"
  ),
  ("Content-Length", "16"),
  ("Server", "Jetty(9.4.19.v20190610)")
]

I get an object HTTPResponseHead in Swift. But how can I read the nonce or other part of the header. If I to call print (head.headers.contains(name: "nonce")) i get the result false. head is an object of HTTPResponseHead. Have I do manually parse the Header or there exists to read the header and  then create my hashes for the authentication.

A: Try with this method.
 func getAuthenticationKey(headerInfo: [(String, String)]) -> String?{
        for item in headerInfo.enumerated(){
            print("key: \(item.element.0), values : \(item.element.1)")

            let headerKeys = item.element.1.split(separator: ",")

            for item in headerKeys {
                if item.contains("nonce") {
                    let authinticationKey = item.split(separator: "=")[1]
                    return String(authinticationKey)
                }
            }

        }
        return nil
    }

USE:
 let headerInfo = [("Connection", "close"), ("Date", "Sun, 22 Dec 2019 07:36:50 GMT"), ("WWW-Authenticate", "Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"), ("Cache-Control", "must-revalidate,no-cache,no-store"), ("Content-Type", "text/plain;charset=utf-8"), ("Content-Length", "16"), ("Server", "Jetty(9.4.19.v20190610)")]
 print(getAuthenticationKey(headerInfo: headerInfo))

Output:

"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz"


text:
Q: Unable to deserialize ActorRef to send result to different Actor I am starting to use Spark Streaming to process a real time data feed I am getting. My scenario is I have a Akka actor receiver using "with ActorHelper", then I have my Spark job doing some mappings and transformation and then I want to send the result to another actor.
My issue is the last part. When trying to send to another actor Spark is raising an exception:

15/02/20 16:43:16 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 2, localhost): java.lang.IllegalStateException: Trying to deserialize a serialized ActorRef without an ActorSystem in scope. Use 'akka.serialization.Serialization.currentSystem.withValue(system) { ... }'

The way I am creating this last actor is the following:
val actorSystem = SparkEnv.get.actorSystem
val lastActor = actorSystem.actorOf(MyLastActor.props(someParam), "MyLastActor")

And then using it like this:
result.foreachRDD(rdd => rdd.foreachPartition(lastActor ! _))

I am not sure where or how to do the advise "Use 'akka.serialization.Serialization.currentSystem.withValue(system) { ... }'". Do I need to set anything special through configuration? Or create my actor differently?

A: Look at the following example to access an actor outside of the Spark domain.
/*
     * Following is the use of actorStream to plug in custom actor as receiver
     *
     * An important point to note:
     * Since Actor may exist outside the spark framework, It is thus user's responsibility
     * to ensure the type safety, i.e type of data received and InputDstream
     * should be same.
     *
     * For example: Both actorStream and SampleActorReceiver are parameterized
     * to same type to ensure type safety.
     */
val lines = ssc.actorStream[String](
  Props(new SampleActorReceiver[String]("akka.tcp://test@%s:%s/user/FeederActor".format(
    host, port.toInt))), "SampleReceiver")

A: I found that if I collect before I send to the actor it works like a charm:
result.foreachRDD(rdd =>  rdd.collect().foreach(producer ! _))

redpajama_set_name: RedPajamaStackExchange


text:
Q: While app is running on an Android device, how can I programmatically get the name of the APK file used for installation? In my code, is it possible to check if the app is running on an Android device, and if so, return the name of the APK file used to install the app on the device?  In my case, that name is app-debug.apk.
The motivation for the question is that I'd like to give the APK a custom name, then when the app is running on the device, to execute some custom code, and set some custom configuration, based on the name of the APK.  Maybe there is a better process to achieve that?
On Stack Overflow, I've seen many questions about how to change the APK name before the build, but none on how to programmatically check the APK name. I've also seen questions about how to check the APK name using native Android code.
Thanks.

A: I'm answering my own question to let people know how I resolved this issue.  The short answer is that I never figured out how to read the APK name.  I achieved the custom configuration I wanted by reading something else.
More Info
In my case, the customization I wanted to do was solely to my project's config.xml file.  My original thought was to read the APK name from my code, and make customization (e.g. change the logo file) based on its value.  But instead, I ensured the custom edits were made based on an environmental variable I passed to the build command via the command line.  And I ensured this customization occurred on every build, using a Cordova hook.  That solution was something I saw in this separate Stack Overflow answer.


text:
Q: Exibir uma imagem quando outra não é carregada Olá,
Eu estou fazendo uma página web na qual as imagens são pegas de fora do servidor, porém algumas vezes a imagem não existe mais, ou o link quebrou, então, eu gostaria de exibir uma outra imagem.
O código seria assim:

    @if(condição de imagem existe){

    }else{//aqui é quando a imagem não for encontrada, se isso ocorrer eu quero que carregue uma imagem do meu servidor

    }

A: Você pode usar o atributo onerror na própria tag. Esse atributo irá executar um código caso haja falha no carregamento da imagem, e esse código pode ser alterando o src da imagem pelo da imagem padrão que você quiser.
Vou colocar abaixo 2 exemplos, um com falha e outro sem falha:
Com falha

img{
   width: 100px;
   height: 100px;
}

Sem falha

img{
   width: 100px;
   height: 100px;
}


text:
Q: PHP - Get random number by clicking button i got two php pages, one generating random numbers and another displaying on refresh page.
i want to get current random value by clicking not refreshing.
we could use javascript / ajax / jquery for that please help me any best way
1.php
<?php
 include("2.php");

 $getnumber=$_SESSION['randomnumber'];

 ?>

 <button class="button" type="button" name="buttonpassvalue" >Get Random Number</button>

2.php
 <?php
  $rannumber=rand();

   $_SESSION['randomnumber']=$rannumber;
   ?>

thanks for your help.

A: this could be used without any php coding, whenever want something to happen without refreshing the page , javascript is your buddy

0

<button onclick="generate()">Randomize</button>

i suggest you take a look over here http://www.w3schools.com/jsref/jsref_random.asp

A: You can do something with JQuery/Javascript, which won't refresh the page by doing:

            <button class="button" type="button" name="buttonpassvalue" id="random" >Get Random Number</button>

//<---This is where the random number would be placed

I have tested this and it works :)
Example is here: http://jsfiddle.net/Q5uKe/


text:
Q: Large array of NSManagedObjects Application have viewcontroller with large array of objects and it has a serious memory pressure. There are a solution - store only managedObjectIds array instead of managed objects, but I'm not sure that is a most efficient way to optimize memory management because object ids is are long too. Is there any solution to reduce memory usage?

A:
Because of complex filtering and sorting I use custom object(not
  managed object) as parent of managed object. Sorry, I forgot to
  mention this important detail

You should try to move filtering and sorting to be a predicate and sortDescriptors of NSFetchRequest. Then you could use fetchBatchSize to limit the number of objects which are simultaneously fetched from the persistent store and kept in memory.


text:
Q: Objects in Scene dark after calling LoadScene/LoadLevel I completed Unity's roll-a-ball tutorial and it works fine. I changed a couple of materials to make it look better. I also added a C# script that should restart the level when the player falls off of the ground (I disables the walls). I am using Unity 5.5.
It initially looks like this:
But when I go off the edge and the level restarts, it looks like this:

It sometimes looks like this for a few seconds after opening unity when the editor is loading.
Here is the script:
using UnityEngine;
using System.Collections;

public class DeathTrigger : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    void OnTriggerEnter (Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
            Application.LoadLevel(Application.loadedLevel);
    }
}

Any ideas on what's causing this?

A: After play with Lighting tools, only one thing should be change on Lighting Setting for every scene.

*

*Window > Rendering > Lighting (Unity 2020)

*Click at Environment Tab

*At Environment Lighting, change Source from Skybox to Color.

*Select white color from Ambient Color.

*Done. Try test it.

Before

After

A: I found many solutions online but I was missing out a step, so I hope this helps.
Most solutions indicated to go to Windows->Lightning, then untick Auto and Click Generate Lighting. My problem was that while I was pressing the generate button I did not have all of my scenes loaded for preview (at least not the scene I had problems with), so it was only applying light generation to the loaded scenes. Make sure all scenes are loaded when generating the lights.

A: The colors and materials are loaded. This is a lighting problem because lighliting is still calculating in the background. This will likely occur in the Editor only. This should not happen in the build.
Depending on your Unity version, you can fix this by going to Windows --> Lighting --> Settings then go to the Scene tab. Scroll down and disable Auto Generate checkbox then click the Generate Lightning button.

For older version of Unity with no Auto Generate checkbox, see here.

A: Try Clearing Baked Data if you are using unity version around 5.5
Go to Windows->Lightning->Untick Auto->Now Click dropdown arrow of Build Button which is near Auto(Check Box) -> Select Clear Baked Data.
Now try Your code which looks fine although SceneManager.LoadScene (1); is enough.
Also unloading the previous scene and setting new scene as active scene is a good practice.
This worked for me.

A: File > Build settings > player Settings > (on the left) Graphics > (Top-Right) gear icon > Reset

A: I'm a newbie and none of the advice on web helped me. However when I went to Window > Rendering > Lightning > scene tab; If "lightning setting" says "none", click on it and choose "demo"- setting. Press "generate".
So it seems like it was missing settings all together which made the scene go dark when loaded.

A: I encountered the exact same problem. What worked for me was to set Directional Light > Light > Mode to Realtime. (it was Baked, for some reason)
I hope this can help someone in the future.


text:
Q: count occurrences across columns and match to ID column I have a df of 100+ columns and not all are filled
> head(othertopics,20)
# A tibble: 20 x 118
   Q6    Q10.1 Q10.2 Q10.3 Q10.4 Q10.5 Q10.6 Q10.7 Q10.8 Q10.9 Q10.10 Q10.11 Q10.12 Q10.13
   <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>  <chr>  <chr>  <chr>
 1 52    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 2 294   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 3 103   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 4 52    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 5 87    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 6 52    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 7 136   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 8 19    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
 9 19    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
10 0     NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
11 0     NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
12 19    NA    NA    NA    4     NA    NA    NA    NA    NA    NA     NA     NA     NA
13 52    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA
14 108   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA     NA     NA     NA

Q6 is an ID.
across Q10.1 to Q10.117 there are different values assigned for each ID (see line 12).
Using unlist i used unlist and managed to get the frequency for every time a value was mentioned among the 117 columns. But i need to match them to their respective ID.
So basically i need to match an ID col with 117 columns and get the frequency of each column.
othertopics<-data.frame(table(unlist(TableTopic2[,22:138])))

    Var1 Freq
    10    1
    100    4
    101    1
    102   12
    103    7
    104   21
    105   36
    106    1

so for example variable 105 appeared 36 times across 17 values of IDs on column Q6( This number I counted on Excel).
So, so far I only have the first half of my solution as i need to know what is the ID associated with the variables . ( ie: the 17 values i counted)
also note that the variable columns contain the number of their variable, So for example row Q10.105 is for variable 105 which has a frequency of 36.

I hope i was able to make it clear.

Thanks!

A: This question is not particularly clear, but I'll do my best. I think the way to tidy this data is to pivot all of the non-id columns to one column (I call it 'col_name') and then have another column with all of the values (mostly NA's; I call it 'numbered_var' for numbered variable). Then, you can aggregate based on the numbered_variable column.
This example is obviously not reproducible, so I constructed a simplified version of your data (I think):
library(dplyr)
library(tidyr)

df <- tibble(
    id = 1:5,
    Q1 = c(NA_integer_, 10L, NA_integer_, 10L, NA_integer_),
    Q2 = c(NA_integer_, NA_integer_, 11L, NA_integer_, 11)
)

It looks like this:
# A tibble: 5 × 3
     id    Q1    Q2
  <int> <int> <dbl>
1     1    NA    NA
2     2    10    NA
3     3    NA    11
4     4    10    NA
5     5    NA    11

Next, I use tidyr::pivot_longer() to put the column names containing Q into a column, with their associated value in another column:
df <- pivot_longer(
        df,
        cols = contains("Q"), # you will want to use this, but first remove the Q from the id column name in your data
        names_to = "col_name",
        values_to = "numbered_var"
)

This makes the data long:
# A tibble: 10 × 3
      id col_name numbered_var
   <int> <chr>           <dbl>
 1     1 Q1                 NA
 2     1 Q2                 NA
 3     2 Q1                 10
 4     2 Q2                 NA
 5     3 Q1                 NA
 6     3 Q2                 11
 7     4 Q1                 10
 8     4 Q2                 NA
 9     5 Q1                 NA
10     5 Q2                 11

You should still probably have three columns, but the id's would repeat themselves n-column times, just as they repeat twice for the two columns here.
Next, I would group by the variables, which seem to be of interest, and list the unique id's that have the variables in a new column:
df <- group_by(df, numbered_var)
df <-   summarize(
        df,
        var_appearances = n(),
        ids = list(unique(id))
    )

Now, the data frame looks like this:
# A tibble: 3 × 3
  numbered_var var_appearances ids
         <dbl>           <int> <list>
1           10               2 <int [2]>
2           11               2 <int [2]>
3           NA               6 <int [5]>

That ids column is a list-column with a vector of ids:
print(df$ids)
[[1]]
[1] 2 4

[[2]]
[1] 3 5

[[3]]
[1] 1 2 3 4 5

I'm not sure this is exactly what you'll be able to do, but hopefully it sets you in the right direction.


text:
Q: I am trying to Implement a function which takes array input and gives products of array with skipping 0 in Javascript but I can only use .reduce function multiplyArray(array) {
  let product_arr = array.reduce(function (accumulator, currentValue) {
    return accumulator * currentValue
  }, 1);
  return product_arr;
}

A: You can check for 0 and return the value on the basis of that like below:

function multiplyArray(array) {

  let product_arr = array.reduce(function(accumulator, currentValue) {
      // If value is 0 return accumulator else return value * accumulator
    return (currentValue == 0 ? accumulator * 1 : accumulator * currentValue)
  }, 1);

  return product_arr

}

console.log(multiplyArray([1, 2, 3, 4, 0, 9]))

A: you could just default to 1 when the array item is 0.

const multiply = (nums) => nums.reduce((a, b) => a * (b || 1), 1);

console.log(
  multiply([0, 1, 2, 0, 3, 4, 0]),
)


text:
Q: (Chrome Extension) How to focus on the omnibox when you create a new tab? I'm making a chrome extension that redirects you to a specific url every time you open a new tab. The code I'm using is down below. However it is really annoying that whenever I open a new tab, it does it's job in redirecting me to the url but it does not highlight the omnibox!! This means it really frustrating to do my searches as this address bar is not highlighted. I know Control + L is an option but we are all so used to not doing this.
When I open a new tab, I can see the omnibox being highlighted but then it it goes away right afterwards. Is there a way keep this address bar highlighted before, during and after the redirect?
I know this is possible because this extension, Tab for a cause redirects you to their custom url while still keeping the onmibox highlighted!!
Thank you in advance!
I'm using manifest version 2.
manifest.json
{
    "name": "...",
    "manifest_version": 2,
    "version": "1.0",
    "description": "...",
    "chrome_url_overrides": {
        "newtab": "my.html"
    },
    "permissions": [
        "tabs",
    ]
}

my.html
<!DOCTYPE html>
<html>
    <head>
        <title>...</title>
        <script type="text/javascript" src="code.js">
        </script>
    </head>
    <body>
    </body>
</html>

code.js
window.location.href = "https://website-of-interest.com/"


text:
Q: Keras ImageDataGenerator with flow, Got ValueError: `x` (images tensor) and `y` (labels) should have the same length I'm working out the CNN course on Coursera, and as I try to solve the assignment notebook, this is the error thrown at me.
ValueError: `x` (images tensor) and `y` (labels) should have the same length. Found: x.shape = (27455, 28, 28, 1), y.shape = (7172, 28, 28, 1)
But aren't they of the same length? (the dimension that is.)
The following is my code block that is creating the issue:
# GRADED FUNCTION: train_val_generators
def train_val_generators(training_images, training_labels, validation_images, validation_labels):
  """
  Creates the training and validation data generators

  Args:
    training_images (array): parsed images from the train CSV file
    training_labels (array): parsed labels from the train CSV file
    validation_images (array): parsed images from the test CSV file
    validation_labels (array): parsed labels from the test CSV file

  Returns:
    train_generator, validation_generator - tuple containing the generators
  """
  ### START CODE HERE

  # In this section, you will have to add another dimension to the data
  # So, for example, if your array is (10000, 28, 28)
  # You will need to make it (10000, 28, 28, 1)
  # Hint: np.expand_dims

  training_images = np.expand_dims(training_images, axis=3)
  validation_images = np.expand_dims(validation_images, axis=3)

  print(training_images.shape)
  print(validation_images.shape)

  # Instantiate the ImageDataGenerator class
  # Don't forget to normalize pixel values
  # and set arguments to augment the images (if desired)
  train_datagen = ImageDataGenerator(
    # Your Code Here
    rescale = 1./255,
    rotation_range = 40,
    width_shift_range = 0.2,
    height_shift_range = 0.2,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
    fill_mode = 'nearest'
    )

  # Pass in the appropriate arguments to the flow method
  train_generator = train_datagen.flow(x=training_images,
                                       y=validation_images,
                                       batch_size=32)

  # Instantiate the ImageDataGenerator class (don't forget to set the rescale argument)
  # Remember that validation data should not be augmented
  validation_datagen = ImageDataGenerator(
      rescale = 1./255
  )

  # Pass in the appropriate arguments to the flow method
  validation_generator = validation_datagen.flow(x=training_images,
                                                 y=validation_images,
                                                 batch_size=32)

  ### END CODE HERE

  return train_generator, validation_generator

After running this cell, it's working fine and adding an extra dimension to my images. The following code cell raises the above-mentioned issue.
# Test your generators
train_generator, validation_generator = train_val_generators(training_images, training_labels, validation_images, validation_labels)

print(f"Images of training generator have shape: {train_generator.x.shape}")
print(f"Labels of training generator have shape: {train_generator.y.shape}")
print(f"Images of validation generator have shape: {validation_generator.x.shape}")
print(f"Labels of validation generator have shape: {validation_generator.y.shape}")

This is my entire error messasge:
(27455, 28, 28, 1)
(7172, 28, 28, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-c93bf4854fbc> in <module>()
      1 # Test your generators
----> 2 train_generator, validation_generator = train_val_generators(training_images, training_labels, validation_images, validation_labels)
      3
      4 print(f"Images of training generator have shape: {train_generator.x.shape}")
      5 print(f"Labels of training generator have shape: {train_generator.y.shape}")

3 frames
/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/numpy_array_iterator.py in __init__(self, x, y, image_data_generator, batch_size, shuffle, sample_weight, seed, data_format, save_to_dir, save_prefix, save_format, subset, dtype)
     87                              'should have the same length. '
     88                              'Found: x.shape = %s, y.shape = %s' %
---> 89                              (np.asarray(x).shape, np.asarray(y).shape))
     90         if sample_weight is not None and len(x) != len(sample_weight):
     91             raise ValueError('`x` (images tensor) and `sample_weight` '

ValueError: `x` (images tensor) and `y` (labels) should have the same length. Found: x.shape = (27455, 28, 28, 1), y.shape = (7172, 28, 28, 1)

I tried searching many similar problems in StackOverflow, which talked about changing its dimensions, but my dimensions are correct I think because changing it did absolutely nothing. Any insights on this? Please help. Thanks! :_)

A: In the train_datagen.flow and validation_datagen.flow, you make two small mistakes. For the y parameter, you pass validation_images, but you need to pass training_labels and validation_labels.
I correct the above mistakes and write full code with random images and a simple CNN model and fit it.
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import numpy as np

def train_val_generators(training_images, training_labels, validation_images, validation_labels):
  training_images = np.expand_dims(training_images, axis=3)
  validation_images = np.expand_dims(validation_images, axis=3)

  print(training_images.shape)
  print(validation_images.shape)

  train_datagen = ImageDataGenerator(
    rescale = 1./255,
    rotation_range = 40,
    width_shift_range = 0.2,
    height_shift_range = 0.2,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
    fill_mode = 'nearest'
    )

  train_generator = train_datagen.flow(x=training_images,
                                       y=training_labels,
                                       batch_size=32)

  validation_datagen = ImageDataGenerator(
      rescale = 1./255
  )

  validation_generator = validation_datagen.flow(x=validation_images,
                                                 y=validation_labels,
                                                 batch_size=32)

  return train_generator, validation_generator

train_generator, validation_generator = train_val_generators(
    training_images = np.random.rand(27455, 28,28),
    training_labels = np.random.randint(0,2,27455),
    validation_images = np.random.rand(7172, 28,28),
    validation_labels = np.random.randint(0,2,7172),
    )

model = tf.keras.Sequential([
  tf.keras.layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=(28, 28, 1)),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, padding='same', activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(64, activation='relu'),
  tf.keras.layers.Dropout(0.4),
  tf.keras.layers.Dense(2)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))

model.fit(train_generator,
          epochs=2,
          validation_data=validation_generator)

Output:
(27455, 28, 28, 1)
(7172, 28, 28, 1)
Epoch 1/2
858/858 [==============================] - 25s 25ms/step - loss: 0.6933 - val_loss: 0.6931
Epoch 2/2
858/858 [==============================] - 18s 21ms/step - loss: 0.6932 - val_loss: 0.6930


text:
Q: Passing parameters made easy in java

public class Model {

public void updateEvent(String name, Date date,String start, String venue, String details,
String opportunity, String more, String end, String row) {
//do stuff here

}

public class Controller {

 public void someMethod() {

 if(button==view.saveButton) {

 model.updateEvent(view.txtEventName.......);

 } }

}

public class View {
public JTextField txtEventName;
//10 more consisting of textarea, datechooser, etc

}

How can I pass a bunch of parameters to for Controller to pass to Model to update its state. Well, if the View is acting as form, it will have lots of text fields, text area etc. for data entry. rather than dealing with them individually how can controller gain access to all of them easily to pass to model. I dont want to simply keep adding view.txtWhere.getText() which is long.

A: Create an "Event" class that has String name, Date date,String start, String venue, String details,
String opportunity, String more, String end, String row and use it instead ?


text:
Q: LEFT JOIN-ing the same MySQL View multiple times makes some of the Views derived I have a Hibernate-generated query that LEFT OUTER JOINs MySQL Views on some of the columns.
The query performs really poor so I EXPLAIN-ed it and found that in some cases the same View is treated as a derived select.
Here is my query generated by Hibernate. I have simplified it for the sake of the example:
SELECT
   *
FROM
   `task` `task`
   LEFT OUTER JOIN
      `view_users` `vu`
      ON `task`.`created_by` = `vu`.`id`
   LEFT OUTER JOIN
      `view_users` `vu2`
      ON `task`.`updated_by` = `vu2`.`id`

The view_users MySQL View that I use in the LEFT OUTER JOINs is this:
SELECT
    `user`.`id` AS `id`,
    `role`.`role` AS `role`,
    `branch`.`name` AS `branch_name`,
    `address`.`city` AS `city`
FROM
    ((((`user` `user`
    JOIN `role` `role` ON ((`user`.`role_id` = `role`.`id`)))
    LEFT JOIN `branch` `branch` ON ((`branch`.`id` = `user`.`branch_id`)))
    LEFT JOIN `address` `address` ON ((`address`.`id` = `user`.`address_id`)))

The result of the EXPLAIN is the following:

Here I noticed that task.created_by has PRIMARY select_type, while task.updated_by is treated as DERIVED, and because of this, MySQL will scan 54876 rows when LEFT OUTER JOINing the view_users View on task.updated_by.
After this I used EXPLAIN EXTENDED, then SHOW WARNINGS, and I got the following query that has been "rewritten" by MySQL:
SELECT
   *
FROM
   `task` `task`
   LEFT JOIN
      (
         `user` `user`
         JOIN
            `role` `role`
         LEFT JOIN
            `branch` `branch`
            ON((`branch`.`id` = `user`.`branch_id`))
         LEFT JOIN
            `address` `address`
            ON((`address`.`id` = `user`.`address_id`))
      )
      ON(((`role`.`id` = `user`.`role_id`)
      AND
      (
         `user`.`id` = `task`.`created_by`
      )
))
   LEFT JOIN
      `view_users` `vu`
      ON((`vu`.`id` = `task`.`updated_by`))

Here we can see that the view_users View that has been joined on task.created_by is "resolved", while on task.updated_by it will use view_users.
Why does MySQL derives Views for some occasions and not for others?
Ideally I would expect that task.updated_by would not be derived, so the performance of the original query would be much better.


text:
Q: Host git repository and access it through my computer's ip I would like to host my project on my own computer, since my computer is on all the time, and access it when im away from home and clone it on my other laptop when needed, and then commit to my desktop computer, basically using it as a GIT host.
Is it possible to do so? I do not want to use GitHub since I dont want to pay the $7 a month, and i would like to use my computer instead.
I made a repository right now with all of my project files inside, how do i continue from here?

A: You could instead use Atlassian BitBucket, which has unlimited free private repos


text:
Q: XSS Vulnerability with PCI RapidComply I have a website hosted on an Apache Tomcat 7 server that uses the Authorize.net gateway and merchant services to handle payment.  I recently ran a required PCI Compliance test against my website, and it failed due to a Reflected Cross-Site
Scripting (XSS) Vulnerability.  The example they gave was to replace the value of one of my form parameters with a script: alert('test')
I feel that I have already addressed this issue on the client-side by validating inputs when the form is submitted, and not proceeding if one of the inputs is invalid.  However, a re-scan recently failed, so I think I need to do more.
My first question: is it possible to pass POST parameters to the server via the URL?  I thought this was only possible with GET method, which I don't utilize.  What I'm trying to figure out is how they are submitting this data.  Their support is non-existent, of course, so I have to figure out the issue on my own.
Has anyone had any experience with PCI RapidComply?  What did you use to fix your XSS Validation issues?
Thanks!

A: You cannot pass POST parameters via the URL, but that is not required for an XSS-vulnerability. A third party site can send the user to your site with any POST parameter they want by using JavaScript:
<html>
  <body onload="document.forms[0].submit()">
    <form action="https://yoursite.example.com/" method="post">
      <input type="hidden" name="parameter" value="alert('test')">
    </form>
  </body>
</html>

As long as the attacker can cause an end user with access to your site to load such an HTML document (e.g. through an iframe put on an ad network), they can cause the user to run arbitrary JavaScript on your page in the context (session) of that user.
The only way to prevent this is by handling it server side. In general, any user data submitted should be sanitized, and also remember to escape everything when outputting HTML. Usually the last part should be handled by a templating library.


text:
Q: Server design using SocketAsyncEventArgs I want to create an asynchronous socket Server using the SocketAsyncEventArgs event.
The server should manage about 1000 connections at the same time. What is the best way to handle the logic for each packet?
The Server design is based on this MSDN example, so every socket will have his own SocketAsyncEventArgs for receiving data.

*

*Do the logic stuff inside the receive function.
No overhead will be created, but since the next ReceiveAsync() call won't be done before the logic has completed, new data can't be read from the socket. The two main questions for me are: If the client sends a lot of data and the logic processing is heavy, how will the system handle it (packets lost because buffer is to full)? Also, if all clients send data at the same time, will there be 1000 threads, or is there an internal limit and a new thread can't start before another one completes execution?

*Use a queue.
The receive function will be very short and execute fast, but you'll have decent overhead because of the queue. Problems are, if your worker threads are not fast enough under heavy server load, your queue can get full, so maybe you have to force packet drops. You also get the Producer/Consumer problem, which can probably slow down the entire queue with to many locks.
So what will be the better design, logic in receive function, logic in worker threads or anything completely different I've missed so far.
Another Quest regarding data sending.
Is it better to have a SocketAsyncEventArgs tied to a socket (analog to the receive event) and use a buffer system to make one send call for a few small packets (let's say the packets would otherwise sometimes! send directly one after another) or use a different SocketAsyncEventArgs for every packet and store them in a pool to reuse them?

A: To effectivly implement async sockets each socket will need more than 1 SocketAsyncEventArgs. There is also an issue with the byte[] buffer in each SocketAsyncEventArgs. In short, the byte buffers will be pinned whenever a managed - native transition occurs (sending / receiving). If you allocate the SocketAsyncEventArgs and byte buffers as needed you can run into OutOfMemoryExceptions with many clients due to fragmentation and the inability of the GC to compact pinned memory.
The best way to handle this is to create a SocketBufferPool class that will allocate a large number of bytes and SocketAsyncEventArgs when the application is first started, this way the pinned memory will be contiguous. Then simply resuse the buffers from the pool as needed.
In practice I've found it best to create a wrapper class around the SocketAsyncEventArgs and a SocketBufferPool class to manage the distribution of resources.
As an example, here is the code for a BeginReceive method:
private void BeginReceive(Socket socket)
    {
        Contract.Requires(socket != null, "socket");

        SocketEventArgs e = SocketBufferPool.Instance.Alloc();
        e.Socket = socket;
        e.Completed += new EventHandler<SocketEventArgs>(this.HandleIOCompleted);

        if (!socket.ReceiveAsync(e.AsyncEventArgs)) {
            this.HandleIOCompleted(null, e);
        }
    }

And here is the HandleIOCompleted method:
private void HandleIOCompleted(object sender, SocketEventArgs e)
    {
        e.Completed -= this.HandleIOCompleted;
        bool closed = false;

        lock (this.sequenceLock) {
            e.SequenceNumber = this.sequenceNumber++;
        }

        switch (e.LastOperation) {
            case SocketAsyncOperation.Send:
            case SocketAsyncOperation.SendPackets:
            case SocketAsyncOperation.SendTo:
                if (e.SocketError == SocketError.Success) {
                    this.OnDataSent(e);
                }
                break;
            case SocketAsyncOperation.Receive:
            case SocketAsyncOperation.ReceiveFrom:
            case SocketAsyncOperation.ReceiveMessageFrom:
                if ((e.BytesTransferred > 0) && (e.SocketError == SocketError.Success)) {
                    this.BeginReceive(e.Socket);
                    if (this.ReceiveTimeout > 0) {
                        this.SetReceiveTimeout(e.Socket);
                    }
                } else {
                    closed = true;
                }

                if (e.SocketError == SocketError.Success) {
                    this.OnDataReceived(e);
                }
                break;
            case SocketAsyncOperation.Disconnect:
                closed = true;
                break;
            case SocketAsyncOperation.Accept:
            case SocketAsyncOperation.Connect:
            case SocketAsyncOperation.None:
                break;
        }

        if (closed) {
            this.HandleSocketClosed(e.Socket);
        }

        SocketBufferPool.Instance.Free(e);
    }

The above code is contained in a TcpSocket class that will raise DataReceived & DataSent events. One thing to notice is the case SocketAsyncOperation.ReceiveMessageFrom: block; if the socket hasn't had an error it immediately starts another BeginReceive() which will allocate another SocketEventArgs from the pool.
Another important note is the SocketEventArgs SequenceNumber property set in the HandleIOComplete method. Although async requests will complete in the order queued, you are still subject to other thread race conditions. Since the code calls BeginReceive before raising the DataReceived event there is a possibility that the thread servicing the orginal IOCP will block after calling BeginReceive but before rasing the event while the second async receive completes on a new thread which raises the DataReceived event first. Although this is a fairly rare edge case it can occur and the SequenceNumber property gives the consuming app the ability to ensure that data is processed in the correct order.
One other area to be aware of is async sends. Oftentimes, async send requests will complete synchronously (SendAsync will return false if the call completed synchronously) and can severely degrade performance. The additional overhead of of the async call coming back on an IOCP can in practice cause worse performance than simply using the synchronous call. The async call requires two kernel calls and a heap allocation while the synchronous call happens on the stack.
Hope this helps,
  Bill

A: In your code, you do this:
if (!socket.ReceiveAsync(e.AsyncEventArgs)) {
  this.HandleIOCompleted(null, e);
}

But it is an error to do that. There is a reason why the callback is not invoked when it finishes synchronously, such action can fill up the stack.
Imagine that each ReceiveAsync is always returning synchronously. If your HandleIOCompleted was in a while, you could process the result that returned synchronously at the same stack level. If it didn't return synchronously, you break the while.
But, by doing the you you do, you end-up creating a new item in the stack... so if you have bad luck enough, you will cause stack overflow exceptions.


text:
Q: Will SQL Server "int" datatype reliably truncate (and not round) decimal values when they are input? I have a user with software that sometimes sends back a UNIT's ID as an integer(ex. 1000), and sometimes with a small decimal value appended (ex. 1000.001).  The software automatically generates MSSQL (2016 SP1) tables with "real" datatypes, and to "top it off" makes this UNIT columns part of a Primary Key.  This causes issues on the data input side and the reporting side.
I realize this is really a "bug" with the software, but I'm trying to be helpful on the DB side.  I have proven in a Sandbox region that I can change the "real" datatype to an "int", that this does not cause data loss with existing data, and every input scenario shows that the decimal values of any input will be truncated in the "int" column(not rounded).
My questions are, "Will SQL Server always reliably truncate decimal values when input into an "int" datatype (We do not have a way to dig into the Packaged App and force it to ROUND)?  Are there any scenarios where this will error, or cause issues?"  I can't find this documentation anywhere.

A: The Microsoft Docs page for the float and real data types, says this:

Values of float are truncated when they are converted to any integer type.

In addition the CAST and CONVERT (Transact-SQL) page says:

When you convert data types that differ in decimal places, SQL Server will sometimes return a truncated result value, and at other times it will return a rounded value. This table shows the behavior.

I'd prefer to get the source software modified to not return floating point data, but short of that, if the data is not used by some process that would be life-threatening, then it looks like an implicit conversion to int should be safe.
I qualified it with "non-life-threatening" because it's possible there is some situation where the implicit conversion does not operate the way it is documented.  Take for instance, the details presented in the "Caution" section of the int Docs page.


text:
Q: Multiple accounts and "cross-pollination" detection? Multiple accounts on SO are merged if they share the same IP/OpenID/etc. However, is there a way to analyze upvotes statistics to detect "cross-pollination" of some accounts which regularly upvote each other? I.e. some new user spends most of the upvotes upvoting the answers of the other for some long period of time. Is there a tool do detect it?

A: Multiple accounts are not necessarily merged, and certainly not automatically. You are allowed to have multiple accounts as long as you do so responsibly and follow some basic ground rules.
Moderators will only manually merge user accounts if there is evidence that they are violating those ground rules, for example conspiring to commit vote fraud.
So yes, these "cross-pollenation" tools that you describe do exist, but they are only available to ♦ moderators because they are based on statistical information about voting and other patterns that we don't want to fall into the wrong hands.
And not all of them even require moderator intervention. For example, there is a process that runs every 24 hours to detect and automatically reverse instances of vote fraud.


text:
Q: How to insert Analytics events inside script tag I have a Wordpress site and I activated a WhatsApp chat plugin. I want to track when people click on that button, but I don't know hot to insert the:
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);

Inside the code of the plugin:
<!-- WhatsHelp.io widget -->
<script type="text/javascript">
    (function () {
        var options = {
            whatsapp: "+XXXXXXXXX", // WhatsApp number
            company_logo_url: "//example.com", // URL of company logo (png, jpg, gif)
            greeting_message: "xxxxx", // Text of greeting message
            call_to_action: "xxxxx", // Call to action
            position: "right", // Position may be 'right' or 'left'
        };
        var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
        var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
        s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
        var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
    })();
</script>
<!-- /WhatsHelp.io widget -->

I tried putting this line:
s.onclick = function () { ga('send', 'event', 'WhatsApp', 'whatsappclick'); };

But doesn't works.
Thanks!

A: Here s is creating the script tag not the button which is the reason your code is not working.
A small hack can be done here because the class of the whatsapp button is fixed and unique.
Put this inside the s.onload function. The only requirement here is that you load your ga script before this script.
var whatsapp_button = document.getElementsByClassName("wh-widget-button wh-widget-button-activator");
whatsapp_button[0].onclick = function () { ga('send', 'event', 'WhatsApp', 'whatsappclick'); };


text:
Q: Can I express $\sqrt{x}$ as $Q(x)$ where Q(x) is a first degree polynomial? Can I express $\sqrt{x}$ as $Q(x)$ where $Q(x)$ is a first degree polynomial?

A: No polynomial of any degree. To expand on @Jose Garcia's comment, for every $x\geqslant0$,
$$\sqrt{x}=1+\cfrac{x-1}{2+\cfrac{x-1}{2+\cfrac{x-1}{2+\cdots}}}$$


text:
Q: Unable to connect to GitHub within Eclipse due to SunCertPathBuilderException: certificate not found I have setup my mac with Eclipse EE Luna and all seem to work fine (coming from Windows).
I installed EGit and the Github (Mylin) plugin.
However, I can't seem to clone a github project in Eclipse.
When using the eclipse import through EGit (not the gitHub plugin), and fill in the Https uri (of any opensource github project), Egit complaints it can't connect and shows a bullet list with possible causes like Uri incorrect, etc..
When using the Eclipse Github plugin to import a github project and let the plugin search I get the famous trusted certification error:
Error searching repositories: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Strange... I have a default java 8 installation.
I even added the github pub cert to the jssecert file in the sdk/jre/lib, but had no effect.
I have no proxy enabled, neither in Eclipse or system.
I am able to clone a repo through the git command "git clone [https repo uri]".
How to solve this?

A:
This should be a comment, but for some stupid reason i need to have a
  reputation to make a comment...

Same problem here.
My git server have a self-signed certificate.
The certificate name (CN) have the same name as the hostname i use to connect to it.
I had put the configuration property "http.sslVerify=false" in .gitconfig.
When i try to clone (using https), Eclipse connects to the repository, gets the repository information, shows the "master" branch, starts to clone (it shows the progress bar), receive the objects, but throws an Exception at the end (exception below), and didn't clone the repository (see the images below).
There is probably a bug here, since it can read the repository to get its information and files, but cannot finish the whole process.
Environment:
eclipse.buildId=4.5.0.I20150320-0800
java.version=1.8.0_25
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=pt_BR
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

Exception:
org.eclipse.core.runtime.CoreException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.eclipse.egit.core.op.ConfigureGerritAfterCloneTask.execute(ConfigureGerritAfterCloneTask.java:89)
    at org.eclipse.egit.core.op.CloneOperation.run(CloneOperation.java:161)
    at org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard.executeCloneOperation(AbstractGitCloneWizard.java:442)
    at org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard.access$2(AbstractGitCloneWizard.java:435)
    at org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard$5.run(AbstractGitCloneWizard.java:396)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1471)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:936)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:871)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1511)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
    at org.eclipse.egit.core.op.ConfigureGerritAfterCloneTask.isGerrit(ConfigureGerritAfterCloneTask.java:138)
    at org.eclipse.egit.core.op.ConfigureGerritAfterCloneTask.execute(ConfigureGerritAfterCloneTask.java:83)
    ... 5 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1453)
    ... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
    ... 26 more

A: Try updating your JDK.
I use jdk1.8.0_121. Just setting the configuration property http.sslVerify=false in .gitconfig is enough.
Best.


text:
Q: How to modify registry value using command prompt?(reg_binary type) I want to create a automatic registry update program using command prompt.
I tried several steps, most methods were to update Boolean values. But i want to update a REG_BINARY value.
Help needed !

A: If you're writing a batch script, the usual method is to import a prepared .reg file:
reg import myupdates.reg

You can create the files by hand, or just by exporting the correct values via Regedit and deleting unnecessary parts (with a text editor).


text:
Q: android UI Test with Espresso java.lang.NoClassDefFoundError: I do UITest with Espresso, and test login function in LoginActivity.java .
when running LoginScreenTest.java ,some exception got,the follow is exception message. I don't konw why LoginPresenter can be found but LoadIdlingResource cannot be found ,why and how to do.thanks very much!!!
the following is exception message.
java.lang.NoClassDefFoundError: bz/sunlight/soubei/util/LoadIdlingResource
atbz.sunlight.soubei.login.view.activity.LoginActivity.getCountingIdlingResource(LoginActivity.java:149)
at bz.sunlight.soubei.login.LoginScreenTest.setUp(LoginScreenTest.java:46)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:270)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1739)
Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
at dalvik.system.DexFile.defineClass(Native Method)
at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:211)
at dalvik.system.DexPathList.findClass(DexPathList.java:313)
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:51)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
... 34 more

there are code :
@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginScreenTest {
    public LoginPresenter loginPresenter;
    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule(LoginActiv`enter herecode `ity.class);

    @Before
    public void setUp() throws Exception {
        loginPresenter = new LoginPresenter(mActivityRule.getActivity(), mActivityRule.getActivity());
        Espresso.registerIdlingResources(mActivityRule.getActivity().getCountingIdlingResource());

    }
}

public class LoginActivity extends BaseActivity {
    private LoginPresenter loginPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        loginPresenter = new LoginPresenter(this, this);
        loginPresenter.showLastUserName();
    }
    @VisibleForTesting
    public IdlingResource getCountingIdlingResource() {

        LoadIdlingResource loadIdlingResource = new LoadIdlingResource(this);
        return loadIdlingResource;
    }
}


text:
Q: Require ForceTouch iOS App Is there a way to write an app's "Required device capabilities" such that the app runs only iPhone 6s and above (due to a requirement of force touch)?

A: You normally use the UIRequiredDeviceCapabilities key, which can require certain features to be present. However at this time it doesn't seem like 3D Touch has been added.
A large warning will have to suffice for now, while waiting for apple to add 3D touch as a thing you can require. Otherwise there might be some features only the new iPhones models have, such as the arm chip, you could require. I haven't looked into this though.
On apples page for documentation you can see available keys for the UIRequiredDeviceCapabilities, where 3D Touch doesn't seem to be present.
open https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html#//apple_ref/doc/uid/TP40009252-SW3

A: No, at this time it is not possible.
It is likely that Apple will introduce a new value to use with the UIRequiredDeviceCapabilities key.
Until that time, the best you can do is require one of (arm64, metal or opengles-3), and one of something like telephony or sms (until iPads get 3D Touch). This will at least restrict your app to the iPhone 5S and up.
And put a notice in the app description that your device requires 3D Touch.
Keep an eye on this document for all the possible device capability values:
https://developer.apple.com/library/ios/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/DeviceCompatibilityMatrix/DeviceCompatibilityMatrix.html
Also, this is handy:
http://28byteslater.com/ios-compatibility/?exclude=&require=22,7,19,26#chart


text:
Q: How to connect to SQLite3 database server? I understand that SQLite3 does not operate under the client-server database application model, so I was wondering how one would actually connect to a "running" database server with a SQLite3 back.
Meaning if I were to have a database server running on Linux with a SQLite3 back, how would clients connect to this server? Would I have to use another RDBMS?
Thanks,
Jake

A: You don't have any database server running SQLlite3. You can just have applications using SQLlite3 (there is no client - server protocol involved). The data is in some files accessed by the libsqlite3 library linked inside the application. (so the data is local to the system running that application).
So by definition you cannot connect to a SQLlite3 database server. Such thing don't exist.
Read the http://www.sqlite.org/ front-page, which starts with

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

And the wikipage sqllite
If you want to have a database server (with external, possibly remote, applications interacting thru a client-server protocol with it) switch to PostGreSQL, MariaDB, etc...

A: Clients that connect to SQLite "server" just use API that looks like connection. Library for "connection" is embedded into application.


text:
Q: How to get the call waiting state of a new incoming call during a phone conversation? Based on my requirement i need to track all incoming phone calls.
i successfully track the incoming and missed calls through broad cast receivers.
But i didn't get the call waiting state.In that state i missed to track the both incoming numbers.
If any one how to get waiting call state ,please reply me.
thanq

A: The actual implementation depends on the specific case, but the answer is: use PhoneStateListener and TelephonyManager in a background thread.


text:
Q: Theory/Logic behind integration Let's suppose we have a curve $y = x^2$
Now when we take two points on the curve, we aren't completely sure how to connect them(will elaborate more later), compared to two points on a straight line which we are sure how to connect(shortest distance).
My argument is that the only way we know how to connect two points (precisely) is by marking the shortest distance between them (please do tell if I'm wrong here and for the sake of the question do assume this for a second) now, to connect two points on the curve we need more points between the two original points and then connect all of those points by marking the shortest distance between them. But then the same initial argument applies to any two adjacent points - that we aren't sure how to connect them again (compared to a straight line). So now we need to consider something like infinity too - basically keep increasing the resolution of the points on the curve to a non finite degree to connect the points and form the curve precisely.
Now comes my question - in this backdrop, how is it that by integrating we can find the precise value of the area under the curve?, since we were unable to form the curve in the first place precisely unless by using the concept of infinity.
Is there any literature which explains my question simply?

A: Yes, there is an error. If you are talking about a curve like $x^2$, the error in measurement of area is proportional to h say. where h is the gap between 2 consecutive divisions you are splitting your curve to assume them to be rectangles.
Now since you are saying I'll reduce the gap between the lines to a value as close to 0 as possible, the error (since proportional) also reduces to a value as close to 0 as possible.
Recall that 10+h as Limit $h\to 0$ is $10$.

A: In real analysis the integral is usually defined using Darboux sums.
You define partition of the interval and then you let n go to infinity.
Then the sum of the (signed) areas of the rectangles (as n goes to infinity)
is defined/said to be the integral (the value of integral).
Check this e.g.
Darboux Integral

A: About 50 years ago a calculus instructor told us there is no direct connection between the summation series and the integral. The summation method has been used since antiquity to determine the area of the circle. I have written compter programs to do the summations, but at the end of the day it is still a guestimate. Fundamentally the best way to see this is to approach it as a ranging problem. For simplicity consider only the rising part of the curve. Reverse the process where the curve falls. If you sum the area where the left side of the rectangles touch the rising curve the summation will be understated. If you sum the area where the right side of the rectangles touch the rising curve that summation will be overstated. The limit lives somewhere between. As the width of the rectangles is decreased the difference between the overstated and understated sumations approach the limit. If you write a program to do this you can watch the limit begin to appear. BUT most computers will exceed their ability to compute fractional numbers as the rectangular slices approach zero. If you let the slice width go to 0.00001 you can probably get to within 3 units of the area limit. BUT here is the kicker: This has nothing to do with the integral, other than someone discovered that integrating the equation of a curve gives you that limit number. There is no magic connection to the summation, other than it works well enough that we have not yet discovered a significant number of places where it does not. The integration process serves as an analog of the infinite summation, but it is not otherwise related. The integral is an analog of the maximum extent, aka the limit, of the area under the curve. Taking the integral of the equation representing the long side of a triangle results in the area which is proven by calculation((base x height)/2). The same summation method can be used to approach the limit of the area under the long side of the triangle, with similar results. So taking the integral of a line equation results in the area, whether the line is straight or a curve.


text:
Q: PostgreSQL 11: how to partition 1000 tenants Setup
We have a multi-tenant app that has about 1000 customers more or less. When a customer churns we delete all their data after a period. We have a few tables that are pretty big and we're considering using partitioning to split them per customer.
Problem
1000 tenants (customers) are a lot of partitions - is it reasonable to do this on PostgreSQL?
More details
Currently, the separation between our tenants is via an account_id column on all tables in the DB. There are a few tables that are pretty big. For example, there is an event table (the one I'm interested in partitioning) that contains audit logs and other events for everything that happens in our app.
Here are a few facts about the event table:

*

*It contains about 300M rows + a few of composite/partial indexes.

*The count of events by account_id is very uneven, 5% accounts have 50% of the data.

*There is a timestamp field and a few others (JSONB, author_id, etc..)

*Write operations: inserts mostly and deletes (per account_id). Deletes can potentially be millions of rows. No updates. Deletes of big accounts are rare and not a big performance issue at the moment.

*Selects are either for a specific event (by account_id + id) or all events in a given period of time. Period of time is not always set. account_id is always present in the query.

Possible solutions
Partionining by account_id:
Pros:

*

*Deletes will be fast because of DROP TABLE.

*Queries should also be pretty decent since all queries contains WHERE account_id = 123
Cons:

*

*Are 1000 partitions too much for Postgres?

*Uneven distribution of events per account creating a few super big partitions and a few small ones.

Partitioning by timestamp:
Pros:

*

*Recent data is usually mostly accessed and will make queries with a timestamp faster.

*More predictable/even distribution of events.

Cons:

*

*Deletion of a single account might touch a lot of partitions - not a big concern.

*Always needs to contain a filter by timestamp - which is not always possible.

A: Partitioning is mostly about speeding up deletes and sequential scans.

*

*If your biggest pain is the big deletes by account_id, list partitioning on that column would be the best solution.

*If your biggest pain is getting rid of all data older than a certain date, range partitioning by time would be the solution.

*If you have may queries that have to perform sequential scans of large tables, but have a WHERE condition on account_id or a time constraint, partitioning on that WHERE condition would allow PostgreSQL to perform the sequential scan only on some of the partitions.
You have to decide if any of these things is painful enough for you to consider partitioning. Partitioning doesn't come for free: it will increase query planning time and sometimes execution time as well.
Partitioning won't make index scans faster, often the opposite is the case. Only partition if you expect a real benefit from it.
1000 partitions is almost too many to be efficient. You might consider having separate partitions for the bigger accounts and bundling the rest, perhaps using a default partition.


text:
Q: How can I let a footnote continue on the next page? I have a rather long footnote which breaks a listing in two parts, unnecessarily.  Since the listing is more important then the footnote I'd rather lake to have the footnote split.

*

*Can I customize (one or all) footnotes to have a maximal length before they are continued on the next page?

*Or can I manually split a footnote in two to get the effect?

A: For consistency across pages, the bigfoot package might be preferred to changing \interfootnotelinepenalty.

A: Meddling with \interfootnotelinepenalty (except setting it to infinite values) does not actually help with the layout of footnotes when using standard LaTeX.  The reason is that TeX takes the next feasible breakpoint after the footnote anchor, and uses that for splitting the footnote.  And it does not reconsider the footnote split for other breakpoints, though if the footnote split leaves the page quite too short, it might still pull in further lines from the main text.  So an infinite penalty might change things, but rarely to the better.  You probably can make do by combining it with a manually placed \pagebreak in the footnote.
Or you use bigfoot.  bigfoot indeed plays through all combinations of breakpoints and penalties, so you can work with noninfinite penalties and get a reasonably balanced result by choosing your penalties such that a break in the listing is penalized harder than in the footnote.

A: Actually, you can indeed "customize (one or all) footnotes to have a maximal length before they are continued on the next page" by saying something like
\global\dimen\footins = 8cm

A: There is a parameter \interfootnotelinepenalty, which is 100 in LaTeX.  Setting it to zero (\interfootnotelinepenalty=0) or even to a negative value before the offending footnote helps to split it.  Then you can set it back to 100 if you wish.
It is difficult to give a more detailed answer without an MWE.


text:
Q: On what SE site should I post a Chrome (browser) usability question? I'd like to ask a question about how to use Chrome profiles/persons.
On what SE site should I post such a question?

A: Super User looks like the right fit in general.
If you're on Mac, Ask Different is an option, as is Ask Ubuntu if you're on that platform. (Although Super User is ok for those too.)
If you're using Chrome on Android, ask over at Android Enthusiasts.
Web Apps doesn't fit, it is for using web applications, not the browser you're viewing them from.


text:
Q: How to know height of softkeyboard
Possible Duplicate:
Get the height of virtual keyboard in Android

If I click on EditText I am getting soft keyboard. I need to know height of default soft keyboard. I didnt find any standard method to get height of soft keyboard. How to know height of soft keyboard on Android?


text:
Q: Javascript error on href getElementById when null I have a popup that lets the user change a href if set or not. If not set, I display "optional web link" as field title. However, I'm getting a JavaScript error on the "if" line that href is null. How can I get href or test it without the error getting in the way? In this application href will be null at times so I need my script to deal with it somehow.
if (document.getElementById('sidebarhref-'+id).href == '') {
    var href = document.getElementById('sidebarhref-'+id).href;
} else {
    var href = 'optional web link';
}

A: Test if the return value of getElementById is a true value before trying to access properties of it.
var element = document.getElementById('sidebarhref-'+id);
if (element && element.href === "") {
// etc


text:
Q: Elixir / Phoenix - Run code at the very beginning of a test run, shared data for ALL tests I'd like to run a block of code right at the beginning of my test suite (that inserts data into the database!), and persists across the entirety of the test suite.
Is something like this possible?
I tried running the code in a setup_all block, but:
A) I was getting failures trying to insert into the database here;
B) This would only be shared between that test module, whereas I'd like it to be shared across all tests.
Thanks for your help!

A: Run once before starting tests
Just put the common code in your test/test_helper.exs:
ExUnit.start()

# Common Code
ModuleOne.some_method
ModuleTwo.other_method(args) # etc

Run before every test
Assuming you have already worked out cleaning up the db and running migrations between tests, you can put something like this in your test/test_helper.exs:
defmodule TestProject.Helpers do
  def setup do
    # Common Code
  end
end

And use this setup block in all of your tests:
setup do
  TestProject.Helpers.setup
end

Setting up a Test Database / Schema
If you also need to set up a fake Database, Schema and Migrations for your tests, you'll need to define them as well, and put this in your test_helper (assuming here that the driver you are using is Postgrex):
# Start Ecto
{:ok, _} = Ecto.Adapters.Postgres.ensure_all_started(TestProject.Repo, :temporary)
_        = Ecto.Adapters.Postgres.storage_down(TestProject.Repo.config)
:ok      = Ecto.Adapters.Postgres.storage_up(TestProject.Repo.config)
{:ok, _} = TestProject.Repo.start_link

For a more detailed example, you can see my Ecto.Rut package that creates a fake database (for the test env only), and resets it before running each test.


text:
Q: jQuery conditional if not in loop How can I add a conditional to the end of a For loop?
Example:
if (state) {
    for (var i = 0, l = $imageLength; i < l; i++) {
        if ($images[i].url === state) {
            rGallery.init(i);
            break;
        }
    }

    /* Need to add here: if NOT in loop... blah*/

} else {
    rGallery.init();
}

Side note, could also improve the logic to avoid it... if (state has a match in the loop) init(i) else init()

A: What about using a boolean variable :
var hasMatch = false;
if (state){
    for (var i = 0, l = $imageLength; i < l; i++){
        if ($images[i].url === state){
            rGallery.init(i);
            hasMatch = true;
            break;
        }
    }
}
if(!hasMatch){
    rGallery.init();
}

A: You could use another variable as a flag and check it after the loop:
var found = false;
if (state){
    for (var i = 0, l = $imageLength; i < l; i++){
        if ($images[i].url === state){
            rGallery.init(i);
            found = true;
            break;
        }
    }
}

if (!found){
    rGallery.init();
}

A: You can set a flag if the result is found in the loop or not:
var found = false;
for (var i = 0, l = $imageLength; i < l; i++){

    if ($images[i].url === state){

        rGallery.init(i);
        fount = true;
        break;
    }
}
if (!found) {
    /* Need to add here: if NOT in loop... blah*/
}


text:
Q: $L^p$-norm of the gradient of a harmonic function. Let $1<p<\infty$, $\Omega \subsetneq U \subset \mathbb{R}^n$ be bounded open sets in $\mathbb{R}^n$ with smooth boundary. The claim is that there is $c>0$ such that the following inequality holds
$$ \| \nabla u \|_{L^p(\Omega^\prime)} \leq c \| u \|_{L^p(U)}$$
for all $u \in L^p(U)$ with $u$ being a weak solution of $\Delta u = 0$,
I believe that it can be proved by the mean value property of harmonic functions that such a $u$ is actually smooth and so $\nabla u$ is defined in the usual sense. My question is how can we prove this inequality? The proof I'm reading just states that applying the mean value property to $\nabla u$ and so the $c$ exists. Also, I'm kind of suspicious of for the case $p \in (1,2)$ because I feel we might need to apply Jensen's inequality to $\frac{p}{2}$ somehow.

A: In what follows, I assume that $\Omega \Subset U$. Fix $r>0$ small enough so that $B(x,r) \subseteq U$ for any $x \in \Omega$.
Assuming that we already know the mean value property holds for $\nabla u$, for $x \in \Omega$ we have
\begin{align*}
\nabla u(x) & = \frac{1}{|B(x,r)|} \int_{B(x,r)} \nabla u(y) dy \\
& = \frac{1}{|B(x,r)|} \int_{\partial B(x,r)} u(y) \vec{n}(y) dy \\
& = \frac{n}{r} \cdot \frac{1}{|\partial B(x,r)|} \int_{\partial B(x,r)} u(y) \vec{n}(y) dy
\end{align*}
by Gauss formula. Now we apply Jensen's inequality to obtain
\begin{align*}
|\nabla u(x)|^p
& \leqslant \frac{n^p}{r^p} \cdot \frac{1}{|\partial B(x,r)|} \int_{\partial B(x,r)} |u(y)|^p dy \\
& = C(n,r) \int_{\partial B(0,r)} |u(x+y)|^p dy.
\end{align*}
Integrating over $x \in \Omega$, changing the order of integration and substituting $z = x+y$ yields
\begin{align*}
\int_{\Omega '} |\nabla u(x)|^p dx
& \leqslant C(n,r) \int_{\partial B(0,r)} \int_{\Omega} |u(x+y)|^p dx dy \\
& \leqslant C(n,r) \int_{\partial B(0,r)} \int_{U} |u(z)|^p dz dy \\
& = C(n,r) \int_{U} |u(z)|^p dz.
\end{align*}


text:
Q: NHibernate Insert into ... select ... with GUID as PrimaryKey I try to do fallowing with NHibernate:
this.Session.CreateQuery(@"insert into ContactGroupContact (Id, MailAddress, Company, Person, Branch, ContactGroup, User, FaxNumber)
                             select newid(), MailAddress, Company, Person, Branch,
                                    :destContactGroupId, User, FaxNumber
                             from ContactGroupContact cgc
                             where cgc.ContactGroup.Id = :contactGroupId")
        .SetEntity("destContactGroupId", tempContactGroup)
        .SetGuid("contactGroupId", contactGroupId)
        .ExecuteUpdate();

The column Id of ContactGroupContact is of type GUID.
When I execute this, I get a NHibernate.QueryException with the following message:

No data type for node: MethodNode ( ( newid exprList ) [insert into
  ContactGroupContact (Id, MailAddress, Company, Person, Branch,
  ContactGroup, User, FaxNumber)
   select newid(), MailAddress, Company, Person, Branch, :destContactGroupId, User, FaxNumber
   from ContactGroupContact cgc
   where cgc.ContactGroup.Id = :contactGroupId]

Can someone help me, what is going wrong? - Thanks.

A: Try creating a derived Dialect and registering newid as a function.

A: Here is an example of Diego's suggestion. I admit I am new to this, but assuming this is the appropriate way to handle it (it works)
public class DerivedDialectWithNewId : MsSql2005Dialect
{
    public DerivedDialectWithNewId()
    {
        RegisterFunction("newid", new NoArgSQLFunction("newid", NHibernateUtil.Guid, true));
    }
}

and here is how to use it with Fluent NHibernate
private static FluentConfiguration GetConfiguration()
    {
        return Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2005.ConnectionString(
                    c => c.FromConnectionStringWithKey("CustomConnectionString"))
                    .Dialect<DerivedDialectWithNewId>()));
    }


text:
Q: Is it possible to adjust the height of a container to the height of its child element that has position absolute? I have a web page with a search field in it, like so:

When the user starts typing in the search field, the autocomplete list will appear. To prevent it from ruining the layout of the page, it has the position attribute set to absolute. The trouble is, when there is little content on the page and when the screen size is rather small, the autocomplete list will spread down below the bottom border of the html element (and therefore below the footer), like so:

I understand that the whole purpose of position: absolute is to make an element independent of the flow of other elements, but is there a way to adjust the height of the container element to the height of its child element that has position: absolute using CSS? If not, what other technique would you recommend?

A: Assumptions:
footer height: 60px;
footer div id="footer";
background behind footer as the window (instead of it all being inside a specific division);
If you have JQuery:
//Replace 120 below with the height of your footer + padding + how far the search bar is from the top of your screen
var height = ($(window).height() - 120);
$('#footer').css({"height", height});

make it look a bit better by replacing the above adjustment with...
$('#footer').stop().animate({height: height});

A: I guess you mean behind the footer.
If so, you can use css z-index property to bring your autocomplete list in front of the footer element.

A: For this using
Overflow-y:scroll
max-height:200px
position:absolute
z-index:2

A: html {
    overflow: auto;
}

body {
    overflow: hidden;
}

.autocomplete-list {
     margin-bottom: [height of footer]
}

If the list exceeds the height of your body, then there is something wrong with your css.
The above css wont let anything goes outside the body and if it does, then you will get and scroll bar.
And the margin-bottom of the autocomplete-list keeps it above the footer


text:
Q: Android XML ScrollView not scrolling I am trying to implement a scrollview in one of my XML files but it doesnt seem to be working. It is cutting out the bottom 3 spinners and the last button in the XML. I guessed this is because I needed to scroll down to see them but I am unable to scroll?
Can anyone seem the issue?
XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
    android:id="@+id/title"
    android:text="New Recipe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"/>

<EditText
    android:id="@+id/recipeName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/title"
    android:hint="Enter Recipe Name"/>

<ListView
    android:id="@+id/ingredientsList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/recipeName"
    android:textColor="#000000"
    android:layout_above="@+id/showIngredientDialog"
    android:minHeight="150px">
</ListView>

<Button
    android:id="@+id/showIngredientDialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Ingredient"
    android:layout_above="@+id/showDirectionDialog"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="145dp" />

<ListView
    android:id="@+id/directionsList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:layout_above="@+id/showDirectionDialog"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="37dp">
</ListView>

<Button
    android:id="@+id/showDirectionDialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Direction"
    android:layout_marginBottom="79dp"
    android:layout_alignParentBottom="true"
    android:layout_alignEnd="@+id/showIngredientDialog" />

<Spinner
    android:id="@+id/timeSpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/showDirectionDialog"
    android:entries="@array/time"/>

<Spinner
    android:id="@+id/dietarySpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/dietary"
    android:layout_below="@+id/showDirectionDialog"
    android:layout_toRightOf="@+id/timeSpinner" />

<Spinner
    android:id="@+id/heatSpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/heat"
    android:layout_below="@+id/showDirectionDialog"
    android:layout_toRightOf="@+id/dietarySpinner" />

<Button
    android:id="@+id/saveRecipe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save Recipe"
    android:layout_below="@+id/timeSpinner"
    android:layout_alignParentBottom="true"
    android:layout_alignEnd="@+id/showDirectionDialog"
    android:layout_marginBottom="25dp" />

</RelativeLayout>
</ScrollView>

A: Set the relativeLayout height to "wrap_content".

A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/title"
    android:text="New Recipe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"/>

<EditText
    android:id="@+id/recipeName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/title"
    android:hint="Enter Recipe Name"/>

<ListView
    android:id="@+id/ingredientsList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/recipeName"
    android:textColor="#000000"
    android:layout_above="@+id/showIngredientDialog"
    android:minHeight="150px">
</ListView>

<Button
    android:id="@+id/showIngredientDialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Ingredient"
    android:layout_above="@+id/showDirectionDialog"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="145dp" />

<ListView
    android:id="@+id/directionsList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:layout_above="@+id/showDirectionDialog"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="37dp">
</ListView>

<Button
    android:id="@+id/showDirectionDialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Direction"
    android:layout_marginBottom="79dp"
    android:layout_alignParentBottom="true"
    android:layout_alignEnd="@+id/showIngredientDialog" />

<Spinner
    android:id="@+id/timeSpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/showDirectionDialog"
    android:entries="@array/time"/>

<Spinner
    android:id="@+id/dietarySpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/dietary"
    android:layout_below="@+id/showDirectionDialog"
    android:layout_toRightOf="@+id/timeSpinner" />

<Spinner
    android:id="@+id/heatSpinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/heat"
    android:layout_below="@+id/showDirectionDialog"
    android:layout_toRightOf="@+id/dietarySpinner" />

<Button
    android:id="@+id/saveRecipe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save Recipe"
    android:layout_below="@+id/timeSpinner"
    android:layout_alignParentBottom="true"
    android:layout_alignEnd="@+id/showDirectionDialog"
    android:layout_marginBottom="25dp" />

</RelativeLayout>
</ScrollView>
</RelativeLayout>

A: Your facing this issue because you are using ScrollView in which having ListView. Both having default scroll property which conflicting the issue. Check this SO post for resolving the issue.

A: you can't put two scrolling widgets inside one another the will cause major issues even with normal scrolling
if there is no way to change this layout design please force a height to each listview but still the scroll will be buggy and you have to set extra margin on the side of list for the user to be able to scroll the parent scroll view
or try to break down the design if you can maybe tabs one for normal data and a tab for each list

A: Because views of total heigt not bigger than screen height.
You can see with coding custom height. I hope below code help you.
I just change listview height.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:text="New Recipe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"/>

    <EditText
        android:id="@+id/recipeName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:hint="Enter Recipe Name"/>

    <ListView
        android:id="@+id/ingredientsList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/recipeName"
        android:textColor="#000000"
        android:layout_above="@+id/showIngredientDialog"
        android:minHeight="150px">
    </ListView>

    <Button
        android:id="@+id/showIngredientDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Ingredient"
        android:layout_above="@+id/showDirectionDialog"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="145dp" />

    <ListView
        android:id="@+id/directionsList"
        android:layout_width="fill_parent"
        android:layout_height="1000dp"
        android:textColor="#000000"
        android:layout_above="@+id/showDirectionDialog"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="37dp">
    </ListView>

    <Button
        android:id="@+id/showDirectionDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Direction"
        android:layout_marginBottom="79dp"
        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/showIngredientDialog" />

    <Spinner
        android:id="@+id/timeSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/showDirectionDialog"
        />

    <Spinner
        android:id="@+id/dietarySpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_below="@+id/showDirectionDialog"
        android:layout_toRightOf="@+id/timeSpinner" />

    <Spinner
        android:id="@+id/heatSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_below="@+id/showDirectionDialog"
        android:layout_toRightOf="@+id/dietarySpinner" />

    <Button
        android:id="@+id/saveRecipe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Recipe"
        android:layout_below="@+id/timeSpinner"
        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/showDirectionDialog"
        android:layout_marginBottom="25dp" />

</RelativeLayout>


text:
Q: How do I get an old version of Meteor? I deployed my app on my own server using Meteor v0.4.2 (I'm not sure that's the exact version number, but it's the latest pre-0.5.0).
Then, I made the mistake of upgrading to Meteor 0.5.2 locally and now don't know how to get 0.4.2 back in order to deploy to the server.
I tried deploying with version 0.5.2 but there's a strange bug that rears its head on the server.

A: You can run Meteor directly from a git checkout, so it should be possible to clone from the meteor trunk, then checkout the 0.4.2 tag and run meteor that way.
Steps to do this are outlined in the readme at the root of the repo.


text:
Q: How to edit restriction on rows that are already defined and filled in mysql I have a table name temp and in it I have column x with datatype INT.
mysql> desc temp;
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| x     | int  | YES  |     | NULL    |       |
+-------+------+------+-----+---------+-------+

As shown below I have inserted value in the column.
mysql> select * from temp;
+------+
| x    |
+------+
|   10 |
+------+

Is it possible to set restriction on already defined column x such that it only takes integers with value less than 10.
Note: I do not intend to create a new column but rather add restriction on already created column

A:
Is it possible to set restriction on already defined column x such that it only takes integers with value less than 10.

Yes. In my opinion you could create a trigger to  set restriction (x < 10 in your case). This worked for me:
CREATE TRIGGER check_trigger
  BEFORE INSERT
  ON tmp
  FOR EACH ROW
BEGIN
  IF NEW.x >= 10 THEN
    CALL `Error: Wrong values for field x. x must be less than 10`; -- this trick will throw an error
  END IF;
END ;

With this trigger I got error when trying to create a record with x = 11
image for more details
You may want to create one more trigger for the update

A: Yes you can add constraint to a already defined and filled column. As @Akina has pointed out in comments that for adding restriction as CHECK constraint you need to update previously filled data to match the new constraint. This is done to ensure that the newly applied constraint do not fail.
After updating the data you can apply the CHECK constraint as follows:
ALTER TABLE temp
ADD CHECK (x <= 10);


text:
Q: Linux hosted subdomain under Windows hosted domain We currently have a website that is hosted on a Windows machine, since the website runs on .NET.
We are planning to build an Intranet portal in Drupal. Is this possible on a subdomain? Would I have to purchase a separate Linux hosting and point the subdomain there?

A: Is this possible on a subdomain?
Yes.
Would I have to purchase a separate Linux hosting and point the subdomain there?
Also yes if you plan to run Drupal on a linux (LAMP) server.
You have short questions I have short answers ;)

A: Of course you can run Drupal on windows hosting. Why not? Windows hosting support both ASP.NET and also PHP. :) You dont need to purchase Linux hosting anymore


text:
Q: Como puedo obtener los datos a través del id en mysql Como puedo hacer una consulta que a través del id me muestre todos los datos de la persona en mysql.
Quiero verificar que el id_emisor sea la persona que e ingresado en la tabla persona.
Hice este intento:
Select NOMBRES from altas where id_emisor = idPersona;

Y me bota errores, ya están relacionadas como foreign key.

A: select *
from personas , altas
where altas.ID_EMISOR = personas.ID_PERSONA

A: select * from personas p
inner join altas a on p.id_persona = a.id_emisor

A: en si deberías de llamar la FK de la tabla que relacionas igual, por convención, pero para darte una solución a tu consulta te da error porque no indicas a que tabla pertenece que campo en la query por eso al no saber de donde obtener los datos te da error, deberias hacer la query de la siguiente manera:
SELECT nombres FROM personas INNER JOIN altas ON personas.id_persona = altas.id_emisor;

suponiendo que cambies la estructura de la tabla y tengas una FK que se llame id_persona se puede simplificar aún más asi:
SELECT nombres FROM personas
JOIN altas USING(id_persona);

toma en cuenta que en ambas tablas debes tener el mismo campo con el mismo nombre, mismo tipo y misma longitud y obviamente su FK que los relacione, para que este ultimo ejemplo te funcione correctamente; espero te sirva...


text:
Q: C# DataGridView - Custom format for a specific column I'm currently retrieving data from a MySQL database and displaying them in a DataGridView. One of the columns is gender(int) with 1 signifying Male and 2 signifying Female. I want the DataGridView to display Male or Female instead of just 1 and 2.
Is it good practice to format the data ahead in the MySQL query? I'm thinking of adorning the retrieved data in DataGridView instead of changing the data retrieved. But let me hear your thoughts.

A: In the below sample, i created a column dynamically  and added to my data grid. Now once the data table is binding to the Grid, it will choose the correct values.
         try
            {
                dataGridView1.AutoGenerateColumns = false;

                //source for combo box
                var items = new Dictionary<string, int>();
                items.Add("Male", 1);
                items.Add("FeMale", 2);

                //new combobox column for the GRID
                DataGridViewComboBoxColumn gender = new DataGridViewComboBoxColumn();
                gender.DisplayMember = "Key";
                gender.ValueMember = "Value";
                gender.DataSource = new BindingSource(items, null);
                gender.HeaderText = "Gender";
                gender.DataPropertyName = "Gender";
                dataGridView1.Columns.Add(gender);

                //Data for the GRID
                DataTable dt = new DataTable();
                dt.Columns.Add("Gender", typeof(int));
                dt.Rows.Add(new object[] { 1 });
                dt.Rows.Add(new object[] { 2 });
                dt.Rows.Add(new object[] { 2 });
                dt.Rows.Add(new object[] { 2 });
                dt.Rows.Add(new object[] { 1 });
                dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

This give the below output

A: This is visual basic code. Not sure if it is good practice to format the data beforehand though..
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs) Handles
GridView1.RowDataBound

If e.Row.RowType = DataControlRowType.DataRow Then
Dim gender As String =
Convert.ToString(e.Row.Cells(columnnumber).Text).Trim()
If gender= "1" Then
e.Row.Cells(columnnumber).Text = "Male"
Else if gender="2" Then
e.Row.Cells(columnnumber).Text="Female"   `

End If
End Sub

fieldtype:
    asp:BoundField DataField="Zone"
Translated using : https://www.carlosag.net/tools/codetranslator/
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        string gender = Convert.ToString(e.Row.Cells[columnnumber].Text).Trim();
        if ((gender == "1")) {
            e.Row.Cells[columnnumber].Text = "Male";
        }
        else if ((gender == "2")) {
            e.Row.Cells[columnnumber].Text = "Female";
        }

    }

}

Hope this helps