text:
Q: Keras: NaN Training Loss After Introducing Batch Normalization The goal of the model is to categorically classify video sequences, where each input is a grayscale, 45-frame, 100x150 video sequence (1, 45, 100, 150), which corresponds to a one-hot encoded categorical output for one of 3 classes e.g. [0, 0, 1]. Here is the script used to train the model:
from keras import backend as K
from keras.callbacks import Callback
from keras.constraints import maxnorm
from keras.models import Sequential, load_model
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Convolution3D
from keras.layers.convolutional import MaxPooling3D
from keras.layers.normalization import BatchNormalization
from keras.optimizers import Nadam
from keras.preprocessing.image import random_rotation, random_shift, random_shear, random_zoom
from keras.regularizers import WeightRegularizer
from keras.utils import np_utils
from keras.utils.io_utils import HDF5Matrix
from pprint import pprint
from random import shuffle
from sklearn.utils import shuffle
K.set_image_dim_ordering("th")

import cv2
import h5py
import json
import os
import sys
import numpy as np

class OpticalSpeechRecognizer(object):
    def __init__(self, rows, columns, frames_per_sequence, samples_generated_per_sample, config_file, training_save_fn, osr_save_fn):
        self.rows = rows
        self.columns = columns
        self.frames_per_sequence = frames_per_sequence
        self.samples_generated_per_sample = samples_generated_per_sample
        self.config_file = config_file
        self.training_save_fn = training_save_fn
        self.osr_save_fn = osr_save_fn
        self.osr = None

    def save_osr_model(self):
        """ Save the OSR model to an HDF5 file
        """
        # delete file if it already exists
        try:
            print "Saved file \"{0}\" already exists! Overwriting previous saved file.\n".format(self.osr_save_fn)
            os.remove(self.osr_save_fn)
        except OSError:
            pass

        print "Saving OSR model to \"{0}\"".format(self.osr_save_fn)
        self.osr.save(self.osr_save_fn)

    def load_osr_model(self):
        """ Load the OSR model from an HDF5 file
        """
        print "Loading OSR model from \"{0}\"".format(self.osr_save_fn)
        self.osr = load_model(self.osr_save_fn)

    def train_osr_model(self):
        """ Train the optical speech recognizer
        """
        print "\nTraining OSR"
        validation_ratio = 0.3
        batch_size = 10
        training_sequence_generator = self.generate_training_sequences(batch_size=batch_size)
        validation_sequence_generator = self.generate_training_sequences(batch_size=batch_size, validation_ratio=validation_ratio)

        with h5py.File(self.training_save_fn, "r") as training_save_file:
            sample_count = training_save_file.attrs["sample_count"]
            pbi = ProgressDisplay()
            self.osr.fit_generator(generator=training_sequence_generator,
                                   validation_data=validation_sequence_generator,
                                   samples_per_epoch=sample_count,
                                   nb_val_samples=int(round(validation_ratio*sample_count)),
                                   nb_epoch=10,
                                   max_q_size=1,
                                   verbose=2,
                                   callbacks=[pbi],
                                   class_weight=None,
                                   nb_worker=1)

    def generate_training_sequences(self, batch_size, validation_ratio=0):
        """ Generates training sequences from HDF5 file on demand
        """
        while True:
            with h5py.File(self.training_save_fn, "r") as training_save_file:
                sample_count = int(training_save_file.attrs["sample_count"])
                sample_idxs = range(0, sample_count)
                shuffle(sample_idxs)
                training_sample_idxs = sample_idxs[0:int((1-validation_ratio)*sample_count)]
                validation_sample_idxs = sample_idxs[int((1-validation_ratio)*sample_count):]

                # generate sequences for validation
                if validation_ratio:
                    validation_sample_count = len(validation_sample_idxs)
                    batches = int(validation_sample_count/batch_size)
                    remainder_samples = validation_sample_count%batch_size
                    # generate batches of samples
                    for idx in xrange(0, batches):
                        X = training_save_file["X"][validation_sample_idxs[idx*batch_size:idx*batch_size+batch_size]]
                        Y = training_save_file["Y"][validation_sample_idxs[idx*batch_size:idx*batch_size+batch_size]]
                        yield (X, Y)
                    # send remainder samples as one batch, if there are any
                    if remainder_samples:
                        X = training_save_file["X"][validation_sample_idxs[-remainder_samples:]]
                        Y = training_save_file["Y"][validation_sample_idxs[-remainder_samples:]]
                        yield (X, Y)

                # generate sequences for training
                else:
                    training_sample_count = len(training_sample_idxs)
                    batches = int(training_sample_count/batch_size)
                    remainder_samples = training_sample_count%batch_size
                    # generate batches of samples
                    for idx in xrange(0, batches):
                        X = training_save_file["X"][training_sample_idxs[idx*batch_size:idx*batch_size+batch_size]]
                        Y = training_save_file["Y"][training_sample_idxs[idx*batch_size:idx*batch_size+batch_size]]
                        yield (X, Y)
                    # send remainder samples as one batch, if there are any
                    if remainder_samples:
                        X = training_save_file["X"][training_sample_idxs[-remainder_samples:]]
                        Y = training_save_file["Y"][training_sample_idxs[-remainder_samples:]]
                        yield (X, Y)

    def print_osr_summary(self):
        """ Prints a summary representation of the OSR model
        """
        print "\n*** MODEL SUMMARY ***"
        self.osr.summary()

    def generate_osr_model(self):
        """ Builds the optical speech recognizer model
        """
        print "".join(["\nGenerating OSR model\n",
                       "-"*40])
        with h5py.File(self.training_save_fn, "r") as training_save_file:
            class_count = len(training_save_file.attrs["training_classes"].split(","))

        osr = Sequential()
        print " - Adding convolution layers"
        osr.add(Convolution3D(nb_filter=32,
                              kernel_dim1=3,
                              kernel_dim2=3,
                              kernel_dim3=3,
                              border_mode="same",
                              input_shape=(1, self.frames_per_sequence, self.rows, self.columns),
                              activation="relu"))
        osr.add(MaxPooling3D(pool_size=(3, 3, 3)))
        osr.add(BatchNormalization())
        osr.add(Convolution3D(nb_filter=64,
                              kernel_dim1=3,
                              kernel_dim2=3,
                              kernel_dim3=3,
                              border_mode="same",
                              activation="relu"))
        osr.add(MaxPooling3D(pool_size=(3, 3, 3)))
        osr.add(BatchNormalization())
        osr.add(Convolution3D(nb_filter=128,
                              kernel_dim1=3,
                              kernel_dim2=3,
                              kernel_dim3=3,
                              border_mode="same",
                              activation="relu"))
        osr.add(MaxPooling3D(pool_size=(3, 3, 3)))
        osr.add(BatchNormalization())
        osr.add(Flatten())
        print " - Adding fully connected layers"
        osr.add(Dense(output_dim=128,
                      init="normal",
                      activation="relu"))
        osr.add(BatchNormalization())
        osr.add(Dense(output_dim=128,
                      init="normal",
                      activation="relu"))
        osr.add(BatchNormalization())
        osr.add(Dropout(0.5))
        osr.add(Dense(output_dim=class_count,
                      init="normal",
                      activation="softmax"))
        print " - Compiling model"
        optimizer = Nadam(lr=0.002,
                          beta_1=0.9,
                          beta_2=0.999,
                          epsilon=1e-08,
                          schedule_decay=0.004)
        osr.compile(loss="categorical_crossentropy",
                    optimizer=optimizer,
                    metrics=["categorical_accuracy"])
        self.osr = osr
        print " * OSR MODEL GENERATED * "

    def process_training_data(self):
        """ Preprocesses training data and saves them into an HDF5 file
        """
        # load training metadata from config file
        training_metadata = {}
        training_classes = []
        with open(self.config_file) as training_config:
            training_metadata = json.load(training_config)
            training_classes = sorted(list(training_metadata.keys()))

            print "".join(["\n",
                           "Found {0} training classes!\n".format(len(training_classes)),
                           "-"*40])
            for class_label, training_class in enumerate(training_classes):
                print "{0:<4d} {1:<10s} {2:<30s}".format(class_label, training_class, training_metadata[training_class])
            print ""

        # count number of samples
        sample_count = 0
        sample_count_by_class = [0]*len(training_classes)
        for class_label, training_class in enumerate(training_classes):
            # get training class sequeunce paths
            training_class_data_path = training_metadata[training_class]
            training_class_sequence_paths = [os.path.join(training_class_data_path, file_name)
                                             for file_name in os.listdir(training_class_data_path)
                                             if (os.path.isfile(os.path.join(training_class_data_path, file_name))
                                                 and ".mov" in file_name)]
            # update sample count
            sample_count += len(training_class_sequence_paths)
            sample_count_by_class[class_label] = len(training_class_sequence_paths)

        print "".join(["\n",
                       "Found {0} training samples!\n".format(sample_count),
                       "-"*40])
        for class_label, training_class in enumerate(training_classes):
            print "{0:<4d} {1:<10s} {2:<6d}".format(class_label, training_class, sample_count_by_class[class_label])
        print ""

        # initialize HDF5 save file, but clear older duplicate first if it exists
        try:
            print "Saved file \"{0}\" already exists! Overwriting previous saved file.\n".format(self.training_save_fn)
            os.remove(self.training_save_fn)
        except OSError:
            pass

        # process and save training data into HDF5 file
        print "Generating {0} samples from {1} samples via data augmentation\n".format(sample_count*self.samples_generated_per_sample,
                                                                                sample_count)
        sample_count = sample_count*self.samples_generated_per_sample
        with h5py.File(self.training_save_fn, "w") as training_save_file:
            training_save_file.attrs["training_classes"] = np.string_(",".join(training_classes))
            training_save_file.attrs["sample_count"] = sample_count
            x_training_dataset = training_save_file.create_dataset("X",
                                                                  shape=(sample_count, 1, self.frames_per_sequence, self.rows, self.columns),
                                                                  dtype="f")
            y_training_dataset = training_save_file.create_dataset("Y",
                                                                   shape=(sample_count, len(training_classes)),
                                                                   dtype="i")

            # iterate through each class data
            sample_idx = 0
            for class_label, training_class in enumerate(training_classes):
                # get training class sequeunce paths
                training_class_data_path = training_metadata[training_class]
                training_class_sequence_paths = [os.path.join(training_class_data_path, file_name)
                                                 for file_name in os.listdir(training_class_data_path)
                                                 if (os.path.isfile(os.path.join(training_class_data_path, file_name))
                                                     and ".mov" in file_name)]
                # iterate through each sequence
                for idx, training_class_sequence_path in enumerate(training_class_sequence_paths):
                    sys.stdout.write("Processing training data for class \"{0}\": {1}/{2} sequences\r"
                                     .format(training_class, idx+1, len(training_class_sequence_paths)))
                    sys.stdout.flush()

                    # accumulate samples and labels
                    samples_batch = self.process_frames(training_class_sequence_path)
                    label = [0]*len(training_classes)
                    label[class_label] = 1

                    for sample in samples_batch:
                        x_training_dataset[sample_idx] = sample
                        y_training_dataset[sample_idx] = label

                        # update sample index
                        sample_idx += 1

                print "\n"

            training_save_file.close()

            print "Training data processed and saved to {0}".format(self.training_save_fn)

    def process_frames(self, video_file_path):
        """ Preprocesses sequence frames
        """
        # haar cascades for localizing oral region
        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        mouth_cascade = cv2.CascadeClassifier('haarcascade_mcs_mouth.xml')

        video = cv2.VideoCapture(video_file_path)
        success, frame = video.read()

        frames = []
        success = True

        # convert to grayscale, localize oral region, equalize frame dimensions, and accumulate valid frames
        while success:
          success, frame = video.read()
          if success:
            # convert to grayscale
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # localize single facial region
            faces_coords = face_cascade.detectMultiScale(frame, 1.3, 5)
            if len(faces_coords) == 1:
              face_x, face_y, face_w, face_h = faces_coords[0]
              frame = frame[face_y:face_y + face_h, face_x:face_x + face_w]

              # localize oral region
              mouth_coords = mouth_cascade.detectMultiScale(frame, 1.3, 5)
              threshold = 0
              for (mouth_x, mouth_y, mouth_w, mouth_h) in mouth_coords:
                if (mouth_y > threshold):
                    threshold = mouth_y
                    valid_mouth_coords = (mouth_x, mouth_y, mouth_w, mouth_h)
                else:
                    pass
              mouth_x, mouth_y, mouth_w, mouth_h = valid_mouth_coords
              frame = frame[mouth_y:mouth_y + mouth_h, mouth_x:mouth_x + mouth_w]

              # equalize frame dimensions
              frame = cv2.resize(frame, (self.columns, self.rows)).astype('float32')

              # accumulate frames
              frames.append(frame)

            # ignore multiple facial region detections
            else:
                pass

        # equalize sequence lengths
        if len(frames) < self.frames_per_sequence:
            frames = [frames[0]]*(self.frames_per_sequence - len(frames)) + frames
        frames = np.asarray(frames[0:self.frames_per_sequence])

        # pixel normalizer
        pix_norm = lambda frame: frame / 255.0

        samples_batch = [[map(pix_norm, frames)]]

        # random transformations for data augmentation
        for _ in xrange(0, self.samples_generated_per_sample-1):
            rotated_frames = random_rotation(frames, rg=45)
            shifted_frames = random_shift(rotated_frames, wrg=0.25, hrg=0.25)
            sheared_frames = random_shear(shifted_frames, intensity=0.79)
            zoomed_frames = random_zoom(sheared_frames, zoom_range=(1.25, 1.25))
            samples_batch.append([map(pix_norm, zoomed_frames)])

        return samples_batch

class ProgressDisplay(Callback):
    """ Progress display callback
    """
    def on_batch_end(self, epoch, logs={}):
        print "    Batch {0:<4d} => Accuracy: {1:>8.4f} | Loss: {2:>8.4f} | Size: {3:>4d}".format(int(logs["batch"])+1,
                                                                                float(logs["categorical_accuracy"]),
                                                                                float(logs["loss"]),
                                                                                int(logs["size"]))

if __name__ == "__main__":
    # Example usage
    osr = OpticalSpeechRecognizer(rows=100,
                                  columns=150,
                                  frames_per_sequence=45,
                                  samples_generated_per_sample=10,
                                  config_file="training_config.json",
                                  training_save_fn="training_data.h5",
                                  osr_save_fn="osr_model.h5")
    # osr.process_training_data()
    osr.generate_osr_model()
    osr.print_osr_summary()
    osr.train_osr_model()
    osr.save_osr_model()
    osr.load_osr_model()

Introducing batch normalization seems to have caused the training loss to be NaN very quickly:

A: Seems like you introduce nan inputs into your network. For nan input you will get nan output. Do you by any chance have an input that is entirely 1 number? Then dividing through the variance is dividing through 0 -> nan inputs.
Edit:
You are using dim_ordering th. Therefore you want to batch normalize the axis 1. This has to be specified for the batch normalization layer. The default argument only works for tf dim_ordering.


text:
Q: how to determine the sections for cell in UITableView - objective-c im working on application that have search view,
the search view contain a tableView with 3 sections - i implement the section manually by
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 0){
        UITextField *title = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
        [title setBackgroundColor:[UIColor lightGrayColor]];
        [title setTextAlignment:UITextAlignmentRight];
        [title setFont:[UIFont boldSystemFontOfSize:15]];
        [title setText:@"videos"];
        return title ;
    }
    if (section == 1){
        UITextField *title = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
        [title setBackgroundColor:[UIColor lightGrayColor]];
        [title setTextAlignment:UITextAlignmentRight];
        [title setFont:[UIFont boldSystemFontOfSize:15]];
        [title setText:@"documents"];
        return title ;
    }
    if (section == 2){
        UITextField *title = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
        [title setBackgroundColor:[UIColor lightGrayColor]];
        [title setTextAlignment:UITextAlignmentRight];
        [title setFont:[UIFont boldSystemFontOfSize:15]];
        [title setText:@"questions"];
        return title ;
    }
}

now, all my data received with XML that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
    <title>documents</title>
        <item>
        <title>how to count the days</title>
        <link>some link...</link>
        <date>11/09/2007 16:45:00</date>
        <SupplierName>roei</SupplierName>
        <CategoryName>the omer</CategoryName>

      </item>

        <item>
        <title>research</title>
        <link>some link...</link>
        <date>16/05/2010 13:41:00</date>
        <SupplierName>eran</SupplierName>
        <CategoryName>shavoot</CategoryName>
      </item>

</channel>

<channel>
    <title> video </title>
                <item>
                <title>the end of holiday</title>
                <link>some link...</link>
                <date>06/06/2011 08:56:00</date>
                <SupplierName>dina</SupplierName>
                <CategoryName>shavoot</CategoryName>

              </item>

                <item>
                <title>bible</title>
                <link>some link...</link>
                <date>24/05/2012 10:00:00</date>
                <SupplierName>amir</SupplierName>
                <CategoryName>shavoot</CategoryName>
              </item>

</channel>

        <channel>
            <title>questions</title>

                <item>
                <title>questions for shavvot</title>
                <link>some link...</link>
                <date>28/10/2008 13:31:00</date>
                <SenderName>אלי.ד.</SenderName>
                <CategoryName>holidays</CategoryName>
              </item>

                <item>
                <title>Shavoot</title>
                <link>some link...</link>
                <date>25/05/2008 01:01:00</date>
                <SenderName>amir</SenderName>
                <CategoryName>holidays</CategoryName>
              </item>

        </channel>

</rss>

as you can see- i have title with the names of the sections, but how should i determine the correct sections for the cells ?
im parsing all the data to one array and then getting it out using dictionary:
NSDictionary *object = [ResultsArrayDisplay objectAtIndex:indexPath.row];

please help me, im after few hours of tries with nothing helpful in the internet so far.

A: This is your problem:

im parsing all the data to one array and then getting it out using
  dictionary:

Put the data for each section in its own array then use indexPath.section to determine which array to use.  For each section it will give you rows for that section only so you can use the indexPath.row to index into each of your arrays.
If you insist on keeping everything in one array, then you will have to maintain a count of how many of each type you have and then use that to figure out which array index you need.
In either case be sure to implement numberOfRowsinSection:.  If you're using multiple arrays then this will just be the array count for that section otherwise it will be the portion of your main array that is used in that section.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Construction of small resolution of a double point Suppose $X$ is the hypersurface in $\mathbb{A}^4$ defined by
$$x_1 x_4-x_2 x_3 +f(x_1,x_2,x_3,x_4)=0$$
where $f$ is a polynomial whose monomial terms are all of degree $\geq 3$. So the origin $(0,0,0,0)$ is a double point of $X$.
If $f=0$, a small resolution of this double point could be easily constructed. Suppose the homogeneous coordinates of $\mathbb{P}^1$ are $(y_0,y_1)$. Let the variety $\hat{X}$ in $\mathbb{A}^4 \times \mathbb{P}^1$ be defined as,
$$x_1 y_0+x_2 y_1=0$$
$$x_3 y_0+x_4 y_1=0$$
Then there is a natural projection $\hat{X} \rightarrow X$ which replaces the double point of $X$ by a $\mathbb{P}^1$. However if $f$ is not zero, does there exist an explicit construction as above?


text:
Q: Wrapping localStorage in Ember-cli Demo In the example code below
http://jsbin.com/ketaqiwe/embed?js,output
I am able to select a color, and the computed property will change based on the color but the localstorage will also change.
But if I open the console and edit the localstorage and change the color manually a storage event will trigger and the action will change the color anyway.
The challenge I am having is triggering the eventListener within Ember-cli.
I'm not sure whats the best practice is for this example to be done inside of ember-cli.

A: Use an addon to handle it for you? https://github.com/locks/ember-localstorage-adapter/blob/master/README.md


text:
Q: Rails: validates_length_of :allow_nil does not allow nil Using: Rails 3.0.3.
I am using this code in the validator:
validates_length_of :birth_date_8, :minimum => 8, :allow_nil => true, :message => "value_is_not_a_proper_date", :if =>:family_birthday?

It does not, however, allow the field to be nil. I have checked so it is not a matter of the :if => :family_birthday? that is messing things up.
Is there something wrong with the code?

A: Try allow_blank instead of allow_nil :-)


text:
Q: Handing image file not found error in Django I am trying to handle the image not found an error in Django by defining a custom view unhandle_urls.
The way I am trying to do this is the following.
Define a URL pattern inside urls.py to match the image URL's pattern and route them to my custom view  unhandle_urls
Here are my url patterns inside urls.py
urlpatterns = [

        ....

        path(r'images/*', unhandle_urls, name="handling image not found urls"),

        ...

]

However, I am still getting the same 404 error whenever any image is requested.
Here is the error msg:
GET https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png 404 (Not Found)

I am not sure what the problem is. My guess is that the url pattern r'images/*' is not matching to
https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png, but when I try to look at this https://docs.djangoproject.com/en/3.1/topics/http/urls/, I could not find what's wrong with my regex or my approach.
Any type of help/suggestions will be appreciated. Thanks in advance.
Update:
Here is my view
def unhandle_urls(request):
    if is_authenticated(request):
        return HttpResponse('')
    else:
        return render(request, "error.html", {})


text:
Q: PHP Radio Button in php table, need syntax to read its value to passon as session variable to other page. Image attached How to read value of radio button included in PHP table so that it can be passon as session.

A: Take your radio button into a form, and set a method for that form.. for eg say POST.
So your code will be
<?php
$value = $_POST['radio1'];
$_SESSION['keyname'] = $value;
//or u can directly do it in this way
$_SESSION['keyname'] = $_POST['radio1'];
?>

now u can use that radio button value from the session variable as long as the session is active.


text:
Q: CMake не находит PythonLibs под Windows Хочу встроить Python в одно своё приложение, которое собирается с помощью CMake. Делаю в CMakeLists.txt так:
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
...
target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES})

Под Linux никаких проблем нет, всё собирается сразу. Поставил Python (последняя актуальная версия на данный момент - 3.6) на Windows. При установке выбрал "Установить для всех пользователей" и "Добавить Python в переменную PATH". После установки интерпретатор Python отлично работает. Однако CMake не может найти Python:
CMake Error at C:/Program Files/CMake/share/cmake-3.7/Modules/FindPackageHandleStandardArgs.cmake:138 (message):
  Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.7/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files/CMake/share/cmake-3.7/Modules/FindPythonLibs.cmake:255 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:3 (find_package)

В чём может быть проблема? И как заставить проект собираться на обоих ОС без проблем?

A: Функция find_package() не ищет по всему вашему жесткому диску, а только в определенных директориях. На Линуксе, грубо говоря, все библиотеки лежат в одном месте, поэтому CMake без труда их находит.
На винде питон можно установить в какую угодно директорию, поэтому CMake необходимо вручную ткнуть мордой в нужную папку. О чем, собственно, он и сказал:

Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)

Можете установить эти переменные в нужные значения, а можете установить переменную CMAKE_PREFIX_PATH и указать в ней папку с питоном. Должно сработать, по идее.


text:
Q: Windows Phone 7 emulator set to 7.0 Microsoft claims that the WP7 emulator supports both 7.0 and 7.1(7.5) builds http://msdn.microsoft.com/en-us/library/ff402563(v=vs.92).aspx
I am developing a web app for this device and need to see the browser in its 7.0 state ( user agent IEMobile/7 ) and its 7.1 state ( user agent IEMobile/9 ). The emulator is set to 7.1 be default, and I cannot figure out how to get it to display to 7.0 browser. Does anyone know how to accomplish this?


text:
Q: DeprecationWarning: please use dns.resolver.Resolver.resolve() I am using resolver() as an alternative to socket() as I found that when multiple connections are made to different IPs it ends up stopping working.
Anyway it returns a warning to me that I should use dns.resolver.Resolver.resolve ()
When changing it, it gives me an error:
TypeError: resolve() missing 2 required positional arguments: 'self' and 'qname'

This is the code:
        # my_resolver = dns.resolver.Resolver()
        my_resolver = dns.resolver.Resolver.resolve()
        answers = my_resolver.query(host, "A")
        answer_txt = my_resolver.query(host, "TXT")

A: faced the same problem
You should remove .resolve from my_resolver = dns.resolver.Resolver.resolve() and replace my_resolver.query() with my_resolver.resolve()
Example:
    my_resolver = dns.resolver.Resolver()
    answers = my_resolver.resolve(host, "A")
    answer_txt = my_resolver.resolve(host, "TXT")


text:
Q: How to map a dask Series with a large dict I'm trying to figure out the best way to map a dask Series with a large mapping. The straightforward series.map(large_mapping) issues UserWarning: Large object of size <X> MB detected in task graph and suggests using client.scatter and client.submit but the latter doesn't solve the problem and in fact it's much slower. Trying broadcast=True in client.scatter doesn't help either.
import argparse
import distributed
import dask.dataframe as dd

import numpy as np
import pandas as pd

def compute(s_size, m_size, npartitions, scatter, broadcast, missing_percent=0.1, seed=1):
    np.random.seed(seed)
    mapping = dict(zip(np.arange(m_size), np.random.random(size=m_size)))
    ps = pd.Series(np.random.randint((1 + missing_percent) * m_size, size=s_size))
    ds = dd.from_pandas(ps, npartitions=npartitions)
    if scatter:
        mapping_futures = client.scatter(mapping, broadcast=broadcast)
        future = client.submit(ds.map, mapping_futures)
        return future.result()
    else:
        return ds.map(mapping)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', default=200000, type=int, help='series size')
    parser.add_argument('-m', default=50000, type=int, help='mapping size')
    parser.add_argument('-p', default=10, type=int, help='partitions number')
    parser.add_argument('--scatter', action='store_true', help='Scatter mapping')
    parser.add_argument('--broadcast', action='store_true', help='Broadcast mapping')
    args = parser.parse_args()

    client = distributed.Client()
    ds = compute(args.s, args.m, args.p, args.scatter, args.broadcast)
    print(ds.compute().describe())

A: You problem is here
In [4]: mapping = dict(zip(np.arange(50000), np.random.random(size=50000)))

In [5]: import pickle

In [6]: %time len(pickle.dumps(mapping))
CPU times: user 2.24 s, sys: 18.6 ms, total: 2.26 s
Wall time: 2.25 s
Out[6]: 6268809

So mapping is big and unpartitioned - the scatter operation is the one giving you the problem in this case.
Consider the alternative
def make_mapping():
    return dict(zip(np.arange(50000), np.random.random(size=50000)))

mapping = client.submit(make_mapping)  # ships the function, not the data
                                       # and requires no serialisation
future = client.submit(ds.map, mapping)

This will not show the warning. However, it seems strange to me to use a dictionary here to do the mapping, a series of straight array seems to encode the nature of the data better.


text:
Q: While Run Facebook Login App it Shows Error Here in my Main activity and I follow all the facebook Concole Methood.
When I tried to run the app.it shows an error that

Login error: There was an error while login your app, try again later

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

        loginButton = findViewById(R.id.login_button);
        textView1 = findViewById(R.id.tv1);
        textView2 = findViewById(R.id.tv2);
        textView3 = findViewById(R.id.tv3);
        circleImageView = findViewById(R.id.profile_pic);

        callbackManager = CallbackManager.Factory.create();

        loginButton.setPermissions(Arrays.asList("first_name","last_name","email","id","image_url"));
        checkLoginStatus();

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
        {
            @Override
            public void onSuccess(LoginResult loginResult)
                {

                }

            @Override
            public void onCancel()
                {

                }
            @Override
            public void onError(FacebookException error)
                {

                }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            callbackManager.onActivityResult(requestCode, resultCode, data);
            super.onActivityResult(requestCode, resultCode, data);
        }

        AccessTokenTracker accessTokenTracker=new AccessTokenTracker()
        {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken)
                {
                    if(currentAccessToken==null)
                        {
                            textView1.setText("");
                            textView2.setText("");
                            textView3.setText("");
                            circleImageView.setImageResource(0);
                            Toast.makeText(MainActivity.this,"User Logged out",Toast.LENGTH_LONG).show();
                        }
                     else
                         {
                            loadUserProfile(currentAccessToken);
                         }
                }
        };

    private void loadUserProfile(AccessToken newacesstoken)
        {
            GraphRequest request=GraphRequest.newMeRequest(newacesstoken,new GraphRequest.GraphJSONObjectCallback()
                {
                     @Override
                     public void onCompleted(JSONObject object, GraphResponse response)
                        {
                             try
                                {
                                    String first_name=object.getString("first_name");
                                    String last_name=object.getString("last_name");
                                    String email=object.getString("email");
                                    String id=object.getString("id");
                                    String  image_url = "https://graph.facebook.com/" + id + "/picture?type=normal";

                                    textView1.setText(first_name +" "+last_name);
                                    textView2.setText(email);
                                    textView3.setText(id);
                                    //RequestOptions requestOptions = new RequestOptions();
                                    //requestOptions.dontAnimate();
                                    Picasso.get().load(image_url).into(circleImageView);
                                }
                             catch (JSONException e)
                                {
                                    e.printStackTrace();
                                }
                        }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "first_name,last_name,email,id,image_url");
                request.setParameters(parameters);
                request.executeAsync();
        }

            private void checkLoginStatus()
    {
        if(AccessToken.getCurrentAccessToken()!=null)
        {
            loadUserProfile(AccessToken.getCurrentAccessToken());

        }
    }
    }


text:
Q: Is there an FPGA based vector graphics card project? I have been messing around with VGA projects as my latest interest. I have a Xilinx Spartan 3E 250K FPGA, which has just barely too little RAM for a full 640x480 frame buffer. So, I'm looking at making things more "interesting". Namely, by instead going for a vector approach rather than bitmap. However, it's a bit mind boggling as far as how to do it. Are there any known and open source vector based VGA graphics cards?
I'm not going to be using this in any kind of "production" scenario, so I don't really care if it can only effectively render at 1fps or something. I'm just looking at an interesting project idea.

A: Please, please, please don't take what I'm about to say personally.  I think your question is one that a lot of people have probably wondered about at one point or another.  I even up-voted the question.  Unfortunately, the answer is "it doesn't work that way".  And there is no good way to answer your question without possibly making you feel bad for asking it-- which is a shame because I think that there is useful info in the answer.  So, bear with me on this and understand that my motivation is to explain how this stuff works and not to make you feel bad.
Modern displays (TV's, LCD's, Plasma, most CRT's) are raster based devices.  Meaning, they redraw the screen one scan line at a time.  The video interfaces used to talk to these displays are based around a raster interface.  NTSC, VGA, HDMI, etc. are all raster display technologies.
Years ago, mostly in the 70's and early 80's, there were some true vector displays.  Instead of drawing things a scan line at a time they actually traced out the shape of the objects.  The best examples of this are analog o-scopes, and the arcade games Asteroids and Battlezone.  There are very few color vector displays that were used, and the best example of that is the arcade game Tempest.  A different form of vector display is the systems used for laser light shows.
The electrical interface to a vector display has signals for the X and Y location of the beam, the intensity, and sometimes the color.  This is very different than the interface for a raster display.
Older CRT technology could be used for either vector or raster displays, but LCD's, Plasma screens, OLED's, etc are all fundamentally raster based and cannot easily be used in a vector type mode.
The problem with your question is that you are asking about a "vector based VGA graphics card".  "Vector Based" does not go with VGA.  VGA is a raster based display standard and interface, while vector is not.  You cannot mix the two, since they are different systems.
It is possible to make a vector graphics card based on an FPGA, but you can't connect it to a VGA type monitor without doing a vector to raster conversion in the FPGA-- and that requires as much RAM or more than a standard raster graphics card.  You could get a vector display, but those have all but gone away with the demise of the CRT.
The easiest way to get a vector display these days is to get an o-scope that has an X/Y mode.  In fact, there are many projects on the web that use an old o-scope with CRT tube as the display for something.  Here is a project that uses one to make a clock.  And here is another one.  There are dozens of other similar projects on the web.
While interesting, these projects are little more than novelties.  They are cool novelties, but just novelties.  And none of them approach the display quality of a normal VGA card.
An alternative solution is to simply get an FPGA with some external RAM.  There are many ways to do this, but the easiest and most pain-free way is to use a Xilinx Spartan-6 based board with external DDR2 SDRAM.  There are several FPGA development boards on the market that have both of these chips that will work.  Some of them even have VGA interfaces too.
I would not use external SRAM.  SRAM, especially async-SRAM, is going to be slow to interface too and the memory size will be limited.  It's not impossible to use SRAM, but it is not any easier to use SRAM than DDR2 SDRAM on a Spartan-6.
I would also not use a Spartan-3.  The S3's DDR SDRAM interface is not very good, and is difficult to get the signal timing to work out reliably.  The Spartan-6 has a "hard macro" for the DDR2 interface, which makes the whole thing much easier.  The S6 also has more internal RAM for buffers, FIFO's, etc.  Xilinx has a nice "Memory Interface Generator" core that makes interfacing several different chunks of logic to the DDR2 SDRAM much easier (with multiple read/write ports too).
As for an open source Vector Graphics core-- I do not know of one.  That doesn't mean there isn't one, just that I have not seen one.  But I also doubt that you'll see one that is very good.  There just isn't that much call for one since the displays are somewhat rare and limited.  If you do find one, it will likely be fairly specialized (it only displays a clock).
Get an FPGA board with a Spartan-6, DDR2 SDRAM, and a VGA port and you'll be much happier.


text:
Q: Resultset overflow occurred jpivot I have created cube in PSW and published it over BI server. Using this cube I have created jPivot view (slice & dice).
When I try to expand the view it gives me "Resultset overflow occured" message. Logs are not showing any error.
I am using PSW CE -8.1 and Pentaho Server CE 8.1
Total records in fact table is 25 million
Below is done to optimise the performance:

*

*Indexes are added in dimensions and fact tables

*Pentaho query time out increased
 file name - pentahoobjects.spring.xml

*Tomcat time out increased
server.xml -> change connectiontimeout to 0

*Below mondrian.properties are changed (mondrian/mondrian.properties)
mondrian.result.limit=0

mondrian.olap.case.sensitive=false

mondrian.native.crossjoin.enable=true

mondrian.native.ExpandNonNative=false

Please suggest what is wrong or any other property needs to be optimised.
Thanks,
Mayuri


text:
Q: Yelp Fusion API v3 returns 401 Unauthorized with TOKEN_MISSING error when called from c# I've created my app in Yelp, got my api key, and things work fine from Postman when executing a business search.
However, when testing from c#, I receive a 401 unauthorized error with a TOKEN_MISSING error that says ""{\"error\": {\"code\": \"TOKEN_MISSING\", \"description\": \"An access token must be supplied in order to use this endpoint.\"}}"".
I'm supplying my api key correctly though, and the Yelp documentation says that's all I need, so I'm not sure what the problem is.  Here are 2 separate c# code samples that do NOT work (I've replaced my actual api key with  for security concerns):
Example using WebRequest:
var webRequest = WebRequest.Create("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
webRequest.Method = "GET";
webRequest.Headers.Add("Cache-Control", "no-cache");
webRequest.Headers.Add("Authorization", "Bearer <my_api_key>");
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
var stream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
var content = stream.ReadToEnd();
Console.Write(content);

Example using RestSharp:
var client = new RestClient("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "Bearer <my_api_key>");
var response = client.Execute(request);
Console.Write(response.Content);

I've examined the requests in Fiddler, and both are sending the same headers as the working Postman search, but both return 401 unauthorized error while Postman returns the search results.  Any ideas?
Edit:
Well this is embarrassing, apparently my issue was I was attempting to access the Yelp API via http instead of https.  Once I changed to https, everything worked as expected.

A: Changed endpoint to use https instead of http, works now.


text:
Q: python change a files creation and modification time without having to use a subcommand? I want to change the modification and creation time of any file with python. This would be the command I use in Linux:
touch -a -m -t 201512180130.09 ./file.jpg

Then I check the following I can see the date is changed correctly:
$ls -l --time-style=full-iso
-rw-rw-r--  1 me me 44570 2015-12-18 01:30:09.000000000 -0500 file.jpg

$exiftool ./file.jpg | grep -i date
File Modification Date/Time     : 2015:12:18 01:30:09-05:00
File Access Date/Time           : 2015:12:18 01:30:09-05:00
File Inode Change Date/Time     : 2022:12:13 19:39:43-05:00

I tried using the Pathlib('./file.jpg').touch() and os.utime('./file.jpg', None). neither worked.
How can I do this in Python without having to use os or subprocess commands?


text:
Q: Creating Android Studio Layout with complete screen as background I have already created complete screens for my App in the development process using spark. These images are the complete screens including buttons etc. I have set them as android: background and put buttons with android:background="@null" in the places where the buttons are in the images. My Intention was to avoid designing all the screens in android studio and instead just setting the whole screen as a background and laying invisible buttons in the correct spots for functionality. Now I have run into the Problem that my Buttons are in different places depending on the device. I am using relative layouts for this. Thank you so much for your help!

A:
my Buttons are in different places depending on the device. I am using relative layouts for this.

I would recommend that you use constraintlayout if you want things to scale. Then use vertical & horizontal bias to position your buttons where they need to be.
If you are struggling with your parent layout changing between devices, use the constraintDimensionRatio, like this:
<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/layoutMap"
        app:layout_constraintDimensionRatio="H, 2 : 1"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
</androidx.constraintlayout.widget.ConstraintLayout>

You may need to create separate layouts for portrait and landscape if need be.


text:
Q: Add Velocity to SKPhysicsBody while moving it's SKSpriteNode Right now I am moving a SKSpriteNode by changing it's position during func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?).
My problem with that is that while I am moving the SpriteNode, it's SKPhysicsBody's velocity is not changed. Therefore when that SpriteNode does collide with another SKSpriteNode that second SpriteNode will only get pushed around and not really bounce off like you would expect it.
Is there anyway to fix that? I was already thinking about manually applying velocity to that second SpriteNode on func didBegin(_ contact: SKPhysicsContact) but I would not really be happy with that kind of solution.
Thanks!

A: Generally speaking, in SpriteKit you should avoid mixing physics-based movement with direct movement. By physics-based movement, I mean moving a node's physics body by applying a force/impulse or setting its velocity property directly. By direct movement, I mean things like settings its position property directly (which it sounds like you are doing) or using an SKAction like moveTo:duration:.
So if you are already using physics to move a node, you should continue using physics to move it rather than altering its movement directly. Or if you are moving a node using direct movement only, and then you want to find out things about its speed (such as velocity in your case), you will have to write your own calculations to figure out how far the object moves between frames. This is because the object's movement is not being performed by the physics engine.
Of course, you don't have to follow this practice. But you might run into issues like the one you have encountered.
One additional point is that if you want to detect if two nodes contact each other---but not collide with each other---then it's okay to use direct movement on physics bodies. But in your case it sounds like you are dealing with colliding bodies, so I'd recommend sticking with one approach or the other to keep things neat.


text:
Q: Is it safe to put control char in string? char *a = malloc(10);
memset(a, 10, 0);
a[0]= 'a';
a[1]= 6;
a[2]= 'b';
printf("%s\n", a); // prints ab
a[0]= 'a';
a[1]= 27;
a[2]= 'b';
printf("%s\n", a); // print a
return 1;

Is it safe to put control char in string? like in strcpy, etc..

A: C strings are NUL-terminated sequences of chars (bytes). Nothing more. Therefore, the control characters have no special meaning to the language or to strcpy.
Functions that care about the contents of strings will define which characters have special meanings.


text:
Q: Square in a finite field I need to prove: $a$ is a square in $\mathbb{Z}$ iff $a\mod p$ is a square in $\mathbb{F_p}$ for every $p$ prime. First side ($\rightarrow$) is trivial and is derived directly from multiplicativity of modulo. Now I need to prove the other side ($\leftarrow$). I tried taking $p>a$ so $a\equiv a\mod p$, and I know that $a$ is a square so there exists $b<p$ s.t $\space$$b^2\mod p \equiv a$. But, $b$ is not necessarily the root of $a$ in $\mathbb{Z}$, so I'm stuck. I also know that for each $p$, $(\frac{a}{p})=1$ but this doesn't get me anywhere. Any hint would help.

A: If think the easiest way is to use quadratic reciprocity, that if $a$ is not a square then for $p\ne 2$,
$(\frac{a}p) =\chi(p) $ with $\chi$ a non-trivial Dirichlet character modulo $4a$,
there is $m>0$ such that $\chi(m)=-1$, some prime $p|m$ is such that $-1=\chi(p)=(\frac{a}p)$


text:
Q: How to add slow log configuration in elasticsearch.yml? In older version of elasticsearch the slowlog will be in elasticsearch.yml but
for new version like 5.1.1 we have to add like slowlog configs like
    index.search.slowlog.threshold.query.debug: 0s
    index.search.slowlog.threshold.fetch.debug: 0s
    index.indexing.slowlog.threshold.index.debug: 0s
I tried adding these configs in my elasticsearch.yml,when i started the elasticsearch service it is not starting it is throwing an error.
Can anyone help me to solve this problem?

A: Since Elasticsearch 5, slow log settings are for each indices.
You can PUT the settings to a specific index /index_name/_settings
with a payload like the following. More details are available at Elasticsearch Reference
{
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.query.debug": "2s",
"index.search.slowlog.threshold.query.trace": "300ms",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.search.slowlog.threshold.fetch.info": "800ms",
"index.search.slowlog.threshold.fetch.debug": "500ms",
"index.search.slowlog.threshold.fetch.trace": "300ms",
"index.indexing.slowlog.threshold.index.warn": "10s",
"index.indexing.slowlog.threshold.index.info": "5s",
"index.indexing.slowlog.threshold.index.debug": "2s",
"index.indexing.slowlog.threshold.index.trace": "300ms",
"index.indexing.slowlog.level": "trace",
"index.indexing.slowlog.source": "1000"
}


text:
Q: How do I show the full output for df.describe()? I'm using df.describe() to get a summary of my data, but I'm only able to see the first and last variables. I want to be able to see all the output from the code so that I can copy it into a word file. How am I able to do that?

A: Use df.to_csv, for example:
df.to_csv(file_name, sep='\t', index = False)


text:
Q: File Download using iframe not working in Iphone/Ipad File download feature is not working for my MVC-Bootstrap web application that uses an iframe in Iphones/Ipads ( for both Safari and Chrome). Everything works well in desktops,laptops and in Android devices ( for all browsers).
In a button click, I use the below Jquery code to invoke an iframe to download a PDF
 $("#iframedownload").attr("src", downloadURL);

downloadURL points to the page that has the code to download the file.
Code to download file
return File(filebyteArray, "application/pdf", string.Format("Myfile.pdf",
DateTime.Now.Ticks.ToString()));

Iframe
<iframe id="iframedownload" style="display: none"></iframe>

Any thoughts on this ?

A: Looks like iframe download approach is not supported in Iphone/Ipad
Use  window.location instead
window.location = "@Url.Action(Action, Controller)";


text:
Q: adjusting all the child div elements within the parent div Hi i am using bootstrap for designing an application, i have the entire form defined inside a container , but as i keep adding the child  inside the container div i want the parent div to expand automatically and show all the child div for example,

  ......
  ........
  .........

now what happens on my page is on the browser few child
s won't show up , can anyone of you tell me what attribute can i include to make the

 to accommodate all the elements,
i tried overflow:auto but this did not work.

A: Try this one with jquery. I hope this will work for you.
$('.container').children().show();


text:
Q: I get an "invalid property name" error while running my code in pycharm. i have a simple python "main.py" file and a kivy "MyQuiz.kv" file OK, so i'm trying to make an app using python and kivy.From tutorials and from search on google i've seen people using kivy language to simplify their code but when i try to create a kv file for my program i get an "Invalid property name" ERROR and i dont know what to do.I did everything the guy on the tutorial did and followd every instruction on google but still i get this error.Did anyone had the same problem before and how did you solve it? Thanks in advance!
This is my python file:
           import kivy
           #kivy.require('1.0.6') # replace with your current kivy version !
           from kivy.app import App
           from kivy.uix.label import Label
           from kivy.uix.button import Button
           from kivy.uix.scatter import Scatter
           from kivy.uix.floatlayout import FloatLayout
           from kivy.uix.textinput import TextInput
           from kivy.uix.boxlayout import BoxLayout
           from kivy.uix.screenmanager import ScreenManager,Screen
           from kivy.lang import Builder
           from kivy.properties import NumericProperty

           class QuizWidget(BoxLayout):
                  pass

           class MyQuizApp(App):

                  def build(self):
                      return QuizWidget()

           if __name__ == '__main__':
                   MyQuizApp().run()

This is my kivy file:
<QuizWidget>:
orientation = 'vertical'
TextInput:
    id: Start_text
    font_size: 100
    size_hint_y: None
    height: 200
    text: 'Wellcome to my quiz.Press START to continue'
    Button:
        text:'START'
        font_size: 150

A: orientation = 'vertical'

This should be orientation: 'vertical'. Kivy is trying to parse the whole thing as a property name since you didn't have a :. The error should probably point to this line, but you didn't give enough info to check.


text:
Q: Unable to append data to string using serializeArray() and array.push() After following answers like this one, I'm trying to append data to a string using:
<input type='checkbox' name='a' />A
<input type='checkbox' name='b' checked='checked'/>B
<input type='checkbox' name='c' />C

var attr_str = $('input').serializeArray();
attr_str.push({q:'hello',p:'world'});

But it returns [object Object],[object Object]. What am I missing?
JSFIDDLE

A: The serializeArray returns an array of objects, each contains the properties name and value.
Ex
[{"name": "x", "value": "y"}, {"name": "a", "value": "b"}, ...]

That is why it is printing [Object, Object].
You can use JSON.stringify(attr_str) to print the stringified values if you want. But JSON.stringify is not natively supported in old browsers, so you may have to include a compatibility library like JOSN2
Demo: Fiddle.

A: I'm not sure what you're trying to accomplish but only the input which is checked is going to be included by serializeArray(). You can read more about it here.
But your array is being returned as an object as it should. To see the layout of the JSON of this object you could try JSON.stringify(attr_str).
var attr_str = $('input').serializeArray();

attr_str.push({q:'hello',p:'world'});

$('body').append('

string='+JSON.stringify(attr_str));

This will show that you are appending an object into yourattr_str array but only input 'b' is included because it is the only one that is checked. string=[{"name":"b","value":"on"}{"q":"hello","p":"world"}]
To access this object you would simply use attr_str[0] then for a property of that object use attr_str[0].name. Which would print b.


text: Q: How many arrangements of the following? How many arrangements (permutations) of a set of $\frac{n(n+1)}{2}$ distinct cards, each having one of $n$ colors $c_1,\ldots,c_n$ where there are $i$ cards of color $c_i$ that are numbered  $1,2,\ldots,i$, satisfy the following constraint: any two cards of the same color and with consecutive numbers cannot be adjacent in the arrangement. This seems to be similar to this problem, but in our case all the cards are distinct, whereas in that problem the cards of the same color are all identical.


text:
Q: iOS Game Center Leaderboard scores are disappearing I have a new game that I just released to the app store, and I'm having an issue with the Game Center Leaderboards. My app successfully posts scores to a leaderboard, and opening Game Center shows those scores as well. Then, after anywhere between 30min-2hrs later all of the scores on the Leaderboard disappear. Has anybody seen anything similar (in live Leaderboards, not Sandbox)?
Thanks


text:
Q: XPages Style Class does not work on Label in browser but appears in Designer This has been eating at me for a while now.  I seem to run into the issue sometimes -- I have a label that has a style class from a stylesheet that I can see working correctly in Domino Designer:

However, when it appears on the web, there in no styling:

I have performed a Clean which I thought might correct this issue.
Here is the code:
<xp:label value="Email Address is already in use." id="emailExistsText"
styleClass="myCustomErrorMessage">
<xp:this.rendered><![CDATA[#{javascript:var emailCheck = sessionScope.get("emailExists");
    if (emailCheck == "true") {
        return true;
    }
    else {
        return false;
    }}]]>
</xp:this.rendered>

Is it because there is a hide/when script on the label?
Thanks!

A: Some other CSS class must be overriding your custom CSS class. Check with for instance Chrome Developer Tools or Firebug what CSS classes and properties affect the style on your label.
Using Chrome Developer Tools or Firebug is essential in "debugging" styling issues.

A: What fixed this -- having the style class appear correctly -- was clicking the "refresh" icon/button in the address bar of Firefox.  That was really interesting that it corrected the issue.
After performing a Clean, removing all cached files, restarting the machine, it was clicking the refresh button that fixed it.


text:
Q: "To your left" versus "on your left"
There is a security camera on the building to your left
There is a security camera on the building on your left

Is there any real difference in meaning here? Which sounds more natural to native speakers?

A: They both sound natural, but I'd say there's a subtle difference... Maybe other native speakers could weigh in to make sure this difference isn't a regional thing.
To me, the phrase "to your left" means "about ninety degrees to the left of where you're facing," and the phrase "on your left" means more generally "to the left of where you're facing."
In your example, if we were walking down the street, I'd probably know exactly which building you were talking about if you said "the building to your left," but I might ask, "Which one?" if you said "the building on your left." (You might be referring to a couple different buildings.)
I'd also say there are subtle differences when you further modify "on/to your left." For example, it sounds much better to me to say, "the next few buildings on your left" than "the next few buildings to your left."
Similarly, if you said "all the buildings to your left," I'd interpret that to mean the buildings that I would see if I turned ninety degrees to my left, possibly including buildings behind me. If you said "all the buildings on your left", I'd interpret that to mean the buildings in front of me on the left hand side of the street.

A: As a native English speaker and English tutor, I would say that the use of the word "on" for both the building and the camera shows consistency but is also more comfortable for me and what I would naturally say if speaking to someone.


text:
Q: How to get a date in past or future in reference to current date using the date function in Liquid Template? I am running a CucumberJs test and is trying to pass a file in liquid template as input, and is trying to figure out how to get a date either in past or future from the current system date (when the test runs).
This is how I have defined in liquid template to get the current system date
"{{ "now" | date: "%Y%m%d" }}","{{ "now" | date: "%Y%m%d" }}"


text:
Q: If statement for ViewHolder is returning false all everytime back with yet another android question and feel as if I am missing something simple here.
The viewholder gets the content in the specific field of the table from which the result is read.
Now I would like to compare that result to a char to change the color of the layout it is in but unfortunately is not working as planned.
Here is the code for the holder:
@Override
public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);
    ViewHolder holder = (ViewHolder) view.getTag();
    if (holder == null) {
        holder = new ViewHolder();
        holder.colImp = cursor.getColumnIndexOrThrow(BetDbAdapter.COL_OUTCOME);
        holder.listTab = view.findViewById(R.id.won_lost);
        view.setTag(holder);
    }
    if (cursor.getString(holder.colImp).trim() == "W" || cursor.getString(holder.colImp).trim() == "w") {
        holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.green));
    } else {
        holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.red));
    }
}

The if statement just keeps returning the red even though the content is a "W", here is a screen of the app:

Also this is the insert, it is hardcoded at the moment for testing purposes:
mDbAdapter.createBet("W", 12.34, 14.78);
mDbAdapter.createBet("W", 23.77, 1.90);
mDbAdapter.createBet("W", 123.45, 134);
mDbAdapter.createBet("W", 0.4, 1.34);

Please see if you can see what I cannot to fix this.

A: The problem is in
cursor.getString(holder.colImp).trim() == "W" || cursor.getString(holder.colImp).trim() == "w"

The == equality only works for primitive values, or to check if objects are the same reference.
Try the following
cursor.getString(holder.colImp).trim().equalsIgnoreCase("W")

A: String is an Object so equality comparator just test reference but not value.
To test String equality you should use
cursor.getString(holder.colImp).trim().equal("W");

A: You are comparing Strings in code, not chars. Char - 'W'. String - "W"
If you need compare chars:
cursor.getString(holder.colImp).trim().charAt(0) == 'W'

but easier to compare Strings
"W".equals(otherString);


text:
Q: NHibernate Filters on Left Outer Joins I am running into an issue with an NHibernate filter.  It works great until I do a left outer join to the object.
For example, Deal references PurchaseItem, but PurchaseItem has a CompanyId filter applied.
If I want to query deal with a left join to PurchaseItem, the CompanyId filter is applied in the WHERE clause, causing nothing to return.
Is there a way to apply the filter at the join instead of at the where clause?

A: Fixed this by using this filter condition:
"CompanyId is NULL or CompanyId = :companyId"
This is ok because CompanyId is not-null in SQLServer so we should only get NULL if we are doing an outer join.

A: I'm looking for this exact problem with nullable optional fields
Note your OR will avoid using indexes so it may be slower.
UPDATE: I think I found the fix:
                // register filters
                var filterDef = new FilterDefinition(
                    "f_CurrentTenant",
                    "TenantId = :f_tenantId",
                    new Dictionary<string, IType> { { "f_tenantId", NHibernateUtil.Guid } },
                    **false**);
                config.AddFilterDefinition(filterDef);

When you create the filter, you can set the last parameter called "useManyToOne" = false. This will tell NH to not use the filter on the joins.
So far it seems it has worked :D


text:
Q: Using Android TCP Client app to interface with sensor UPDATE #2: BLUF: I think I found the problem, but I need help figuring out how to fix it.  The device needs a command with prefix and suffix STX>command ETX> (I had to drop the open bracket so stackoverflow would show it).  When I send over TCP using Hercules (which works), the host interprets STX> and ETX> correctly and just displays "command", however I wrote a java client program that sends the same information but it shows up on the host as "STX>commandETX>".  What is java doing differently?

Original:
I've been troubleshooting this for the last few days and I'm out of ideas so here I am.  First some background information that may or may not be relevant:
I have a SICK LMS151 LIDAR sensor that I need to access through an Android application.  The sensor is designed as a TCP server so you connect as a client and send the command STX>sRN LMDscandataETX>.  This cues the sensor to spit a bunch of data back to the client.  On a computer I can use a program like Hercules in TCP client mode, send the command and instantly receive the data without issue.  However getting an Android app to do the same has been problematic (I've attached the client code below).
I wrote a server app on a separate android device which my client app has been able to connect to and exchange data.  I send the command "STX>sRN LMDscandataETX>" through the connection and that's exactly how it shows up on the server side.  When the server app sends data, I can see it on my client. However, when I attempt to connect to the sensor with the client, it connects but does not respond to my request for data.  Any ideas of issues to look into would be helpful because at this point I'm fresh out.  Thanks!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class TcpClient extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        runTcpClient();
    }

private static final int TCP_SERVER_PORT = 2111;
private void runTcpClient() {
    try {
        Socket s = new Socket("192.168.0.105", TCP_SERVER_PORT);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Log.i("TcpClient", "Connected!");
        //send output msg
        String outMsg = "<STX>sRN LMDscandata<ETX>";
        out.write(outMsg);
        out.flush();
        Log.i("TcpClient", "sent: " + outMsg);
        //accept server response
        String inMsg = in.readLine() + System.getProperty("line.separator");
        Log.i("TcpClient", "received: " + inMsg);
        //close connection
        s.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

UPDATE:  Spent some more time on this today.  Added a BoundedInputStream from Apache in hopes that maybe I wasn't seeing anything because the sensor wasn't sending a /n character at the end of each reading.  Also converted from BufferedReader to Scanner.  No luck.  I'm fairly convinced now that it's not a problem with my client reading but instead it is somehow sending the command differently from the computer such that it isn't understood by the sensor.

A: Ok, I solved this issue and I think its worth sharing.  After using wireshark I found that the command that worked is substituting STX> and ETX> for \u0002 and \u0003.  These are standard TCP headers and footers.  I manually went into my code to make the substitution and voila! It worked.


text:
Q: Upgrading Facebook Graph API Version I would like to upgrade my Facebook application Graph API version from v2.3 to v2.9 .
I researched my application's usage of the Graph and Marketing APIs, and saw that it is calling the Marketing API with the version explicitly in the url.
Regarding the Graph API, the only config for it's version is in the app Dashboard (in the FB developer dashboard).
If I change the version in the Dashboard - will it affect only the non-explicit calls for the Graph API? or also the explicit calls to the marketing api?


text:
Q: UWP C# How would I Rearrange / Reorder a SQLite Database from a ListView Im currently having a problem with reordering my records / rows in my SQLite Database using the SQLite PCL, I have set up the ListView to be able to drag and reorder items but cant get my head around making them changes appear / save to the database. I haven't found a solid answer around the internet about changing the order of a SQLite Database Table using a ListView.

A: If I understand you correctly, you want users to be able to reorder the list in the way they like and store it that way in the database so that when the user reopens the UWP, the ListView gets ordered in the order they chose?
You can create a new property for eacht item called OrderIndex or something, and use that property when loading in the list for the user. You don't use the ID of the item, you use that property.
By default you could say they are the same, when a user puts one item above or beneath another, they can just swap their OrderIndex value.
I hope this idea inspires you :)


text:
Q: Does the fragment manager restore the last displayed fragment on screen after orientation change? The app consists of an activity (containing a FrameLayout only) and three Fragments (all of them same in structure, have a button but the only difference being different background color).
When the activity is first created, all fragments are put into the FrameLayout one by one by replacing. When we click the button (of the fragment) on the screen, it replaces the current fragment with another fragment.
The problem being that on screen rotation, the activity shows the fragment which was displayed when the app was first started, irrespective of the fragment that was being displayed just before rotation.
Why does this happen? Why isn't the last displayed fragment restored on the screen?
I know that I can use onSavedInstanceState, but more importantly, I want to learn how the FragmentManager works.
The Main Activity:
public class MainActivity extends AppCompatActivity implements ActivityInstance {

    fraga a;
    fragb b;
    fragc c;
    FragmentManager fm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fm = getSupportFragmentManager();

        if (fm.findFragmentByTag("a")!=null){
            a  = (fraga) fm.findFragmentByTag("a");
        }
        else {
            a = new fraga();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.frame, a, "a" );
            ft.commit();
        }

        if (fm.findFragmentByTag("b")!=null){
            b  = (fragb) fm.findFragmentByTag("b");
        }
        else {
            b = new fragb();
            FragmentTransaction fx = fm.beginTransaction();
            fx.add(R.id.frame, b, "b" );
            fx.commit();
        }

        if (fm.findFragmentByTag("c")!=null){
            c  = (fragc) fm.findFragmentByTag("c");
        }
        else {
            c = new fragc();
            FragmentTransaction fl = fm.beginTransaction();
            fl.add(R.id.frame, c, "c" );
            fl.commit();
        }
    }

    public void changefrag(int i) { //This method is called by the fragment
                                     using the ActivityInstance interface
        switch (i){
            case 1: FragmentTransaction f1 = fm.beginTransaction().replace(R.id.frame, a, "a" );
                    f1.commit();
                    break;
            case 2: FragmentTransaction f2 = fm.beginTransaction().replace(R.id.frame, b, "b" );
                    f2.commit();
                    break;
            case 3: FragmentTransaction f3 = fm.beginTransaction().replace(R.id.frame, c, "c" );
                    f3.commit();
                    break;
            default:
                    {Toast.makeText(this, "default", Toast.LENGTH_SHORT).show();}
        }
    }
}

A: The FragmentManager restores the last displayed fragment after orientation change. Looks like you are adding a new fragment after every orientation change from the Activity. So a new fragment is added over the last fragment, which covers the last fragment.
You should add your fragment in onCreate only if the  savedInstanceState is null. savedInstanceState will be null only the first time, it won't be null after orientation change.
if (savedInstanceState == null) {
    // add your fragment
}
// else -  don't add fragment, because all the fragments are restored automatically


text:
Q: TSQL to get next number of rows of data? Normally we use the TSQL TOP to get first number of rows of data like this:
SELECT TOP 10 * FROM myTable;

I am not sure if there is any way to get the next 10 and next 10, ... till to the end, just something paging. I cannot figure out. May be CTE statements?

A: Here's a solution using row_number() in SQL Server 2005:
Paging Records Using SQL Server 2005 Database - ROW_NUMBER Function
... and here's the Google-search I used to find it:
row_number() over paging


text:
Q: Как отправлять данные частями на бекенде? Я захотел сделать музыкальный плеер (golang + react).
Не совсем понимаю, как можно музыку отправить частями (то есть чтоб не сразу вся песня грузилась). Может статьи какие-то почитать можно)


text:
Q: Covert html form to pdf when clicking submit button using php Please Help me out As i m new to php!!
 I have a site with  html form of filling the details of a student.  I need this: when user clicks on  submit button it as to show the details filled in the form in  form of  pdf as well as it as to be sent the same pdf form by e-mail. Please help me with the code how to do this using php.
Thank you

A: you can also try by TCPDF(library) which is currently the most stable version. Here is the clean example of what you are looking for.
<?php

require_once('tcpdf_include.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 049');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 049', PDF_HEADER_STRING);

]$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 10);

$pdf->AddPage();

$html = '
Test TCPDF Methods in HTML

IMPORTANT:

If you are using user-generated content, the tcpdf tag can be unsafe.

You can disable this tag by setting to false the K_TCPDF_CALLS_IN_HTML constant on TCPDF configuration file.

write1DBarcode method in HTML
';

$params = TCPDF_STATIC::serializeTCPDFtagParameters(array('CODE 39', 'C39', '', '', 80, 30, 0.4, array('position'=>'S', 'border'=>true, 'padding'=>4, 'fgcolor'=>array(0,0,0), 'bgcolor'=>array(255,255,255), 'text'=>true, 'font'=>'helvetica', 'fontsize'=>8, 'stretchtext'=>4), 'N'));
$html .= '<tcpdf method="write1DBarcode" params="'.$params.'" />';

$params = TCPDF_STATIC::serializeTCPDFtagParameters(array('CODE 128', 'C128', '', '', 80, 30, 0.4, array('position'=>'S', 'border'=>true, 'padding'=>4, 'fgcolor'=>array(0,0,0), 'bgcolor'=>array(255,255,255), 'text'=>true, 'font'=>'helvetica', 'fontsize'=>8, 'stretchtext'=>4), 'N'));
$html .= '<tcpdf method="write1DBarcode" params="'.$params.'" />';

$html .= '<tcpdf method="AddPage" />
Graphic Functions
';

$params = TCPDF_STATIC::serializeTCPDFtagParameters(array(0));
$html .= '<tcpdf method="SetDrawColor" params="'.$params.'" />';

$params = TCPDF_STATIC::serializeTCPDFtagParameters(array(50, 50, 40, 10, 'DF', array(), array(0,128,255)));
$html .= '<tcpdf method="Rect" params="'.$params.'" />';
$pdf->writeHTML($html, true, 0, true, 0);

$pdf->lastPage();
$pdf->Output('example_049.pdf', 'I');

?>


text:
Q: Porque os pseudo-elementos ::after e ::before não funcionam em um ? Andei testando recentemente os pseudo-elementos ::after e ::before em um elemento  e como resultado não aconteceu absolutamente nada que é o caso do exemplo abaixo usando o ::after:

Um parágrafo qualquer

No Devtools do navegador é possível visualizar que o ::after foi criado, porém o estilo definido no CSS não foi aplicado ao :

Porque isso está acontecendo? Visto que até mesmo páginas internas que estão na mesma origem do site incorporadas no  os pseudo-elementos ::after ou ::before não funcionam.

A: 1º Não dá pra alterar nada nas Páginas de um iframe
2º "Este conteúdo está sobrepondo o de baixo"
ele está sobrepondo o "Um parágrafo qualquer"
porque você alterou a posição de todos os parágrafos da Pág.
para position:relative;. obviavimente os filhos destes parágrafos, no caso as pseudo-classes, vão sobrepor mesmo o elemento pai, pois um elemento filho com position:absolute;, cujo elemento pai tem position:relative;
estes filhos ficarão por cima do elemento pai, isso é regra básica de css.
3º o que você viu no devtools, relacionado a pseudo-classe
do  nada mais era do que apenas as propriedades que você
lançou, mas isso não quer dizer que a pseudo-classe foi criada.
eu posso definir no css de uma página, varias propriedades para uma tag  sem sequer tê-la na página. as propriedades lançadas à tag   vão continuar a aparecer normalmente no devtools.
4º E respondendo sua pergunta, a tag  não aceita pseudo-classes.

A: A princípio eu diria que você não pode modificar nada no conteúdo de um iframe da sua página principal. O máximo que você pode fazer é trabalhar no css as dimensões do iframe.
Segue aqui um link para exemplificação: https://fiodevida.com/como-definir-o-estilo-de-iframes-com-css/


text:
Q: Why is flex-flow: column wrap not working as expected? In this example, I'm trying to use flex-flow: column wrap in tablet media query, to let Section Three fall under Section Two and Section Four fall under Section Three... I'm not sure what I'm doing wrong? Instead, there's a large gap under Section Two.

/* Roboto Font */
@import url('https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700&display=swap');

::-webkit-scrollbar {
  display: none;
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

html {
  height: 100vh;
}

body {
  background-color: lightblue;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  position: relative;
  padding-bottom: 50px;
}

ul {
  padding: 0;
}

ul li {
  list-style: none;
}

img {
  max-width: 100%;
  height: auto;
}

main {
  padding-left: 16px;
  padding-right: 16px;
  display: flex;
  flex-flow: column wrap;
}

@media screen and (min-width: 768px) {
  main {
    flex-flow: row wrap;
    height: 10000px;
  }
}
section {
  margin: 24px 0;
}

@media screen and (min-width: 768px) {
  section {
    flex: 50%;
    padding-left: 16px;
    padding-right: 16px;
  }
}

article p {
  margin: 16px 0;
}

Section One

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Excepturi nisi earum cupiditate error animi nesciunt quas, a possimus enim dignissimos deleniti autem non reiciendis assumenda culpa dolores quis nulla eveniet.

Veritatis at tenetur explicabo reprehenderit adipisci, nisi alias, dolores illum quibusdam fugiat dolorem corrupti facilis aspernatur quae cum odit eveniet, neque quisquam quam suscipit iste. Amet provident cum id quasi!

Nihil quibusdam provident optio unde eaque asperiores est veritatis repudiandae officia distinctio deleniti fuga facere modi ipsam autem cum deserunt, facilis quia accusantium labore illum possimus corporis! Fugiat, mollitia vitae.

Section Two

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Alias eaque, impedit sint nobis dolore non porro accusantium ullam quas eligendi sequi suscipit nemo cumque quisquam ipsa harum nam beatae nesciunt!

Tenetur odit libero in ea odio hic voluptatibus amet officiis. Est unde quae ipsam in veritatis alias at ipsa sapiente delectus neque. Quis officiis minus quibusdam voluptate? Praesentium, recusandae libero.

Quod ipsum fugit saepe nisi at quae iure culpa magni, voluptatibus consectetur enim adipisci quo repellat ad est a eos voluptatem tenetur dolorem dolore! Ab iure tenetur dignissimos laborum officiis!

Section Three

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Alias eaque, impedit sint nobis dolore non porro accusantium ullam quas eligendi sequi suscipit nemo cumque quisquam ipsa harum nam beatae nesciunt!

Tenetur odit libero in ea odio hic voluptatibus amet officiis. Est unde quae ipsam in veritatis alias at ipsa sapiente delectus neque. Quis officiis minus quibusdam voluptate? Praesentium, recusandae libero.

Quod ipsum fugit saepe nisi at quae iure culpa magni, voluptatibus consectetur enim adipisci quo repellat ad est a eos voluptatem tenetur dolorem dolore! Ab iure tenetur dignissimos laborum officiis!

Section Four

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Alias eaque, impedit sint nobis dolore non porro accusantium ullam quas eligendi sequi suscipit nemo cumque quisquam ipsa harum nam beatae nesciunt!

Tenetur odit libero in ea odio hic voluptatibus amet officiis. Est unde quae ipsam in veritatis alias at ipsa sapiente delectus neque. Quis officiis minus quibusdam voluptate? Praesentium, recusandae libero.

Quod ipsum fugit saepe nisi at quae iure culpa magni, voluptatibus consectetur enim adipisci quo repellat ad est a eos voluptatem tenetur dolorem dolore! Ab iure tenetur dignissimos laborum officiis!

Tenetur odit libero in ea odio hic voluptatibus amet officiis. Est unde quae ipsam in veritatis alias at ipsa sapiente delectus neque. Quis officiis minus quibusdam voluptate? Praesentium, recusandae libero.

Quod ipsum fugit saepe nisi at quae iure culpa magni, voluptatibus consectetur enim adipisci quo repellat ad est a eos voluptatem tenetur dolorem dolore! Ab iure tenetur dignissimos laborum officiis!


text:
Q: Gradle binding dependency configuration with a task
I'm completely new with Gradle. For beginning, I am trying to create a build script for simple console Java application, without using java plugin. There are only two dependencies in my code from maven repository.
So, my build contains one task, which extends JavaCompile, in which I specify classpath, destination, ect.
My project doesn't apply java plugin, therefore I need to create dependency configuration by my own, like this:
    configurations {
      myCompile {
      desciprtion = 'my own compile dependency configuration'
      transitive = true
      }
 }

Then I can bind dependencies on this configuration:
dependencies {
myCompile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.7'
myCompile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.7'
}

As far as i understand, after that I must bind those configuration with my compile action, but I can't figure out how. Can someone point this out to me?
Any help will be really appreciated)
P.S. I have read this In Gradle, associating task with a dependency configuration, and there is mentioned sourcesets. So, I can create sourceset myThing, and task with configuration will be created for me? Will this work without java plugin?
P.P.S. I want to achieve this simple task without plugins just for the purpose of learning Gradle, and it's basic tools :)

A: First create the compilation task using an exec task type, see DSL refreence for Exec.
When you create your compilation task, you can get a reference to the configuration using getAsPath(), see API doc for FileCollection
configurations.myCompile.getAsPath()

But seriously, I do recommend that you apply the java plugin for this.
If you feel the need tor a quick beginner course, try this video.

A: Eventually, I used this code to compile project without java plugin:
task resolveCompileDependency(type: Copy) {
    //download libraries specified in dependency configuration
    def lib_files = configurations.myCompile.resolve()
    //print names of downloaded files and copy to build directory (optional)
    lib_files.each {File file ->
        println file.name
    }
    from lib_files
    into 'build/classes'
    outputs.files(lib_files)
}

And compile task is just ordinary JavaCompile task, which depends on resolveCompileDependency. Hope this will help someone.


text:
Q: localStorage on javascript leads refreshing I am trying to fire out the user when idle, using javascript across tabs, the below code working fine for single tab for multiple tab it is not working properly
For Eg: I have set 10 secs as idle time and left the first tab it throws out the user on 10 seconds, assume i opened the first tab at 00:00:05 hours and opened second tab at 00:00:10 hours and working on second tab for 00:00:13 hours and left both the tabs the project have to logout on 00:00:23 right? but it logs out on 00:00:15, I don't know whats happening right here, if it was not refreshing properly how could it stay on second tab for a long time when i am using it? if it is refreshing properly how could it log me out based on first opened tab, and the code as follows.
<script>
var IDLE_TIMEOUT = 10; //seconds
localStorage.setItem("setTimeOut", "0");

document.onclick = function () {
    localStorage.setItem("setTimeOut", "0");
};

document.onmousemove = function () {
    localStorage.setItem("setTimeOut", "0");
};

document.onkeypress = function () {
    localStorage.setItem("setTimeOut", "0");
};

document.onfocus = function () {
    localStorage.setItem("setTimeOut", "0");
};

window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
    localStorage.setItem("setTimeOut", parseInt(localStorage.getItem("setTimeOut"))+1);
    if (localStorage.getItem("setTimeOut") >= IDLE_TIMEOUT) {
        alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}
</script>

A: This line will run every second for each instance of your app (tab). That means that if you have 2 tabs open, then its incrementing by 2 every second instead of 1.
localStorage.setItem("setTimeOut", parseInt(localStorage.getItem("setTimeOut"))+1);

You can fix this by using a specific time when the user will be logged out, rather than a countdown.

A: Instead of incrementing the value each second on each tab, which means every second it will be increased with the number of tabs open rather than 1 second, simply set the current time on interaction and then compare to that every second.
So, in your event handlers, do this instead:
localStorage.setItem("lastInteraction", Date.now())

... and then in your CheckIdleTime() function, remove the localStorage.setItem() and change your if condition to this:
Number(localStorage.getItem("lastInteraction")) + (IDLE_TIMEOUT * 1000) < Date.now()

The condition takes the time when the last interaction occurred, adds the timeout constant and then checks if the current time (now) has passed that value.


text:
Q: How to downgrade Xcode without apple developer account? I've recently upgraded my Xcode to 6.3.
Now I'm experiencing a lot of errors in my project, which I'm not capable of debugging.
Is it possible to downgrade it to 6.2 version if I don't have Apple Developer account?

A: go into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Actually there is no need to "downgrade". Just download Xcode 6.2 from the Apple developer download pages, and install it. Give it a name different from Xcode 6.3's name (e.g. call it "Xcode 6.0.2") and they can happily live side by side.
link : https://developer.apple.com/downloads/index.action?name=Xcode

A: You can download XCode 6.2 from developer.apple.com and can install it along with 6.3. You don't even need to remove 6.2. While installing 6.2  it will ask to replace, stop or keep both, so click both and you will have both version of xcode installed. While opening your project right click on xcodeproj file and select the xcode 6.2 version.
I have 2-3 version of xcode installed on my machine like 5.0, 6.2 and 6.3. Though this will slow your machine so won't recommend that

A: Enjoy version 6.2 Click here to download
You can change the version now and can download any of them.


text:
Q: MongoDB: Querying an array with a reference I am new to MongoDB and I have a problem. Lets assume I have the following documents:
db.users.insert({
forname: 'John',
surname: 'Smith',
DOB: 12061989,

streaming: [{media_content_id: 5000, stream_min: 45, stream_date: 10042015},
            {media_content_id: 5001, stream_min: 45, stream_date: 10042015}]
});

db.media_content.insert({
_id: 5000,
content_name: 'FILM B',
durations_min: 45,
content_type_price: {
                    min_price: 0.002,
}
});

db.media_content.insert({
_id: 5001,
content_name: 'FILM B',
durations_min: 45,
media_type: 'video',
content_type_price: {
                    min_price: 0.002,
}
});

I would like to have a query that shows which films user John Smith have streamed. As it can be seen the references are embedded in the arrays (within streaming). Does anybody have an idea how to do this?
Thanks for your help!

A: You can use the cursor method forEach() to iterate the cursor and access the documents, as in the following example:
var firstName = "John",
    lastName = "Smith";

db.users.find({"forname" : firstName, "surname" : lastName}).forEach( function(doc){
    doc.streaming.forEach(function (stream){
        var movie = db.media_content.findOne({"_id": stream.media_content_id});
        print(firstName + " " + lastName + " watched " + movie.content_name + " for " + stream.stream_min + " minutes");
    });
});

Output
John Smith watched FILM B for 45 minutes
John Smith watched FILM B for 45 minutes


text:
Q: Bitwise Operations-- How to change existing color? I have read up on bitwise operators (& | ^) and I understand that if I were to do:
alpha = 0xFF000000 >> 24 ;
blue = 0xFF0000FF & 0x000000FF;
red = 0xFFFF0000>>16 & 0x000000FF;
green = 0xFF00FF00>>8 & 0x000000FF;

then I can mask the other colors and just have red or blue(etc...) components
and if I were to do
int color = alpha | blue | red | green;

then I re-construct the color again so to speak. What I am curious about is what if I wanted to create a bilinear interpolation between two colors in Java. How would I go about constructing it?
I would like to start with the standard green color( 0xFF00FF00) and end with black (0xFF000000), the colors in the middle would be change from green to darker greens until it eventually gets to black. I think that I would have to do something where I create a bufferedImage which starts off as green at the top and then maybe create a for loop that would read the color of the previous pixel and then shift something until a new version of the previous color is created and so forth. Unfortunately I am not sure how to implement this because I understand bitwise operations and shifts in theory but am not sure how to apply them for this purpose. Any help would be greatly appreciated! Thank you in advance!

A: As EJP noted the masks are used to filter out the values for one of the color components/channels (Red, Green, Blue). And that's usually what you do with bit shift/masking operations. Everything else you do with the values you get is arithmetics or more advanced math.
A color channel's range is 0-255, or 0x00 - 0xFF in hexadecimal values. To reconstruct it, you need to bitshift the components value back to their place. Which can be put together with simple arithmetic addition:
// Example values
int r = 255; // 0xFF
int g = 1;   // 0x01
int b = 15;  // 0x0F

// go back to original form:
                      //    A  R  G  B
int color = r << 16;  // 0x00.FF.00.00
color += g << 8;      // 0x00.FF.01.00
color += b;           // 0x00.FF.01.0F

// just add back the alpha if it is going to be full on
color = += 255 << 24; // 0xFF.FF.01.0F

If you want to do some interpolation between colors you need to do it for each color component seperately, not all of them together in one integer. In some instances it may also a good idea to change the representation from [0-255] to a decimal one [0.0f-1.0f]:
// Darken red value by 50%
int color = ...; // some color input
int mask = 0xFF;

int a = (color >> 24) & mask;
int r = (color >> 16) & mask;
int g = (color >> 8) & mask;
int b = color & mask;

// convert to decimal form:
float rDecimal = r / 255f;
  // Let r: 0x66 = 102 => rDecimal: 0.4

// darken with 50%, basically divide it by two
rDecimal = r/2;
  // rDecimal: 0.2

// Go back to original representation and put it back to r
r = (int)(rDecimal * 255);
  // r: 51 = 0x33

// Put it all back in place
color = (a << 24) + (r << 16) + (g << 8) + b;

Hope this helps out.

A:
I understand that if I were to do:

No, you don't understand at all. The result of all your bitshifting is 0xff in all four cases, which is self-evidently incorrect. The alpha mask is 0xff000000, the blue mask is 0xff, the red mask is 0xff0000, the green mask is 0xff00. These are masks, which need to be applied to the actual pixel, with the & operator, to mask out the relevant channels. You need to understand that before you can go any further.


text:
Q: Excel VBA checking for dots Hopefully, someone can help me with this!
I have a worksheet, in this worksheet, I have first names in column C.
So I need a script/macro which gets the first letter and put it in column B with a dot. (for example, the first name is Dave in column C, it needs to put the letter D in column B with a dot, for example, D.
Also, I would like that column B get checked so there aren't any double dots.
Is this even possible?
I know I can get the first letter with =LEFT(C1), but I'm trying to automate this with a script/macro.
And I found also out I can create dots in front of the letters with:
Sub AddDotAfter()
    Dim cell As Range
    For Each cell In Selection
        If cell.Value <> "" Then
            cell.Value = cell.Value & "."
        Else: cell.Value = cell.Value
        End If
    Next cell
End Sub

Hope there is someone who can help me! Ty in advance!

A: Check out the Range.Offset property in combination with the Left function:
Sub AddDotAfter()
    Dim cell As Range
    For Each cell In Selection
        If cell.Value <> "" Then
            cell.Offset(ColumnOffset:=-1).Value = Left$(cell.Value, 1) & "."
        End If
    Next cell
End Sub