text:
Q: How can i add UISplitViewController To UINavigationController? In my application. I have to use UISplitViewController and I want to do add UISplitViewController To UINavigationController but I can't do this.
I also know that inheritance of UISplitViewController is not possible. but it very important for me to add in UINavigationController.
Thanks in advance :)

A: Note: a UISplitViewController must be the root view of an app (or perhaps more specifically, a window). It can not live inside a UINavigationController or anything else.
refer can-a-uisplitviewcontroller-be-the-root-controller-in-a-uinavigationcontroller link

A: I've been able to do this using the open source MGSplitViewController.

A: You can add MGSplitViewController in delegate like :- in .m file
    self.splitViewController = [[[MGSplitViewController alloc] init] autorelease];

    //
    MasterPage *aMasterPage = [[[MasterPage alloc] initWithNibName:@"MasterPage" bundle:[NSBundle mainBundle]] autorelease];

    aMasterPage.splitViewController = self.splitViewController;
    self.splitViewController.delegate = aMasterPage;

    UINavigationController *navCntrl = [[[UINavigationController alloc] aMasterPage] autorelease];
    [navCntrl.navigationBar setBarStyle:UIBarStyleBlackOpaque];

    DetailPage *aDetailPage = [[[DetailPage alloc] initWithNibName:@"DetailPage" bundle:[NSBundle mainBundle]] autorelease];

    UINavigationController *navCntrl2 = [[[UINavigationController alloc] initWithRootViewController:aDetailPage] autorelease];

    [navCntrl2.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    [self.splitViewController setViewControllers:[NSArray arrayWithObjects:navCntrl, navCntrl2, nil]];

    [self.window addSubview:self.splitViewController.view];

A: Refer this Q&A - Is it possible to implement a Split View Controller within a Navigation Controller in an iOS app?
This violates Apples guidelines (https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/SplitViewControllers.html#//apple_ref/doc/uid/TP40011313-CH7)
A split view controller must always be the root of any interface you create. In other words, you must always install the view from a UISplitViewController object as the root view of your application's window. The panes of your split view interface may then contain navigation controllers, tab bar controllers, or any other type of view controller you need to implement your interface. Split view controllers cannot be presented modally.


text:
Q: android opencv crop top image portion with opencv i want crop top image portion and written this code.
// crop image
Integer halfWidth = width / 2;
Integer HalfHeight = height / 2;
Integer startX = halfWidth - (halfWidth / 2);
Mat mRgba = new Mat(HalfHeight, halfWidth, CvType.CV_8UC1);
Rect roi = new Rect(0, HalfHeight, width, height);

At result i got this result and my program shutdown.
Mat [ 360*480*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x5c54da18, dataAddr=0x60aa8010 ]
1549064728
{0, 360, 960x720}

My old object higher than first. How i can fix them?

A: From the code you provide, I can guess that your ROI should be:
Rect roi = new Rect(0, HalfHeight, width, height-HalfHeight);

A: My full code
protected void calculate(int width, int height, byte[] data)
    {
        Mat mYuv = new Mat(height + height / 2, width, CvType.CV_8UC1);
        Mat thresholdImage = new Mat(height + height / 2, width, CvType.CV_8UC1);
        mYuv.put(0, 0, data);
        // crop image
        Integer halfWidth = width / 2;
        Integer HalfHeight = height / 2;
        Integer startX = halfWidth - (halfWidth / 2);
        Mat mRgba = new Mat(HalfHeight, halfWidth, CvType.CV_8UC1);
        Rect roi = new Rect(0, HalfHeight, width, height-HalfHeight);
        mRgba = new Mat(mRgba, roi);
        Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV420p2BGR, 4);
        //convert to grayscale
        Imgproc.cvtColor(mRgba, thresholdImage, Imgproc.COLOR_mRGBA2RGBA, 4);
//       Perform a Gaussian blur (convolving in 5x5 Gaussian) & detect edges
        //Imgproc.GaussianBlur(mRgba, mRgba, new Size(5,5), 2.2, 2);
        Imgproc.Canny(mRgba, thresholdImage, VActivity.CANNY_MIN_TRESHOLD, VActivity.CANNY_MAX_THRESHOLD);
        Mat lines = new Mat();

        double rho = 0.15;
        double theta = Math.PI/180;
        int threshold = 50;

        //do Hough transform to find lanes
        Imgproc.HoughLinesP(thresholdImage, lines, rho, theta, threshold, VActivity.HOUGH_MIN_LINE_LENGTH, VActivity.HOUGH_MAX_LINE_GAP);
        for (int x = 0; x < lines.cols() && x < 5; x++)
        {
            double[] vec = lines.get(0, x);
            double x1 = vec[0],
                    y1 = vec[1],
                    x2 = vec[2],
                    y2 = vec[3];
            Point start = new Point(x1, y1);
            Point end = new Point(x2, y2);

            Core.line(mRgba, start, end, new Scalar(255, 0, 0), 3);
        }

        if (bitmap == null)
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        Utils.matToBitmap(mRgba, bitmap);

        drawThread.setBitmap(bitmap);
    }

And got same error. Maybe in this i need send another params or just clone to mRgba
Mat mRgba = new Mat(HalfHeight, halfWidth, CvType.CV_8UC1);
        Rect roi = new Rect(0, HalfHeight, width, height-HalfHeight);
        mRgba = new Mat(mRgba, roi);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it problematic to request the server on every character typed in? In my frontend I have an input-field that sends an ajax request on every character typed in (using vue.js) to get realtime-filtering (can't use vue filter because of pagination).
Everything works smooth in my test environment, but could this lead to performance issues on (a bigger amount of) real data and if so, what can I do to prevent this?

A: I actually discuss this exact scenario in my Vue.js training course. In short, you may want to wait until a user clicks a button or something of that nature to trigger sending the request. Another approach to consider is to use the lazy modifier, which will delay the event until the change event is fired.
It's hard to know the correct approach without knowing more about the goals of the app. Still, the options listed above are two options to consider.
I hope this helps.

A: Is it problematic?
Yes.

*

*The client will send a lot of requests. Depending on the network connection and browser, this could lead to a perceptible feeling of lag by the client.

*The server will receive a lot of requests, potentially leading to degraded performance for all clients, and extra usage of resources on the server side.

*Responses to requests have a higher chance of arriving out of order. If you send requests very fast, it has increased chances of being apparent (e.g. displaying autocomplete for "ab" when the user has already typed "abc")

Overall, it's bad practice mostly because it's not necessary to do that many requests.
How to fix it?
As J. B. mentioned in his answer, debouncing is the way to go.
The debounce function (copied below) ensures that a certain function doesn't get called more than once every X milliseconds. Concretely, it allows you to send a request as soon as the user hasn't typed anything for, say, 200ms.
Here's a complete example (try typing text very fast in the input):

function debounce(func, wait, immediate) {
 var timeout;
 return function() {
  var context = this, args = arguments;
  var later = function() {
   timeout = null;
   if (!immediate) func.apply(context, args);
  };
  var callNow = immediate && !timeout;
  clearTimeout(timeout);
  timeout = setTimeout(later, wait);
  if (callNow) func.apply(context, args);
 };
}

var sendAjaxRequest = function(inputText) {
    // do your ajax request here
    console.log("sent via ajax: " + inputText);
};

var sendAjaxRequestDebounced = debounce(sendAjaxRequest, 200, false); // 200ms

var el = document.getElementById("my-input");
el.onkeyup = function(evt) {
    // user pressed a key
    console.log("typed: " + this.value)
    sendAjaxRequestDebounced(this.value);
}
<input type="text" id="my-input">

For more details on how the debounce function works, see this question

A: The mechanism I was searching for is called debouncing.
I used this approach in the application.


text:
Q: 4-dimensions data became 2 dimensions after going throught convolutional neuron network I am training a neuron network with two types of input: image and BR (blue over red, it's kind of a non-image feature like height, weight...). To do that, i use fit function in keras, and convert image to list for input. But I don't know why the image list, which have 4 dimensions shape became 2 dimemsions when going into fit, and I got the error as below:

Error when checking input: expected dense_1_input to have 3
  dimensions, but got array with shape (1630, 1)

When I converted the image list to array, I had checked the shape of image_array and it has exactly 4 dimensions (particularly its shape is 1630, 60, 60, 3). Even right before the fit function, it still has the same shape. So I really don't know why the shape became (1630,1). Could anyone explain for me?
Here is my code:
from keras.utils.np_utils import to_categorical
import pandas as pd
import numpy as np
import os
from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Input, Activation, Dropout, Flatten, Dense,Concatenate, concatenate,Reshape, BatchNormalization, Merge
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.optimizers import Adagrad
from sklearn import preprocessing
from scipy.misc import imread
import time
from PIL import Image
import cv2
img_width, img_height = 60, 60
img_list = []
BR_list = []
label_list = []
data_num = 1630

folder1 = "cut2/train/sugi/"

folder2 = "cut2/train/hinoki/"

def imgConvert(file_path):
    img = imread(file_path,flatten = True)
    img = np.arange(1*3*60*60).reshape((60,60,3))
    img = np.array(img).reshape(60,60,3)
    img = img.astype("float32")
    return img

def B_and_R(img_path):
    img = cv2.imread(img_path)
    B = 0
    R = 0

    for i in range(25,35):
    #print(i)
        for j in range(25,35):
            B = B+img[i,j,0]
            R = R+img[i,j,2]
        #(j)
        #(img[i,j])

    ave_B = B/100
    ave_R = R/100

    BR = ave_B/ave_R
    return BR

def getData(path,pollen):
    for the_file in os.listdir(path):
        #print(the_file)
        file_path = os.path.join(path, the_file)
        B_over_R = B_and_R(file_path)
        img_arr = imgConvert(file_path)
        #writer.writerow([img_arr,B_over_R,"sugi"])
        img_list.append(img_arr)
        BR_list.append(B_over_R)
        lb = np.zeros(2)
        if pollen == "sugi":
            lb[0] +=1
        else:
            lb[1] +=1
        label_list.append(lb)

if __name__ == '__main__':

    getData(folder1,"sugi")
    getData(folder2,"hinoki")

    img_arr = np.array(img_list)
    print(img_arr.shape)
    #.reshape(img_list[0],1,img_width,img_height)
    img_arr.astype("float32")
    img_arr /= 255
    print(img_arr.shape)
    img_array = np.expand_dims(img_arr, axis = 0)
    img_array = img_array[0,:,:,:,:]
    print(img_array.shape)

    """
    datagen = ImageDataGenerator(
        featurewise_center=True,
        featurewise_std_normalization=True,
        rotation_range=20,
        width_shift_range=0.2,
        height_shift_range=0.2,
        horizontal_flip=True)
    datagen.fit(img_array)
    """
    #img_array = img_array.reshape(img_array[0],1,img_width,img_height)

    print(img_array.shape)
    label_arr = np.array(label_list)
    print(label_arr.shape)
    #label_array = np.expand_dims(label_arr, axis = 0)
    #label_array = label_array[0,:,:,:,:]

    BR_arr = np.array(BR_list)
    print(BR_arr.shape)
    #BR_array = np.expand_dims(BR_arr, axis = 0)
    #BR_array = BR_array[0,:,:,:,:]

    #print(len([img_arr,BR_arr]))

    input_tensor = Input(shape=(img_width, img_height,3))
    vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)

    # FC層の作成
    top_model = Sequential()
    top_model.add(Flatten(input_shape=vgg16.output_shape[1:]))

#print(top_model.summary())

    # VGG16とFC層を結合してモデルを作成
    branch1 = Model(input=vgg16.input, output=top_model(vgg16.output))
#model.summary()
    print(branch1.summary())

    branch2 = Sequential()
    branch2.add(Dense(1, input_shape=(data_num,1), activation='sigmoid'))
    #branch1.add(Reshape(BR.shape, input_shape = BR.shape))
    branch2.add(BatchNormalization())
    branch2.add(Flatten())

    print(branch2.summary())
    merged = Merge([branch1, branch2], mode = "concat")

    model = Sequential()
    model.add(merged)
    model.add(Dense(256, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(2, activation='softmax'))

   #last_model = Model(input = [branch1.input,branch2.input],output=model())
    print(model.summary())
    model.compile(loss='categorical_crossentropy',
              optimizer=optimizers.SGD(lr=1e-3, momentum=0.9),
              metrics=['accuracy'])
    print(img_array.shape)
    model.fit([img_array,BR_arr], label_arr,
            epochs=5, batch_size=100, verbose=1)

A: Ok, then the problem is the input shape.
While your data for branch 2 is 2D (batch, 1), your model should also have a 2D input: input_shape = (1,). (Batch sizes are ignored in input_shape)


text:
Q: How do I fire a custom event in SWT? I am building an application in swt, I also have a thread running which polls the database for any changes (made directly to the db or by another application).
I am able to pick up the changes but I now need to tell my interface to refresh, I tried calling the objects refresh method (that I made) directly from the thread but I get an SWTException "Invalid Thread Access".
Is there a way to create my own event inside the thread which can then be manually fired upon finding a change on the database, which is then picked up by the class that needs to be refreshed.
I have looked at SWT events but I can only seem to find ones which are attached to widgets and can only be fired through the widget itself...
Thanks!

A: You need to update the user interface from the user-interface thread.
One way to do that is to use one of these methods on the org.eclipse.swt.widgets.Display class:
Display.getDefault().syncExec( new Runnable() { ... } );

or:
Display.getDefault().asyncExec( new Runnable() { ... } );


text:
Q: Python: Only keep section of string after second dash and before third dash I have a column 'Id' that has data like this:
'10020-100-700-800-2'
How can I create a new column that would only contain the third number, in this case 700, for each row?
Here is an example dataframe:
d = {'id': {0: '10023_11_762553_762552_11', 1: '10023_14_325341_359865_14', 2: '10023_17_771459_771453_17', 3: '10023_20_440709_359899_20', 4: '10023_24_773107_625033_24', 5: '10023_27_771462_771463_27', 6: '10023_30_771262_771465_30', 7: '10023_33_761971_762470_33'}, 'values': {0: 10023, 1: 10023, 2: 10023, 3: 10023, 4: 10023, 5: 10023, 6: 10023, 7: 10023}}

A: Use str.split and take the third argument of the list:
df = pd.DataFrame({'Col': ['10020-100-700-800-2']})
df['NewCol'] = df['Col'].str.split('-').str[2].astype(int)
print(df)

# Output
                   Col  NewCol
0  10020-100-700-800-2     700

Update with your sample:
data = {'Id': ['10020-100-700-800-2',
       '10022-400-900-900-2',
       '10045-600-800-900-3',
       '10000-300-400-300-3',
       '10020-200-200-200-2'],
      'Employed': [1, 0, 0, 1, 1],
      'Name': ['Alan', 'Joe', 'Sam', 'Amy', 'Chloe']}
df = pd.DataFrame(data)

df['Id2'] = df['Id'].str.split('-').str[2].astype(int)
print(df)

# Output
                    Id  Employed   Name  Id2
0  10020-100-700-800-2         1   Alan  700
1  10022-400-900-900-2         0    Joe  900
2  10045-600-800-900-3         0    Sam  800
3  10000-300-400-300-3         1    Amy  400
4  10020-200-200-200-2         1  Chloe  200

Update 2 with your new data
data = {'id': ['10023_11_762553_762552_11',
               '10023_14_325341_359865_14',
               '10023_17_771459_771453_17',
               '10023_20_440709_359899_20',
               '10023_24_773107_625033_24',
               '10023_27_771462_771463_27',
               '10023_30_771262_771465_30',
               '10023_33_761971_762470_33'],
        'values': [10023, 10023, 10023, 10023, 10023, 10023, 10023, 10023]}
df = pd.DataFrame(data)

df['id2'] = df['id'].str.split('_').str[2].astype(int)
print(df)

# Output
                          id  values     id2
0  10023_11_762553_762552_11   10023  762553
1  10023_14_325341_359865_14   10023  325341
2  10023_17_771459_771453_17   10023  771459
3  10023_20_440709_359899_20   10023  440709
4  10023_24_773107_625033_24   10023  773107
5  10023_27_771462_771463_27   10023  771462
6  10023_30_771262_771465_30   10023  771262
7  10023_33_761971_762470_33   10023  761971


text:
Q: How can i list the files from DDMS? I've some files in this location data/data/com.android/file/...   I'm having one listview and one button in my layout and am extends Activity only. How can i fetch those files from DDMS and display that by items. Anyone know this?

A: I'm going to assume that com.android is your package name. If that is the case, you access these files by doing the following
String [] files = fileList();

fileList() is an existing method for your activity so you don't have to write it. This will return to you a list of all private files associated with your application because /data/data/<package name>/files/... is where the application saves your private files.
To populate the listView, I would follow the guide here: example
That tutorial explains exactly how to create a list view using a String array. So where you have the line
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));

Substitute COUNTRIES with files.
Hope that helps out.

A: try this one,
ArrayList<String> list_files = fileList();

private ArrayList<String> fileList(){

private ArrayList<String> filesList=new ArrayList<String>();

      File dir=new File("data/data/com.android/file");

      File[] files=dir.listFiles();

     for(File f:files){
           filesList.add(f.getName());
       }

 }

then use list view and adapter class to list these arraylist file names in usual way.


text:
Q: Compilation headers for 64-bit ARM64 Raspberry Pi for Yate? When I try to compile Nuand's Yate software on 64-bit (ARM64) Ubuntu 21.04 on a Raspberry Pi 4, I get architecture support headers errors:
~/software/bts/yate$ make
make -C ./engine all
make[1]: Entering directory '/home/parallels/software/bts/yate/engine'
make[1]: Nothing to be done for 'all'.
make[1]: Leaving directory '/home/parallels/software/bts/yate/engine'
make -C ./modules all
make[1]: Entering directory '/home/parallels/software/bts/yate/modules'
make -C ../libs/miniwebrtc
make[2]: Entering directory '/home/parallels/software/bts/yate/libs/miniwebrtc'
g++ -Wall   -I. -I./audio/common/processing -I./audio/common/vad -I./audio/processing/aec -I./audio/processing/aecm -I./audio/processing/agc -I./audio/processing/ns -I./audio/processing/utility -I./system_wrappers -O2 -Wno-overloaded-virtual  -fno-exceptions -fPIC -DHAVE_GCC_FORMAT_CHECK -DHAVE_BLOCK_RETURN  -DWEBRTC_NS_FLOAT=true -c -o audio/common/resampler/resampler.o audio/common/resampler/resampler.cc
In file included from ./audio/common/processing/signal_processing_library.h:22,
                 from audio/common/resampler/resampler.cc:19:
./typedefs.h:104:2: error: #error Please add support for your architecture in typedefs.h
  104 | #error Please add support for your architecture in typedefs.h
      |  ^~~~~
make[2]: *** [Makefile:263: audio/common/resampler/resampler.o] Error 1
make[2]: Leaving directory '/home/parallels/software/bts/yate/libs/miniwebrtc'
make[1]: *** [Makefile:448: ../libs/miniwebrtc/libminiwebrtc.a] Error 2
make[1]: Leaving directory '/home/parallels/software/bts/yate/modules'
make: *** [Makefile:186: modules] Error 2

When I check the typedefs.h header, I see arm64 support is not added yet:
/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// This file contains platform-specific typedefs and defines.
#ifndef WEBRTC_TYPEDEFS_H_
#define WEBRTC_TYPEDEFS_H_

// Reserved words definitions
// TODO(andrew): Look at removing these.
#define WEBRTC_EXTERN extern
#define G_CONST const
#define WEBRTC_INLINE extern __inline

// Define WebRTC preprocessor identifiers based on the current build platform.
// TODO(andrew): Clean these up. We can probably remove everything in this
// block.
//   - TARGET_MAC_INTEL and TARGET_MAC aren't used anywhere.
//   - In the few places where TARGET_PC is used, it should be replaced by
//     something more specific.
//   - Do we really support PowerPC? Probably not. Remove WEBRTC_MAC_INTEL
//     from build/common.gypi as well.
#if defined(WIN32)
    // Windows & Windows Mobile.
    #if !defined(WEBRTC_TARGET_PC)
        #define WEBRTC_TARGET_PC
    #endif
#elif defined(__APPLE__)
    // Mac OS X.
    #if defined(__LITTLE_ENDIAN__ )
        #if !defined(WEBRTC_TARGET_MAC_INTEL)
            #define WEBRTC_TARGET_MAC_INTEL
        #endif
    #else
        #if !defined(WEBRTC_TARGET_MAC)
            #define WEBRTC_TARGET_MAC
        #endif
    #endif
#else
    // Linux etc.
    #if !defined(WEBRTC_TARGET_PC)
        #define WEBRTC_TARGET_PC
    #endif
#endif

// Derived from Chromium's build/build_config.h
// Processor architecture detection.  For more info on what's defined, see:
//   http://msdn.microsoft.com/en-us/library/b0084kay.aspx
//   http://www.agner.org/optimize/calling_conventions.pdf
//   or with gcc, run: "echo | gcc -E -dM -"
// TODO(andrew): replace WEBRTC_LITTLE_ENDIAN with WEBRTC_ARCH_LITTLE_ENDIAN?
#if defined(_M_X64) || defined(__x86_64__)
#define WEBRTC_ARCH_X86_FAMILY
#define WEBRTC_ARCH_X86_64
#define WEBRTC_ARCH_64_BITS
#define WEBRTC_ARCH_LITTLE_ENDIAN
#elif defined(_M_IX86) || defined(__i386__)
#define WEBRTC_ARCH_X86_FAMILY
#define WEBRTC_ARCH_X86
#define WEBRTC_ARCH_32_BITS
#define WEBRTC_ARCH_LITTLE_ENDIAN
#elif defined(__ARMEL__)
// TODO(andrew): We'd prefer to control platform defines here, but this is
// currently provided by the Android makefiles. Commented to avoid duplicate
// definition warnings.
//#define WEBRTC_ARCH_ARM
// TODO(andrew): Chromium uses the following two defines. Should we switch?
//#define WEBRTC_ARCH_ARM_FAMILY
//#define WEBRTC_ARCH_ARMEL
#define WEBRTC_ARCH_32_BITS
#define WEBRTC_ARCH_LITTLE_ENDIAN
#elif defined(__mips__)
#define WEBRTC_ARCH_32_BITS
#define WEBRTC_BIG_ENDIAN
#elif defined(__powerpc64__)
#define WEBRTC_ARCH_PPC64 1
#define WEBRTC_ARCH_64_BITS
#ifdef __LITTLE_ENDIAN__
#define WEBRTC_ARCH_LITTLE_ENDIAN
#define WEBRTC_LITTLE_ENDIAN
#else
#define WEBRTC_ARCH_BIG_ENDIAN
#define WEBRTC_BIG_ENDIAN
#endif
#elif defined(__powerpc__)
#define WEBRTC_ARCH_PPC 1
#define WEBRTC_ARCH_32_BITS
#ifdef __LITTLE_ENDIAN__
#define WEBRTC_ARCH_LITTLE_ENDIAN
#define WEBRTC_LITTLE_ENDIAN
#else
#define WEBRTC_ARCH_BIG_ENDIAN
#define WEBRTC_BIG_ENDIAN
#endif

#else
#error Please add support for your architecture in typedefs.h
#endif

#if defined(__SSE2__) || defined(_MSC_VER)
#define WEBRTC_USE_SSE2
#endif

#if defined(WEBRTC_TARGET_PC)

#if !defined(_MSC_VER)
  #include <stdint.h>
#else
    // Define C99 equivalent types.
    // Since MSVC doesn't include these headers, we have to write our own
    // version to provide a compatibility layer between MSVC and the WebRTC
    // headers.
    typedef signed char         int8_t;
    typedef signed short        int16_t;
    typedef signed int          int32_t;
    typedef signed long long    int64_t;
    typedef unsigned char       uint8_t;
    typedef unsigned short      uint16_t;
    typedef unsigned int        uint32_t;
    typedef unsigned long long  uint64_t;
#endif

#if defined(WIN32)
    typedef __int64             WebRtc_Word64;
    typedef unsigned __int64    WebRtc_UWord64;
#else
    typedef int64_t             WebRtc_Word64;
    typedef uint64_t            WebRtc_UWord64;
#endif
    typedef int32_t             WebRtc_Word32;
    typedef uint32_t            WebRtc_UWord32;
    typedef int16_t             WebRtc_Word16;
    typedef uint16_t            WebRtc_UWord16;
    typedef char                WebRtc_Word8;
    typedef uint8_t             WebRtc_UWord8;

    // Define endian for the platform
    #define WEBRTC_LITTLE_ENDIAN

#elif defined(WEBRTC_TARGET_MAC_INTEL)
    #include <stdint.h>

    typedef int64_t             WebRtc_Word64;
    typedef uint64_t            WebRtc_UWord64;
    typedef int32_t             WebRtc_Word32;
    typedef uint32_t            WebRtc_UWord32;
    typedef int16_t             WebRtc_Word16;
    typedef char                WebRtc_Word8;
    typedef uint16_t            WebRtc_UWord16;
    typedef uint8_t             WebRtc_UWord8;

    // Define endian for the platform
    #define WEBRTC_LITTLE_ENDIAN

#else
    #error "No platform defined for WebRTC type definitions (typedefs.h)"
#endif

#endif  // WEBRTC_TYPEDEFS_H_

So I reported this error to manufacturer Nuand, but they were not responding quickly on how to resolve these issues. So if I would add support for the raspberry pi manually, What's the correct way to add support for ARM64 without resulting into errors after compilation?
I tried:
#elif defined(__aarch64__)
#define WEBRTC_ARCH_64_BITS
#define WEBRTC_ARCH_LITTLE_ENDIAN

But it didn't result into a working Yate binary:
make[1]: Leaving directory '/home/yate/yate-rc-2/yate/conf.d'
make: *** [Makefile:259: install-api] Error 1


text:
Q: Why the input capacitance value decrease as the input voltage increases? Following is the screenshot of the logic CMOS-inverter curve (Input capacitance vs voltage).
Why the input capacitance decreases with the increase of input voltage?

A: A reverse-biased semiconductor diode's capacitance is a function of voltage. This effect is used in the varactor or varicap diode, a voltage-dependent capacitor. Wikipedia has an illustration of this, showing that increasing bias narrows the depletion zone, decreasing capacitance.

A: Sincw these input_capacitance spikes are occurring, in each case, at VDD/2 where typical CMOS inverter designs have Nchan and Pchan conductances tweaked via W/L to operate, I suspect these spikes are

*

*MILLER EFFECT capacitance multiplication

and the FET's gate_drain overlap capacitances are modulated by higher and higher voltages at the drain.

A: The Philips NXP Nexperia HC(T) User Guide says:

7.6 Input capacitance
… is specified as
3.5 pF (typ.) and comprises package, bonding
pad/interconnecting track, input protection diode and
transistor gate capacitances. […]
The initial decrease in capacitance as VI rises
from zero or falls from 5 V is due to increased reverse bias
on the protection diodes. The peak is caused by internal
Miller feedback capacitance when the inverter is in its
linear mode.

With a higher supply voltage, the drain-source voltage of the input MOSFETs increases, which decreases the input capacitance:


text:
Q: Batch increase drone imagery altitude by editing EXIF GPS information I have around 3.600 drone images covering an area of around 2 x 4 KMs. The images were recorded using two drones. For some reason the images from one of the drones is off by around 15 meters in the z-axis. This could be space weather, drone specifications etc.
The software I am using in this case is Pix4D. It produces a fine orthophoto. The point cloud represents the difference in altitude well. This means the 3D-model shows up with an unsavory step up where the images from the two drones meet.

There might be several ways to fix this. One of them is to adjust the exif altitude (GPSAltitude) of the images from one of the drones.
I thus need to systematically subtract 15 meters from the EXIF information for all images from one of the drones. Are there any GIS tools which could help me out here, or should I script it using Python?


text:
Q: Exclude certain directories and files in pdepend, phpmd, phpcpd, phpcs, phpdoc, phploc In my project there are certain directories and certain php files which are very large in size due to which my build is failing and I want to exclude them in my build.xml
Ques1- Do I have to write the --ignore="path/filename" for every php file in the project?
Ques2- There are certain files which are not php but .dat so should I mention these files in the --ignore too?
Ques3- Can I specify to exclude files based on their size such that I exclude all the files larger than 500kb?
My current xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>

<project name="name-of-project" default="build" basedir=".">
  <property name="root.dir" value="${basedir}/.."/>
  <property name="source" value="${root.dir}"/>

 <target name="clean"
         description="Clean up and create artifact directories">
  <delete dir="${basedir}/build/api"/>
  <delete dir="${basedir}/build/code-browser"/>
  <delete dir="${basedir}/build/coverage"/>
  <delete dir="${basedir}/build/logs"/>
  <delete dir="${basedir}/build/pdepend"/>

  <mkdir dir="${basedir}/build/api"/>
  <mkdir dir="${basedir}/build/code-browser"/>
  <mkdir dir="${basedir}/build/coverage"/>
  <mkdir dir="${basedir}/build/logs"/>
  <mkdir dir="${basedir}/build/pdepend"/>
 </target>

 <target name="phpunit"
         description="Run unit tests using PHPUnit and generates junit.xml and clover.xml">
  <exec executable="phpunit" failonerror="true">
    <env key="DOCUMENT_ROOT" value="${source}/api"/>
    <env key="MODEL_ROOT" value="${source}/model"/>
  </exec>
 </target>

 <target name="parallelTasks"
         description="Run the pdepend, phpmd, phpcpd, phpcs, phpdoc and phploc tasks in parallel using a maximum of 2 threads.">
  <parallel threadCount="2">
   <sequential>
    <antcall target="pdepend"/>
    <antcall target="phpmd"/>
   </sequential>
   <antcall target="phpcpd"/>
   <antcall target="phpcs"/>
   <antcall target="phpdoc"/>
   <antcall target="phploc"/>
  </parallel>
 </target>

 <target name="pdepend"
         description="Generate jdepend.xml and software metrics charts using PHP_Depend">
  <exec executable="pdepend">
   <arg value="--jdepend-xml=${basedir}/build/logs/jdepend.xml" />
   <arg value="--jdepend-chart=${basedir}/build/pdepend/dependencies.svg" />
   <arg value="--overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg" />
   <arg value="--ignore=${source}/web" />
   <arg path="${source}" />
  </exec>
 </target>

 <target name="phpmd"
         description="Generate pmd.xml using PHPMD">
  <exec executable="phpmd">
   <arg path="${source}" />
   <arg value="xml" />
   <arg value="${basedir}/build/phpmd.xml" />
   <arg value="--reportfile" />
   <arg value="${basedir}/build/logs/pmd.xml" />
   <arg value="--exclude" />
   <arg value="${basedir}/web" />
  </exec>
 </target>

 <target name="phpcpd"
         description="Generate pmd-cpd.xml using PHPCPD">
  <exec executable="phpcpd">
   <arg value="--log-pmd" />
   <arg value="${basedir}/build/logs/pmd-cpd.xml" />
   <arg value="--exclude" />
   <arg value="${basedir}/web" />
   <arg path="${source}" />
  </exec>
 </target>

 <target name="phploc"
         description="Generate phploc.csv">
  <exec executable="phploc">
   <arg value="--log-csv" />
   <arg value="${basedir}/build/logs/phploc.csv" />
   <arg value="--exclude" />
   <arg value="${basedir}/web" />
   <arg path="${source}" />
  </exec>
 </target>

 <target name="phpcs"
         description="Generate checkstyle.xml using PHP_CodeSniffer">
  <exec executable="phpcs" output="/dev/null">
   <arg value="--report=checkstyle" />
   <arg value="--report-file=${basedir}/build/logs/checkstyle.xml" />
   <arg value="--standard=${basedir}/build/phpcs.xml" />
   <arg value="--ignore=${source}/web" />
   <arg path="${source}" />
  </exec>
 </target>

 <target name="phpdoc"
         description="Generate API documentation using PHPDocumentor">
  <exec executable="phpdoc">
   <arg value="--directory" />
   <arg path="${source}" />
   <arg value="--target" />
   <arg path="${basedir}/build/api" />
   <arg value="--ignore" />
   <arg path="${basedir}/web" />
  </exec>
 </target>

 <target name="phpcb"
         description="Aggregate tool output with PHP_CodeBrowser">
  <exec executable="phpcb">
   <arg value="--log" />
   <arg path="${basedir}/build/logs" />
   <arg value="--source" />
   <arg path="${source}" />
   <arg value="--ignore" />
   <arg path="${basedir}/web" />
   <arg value="--output" />
   <arg path="${basedir}/build/code-browser" />
  </exec>
 </target>

 <target name="build" depends="clean,parallelTasks,phpunit,phpcb"/>
</project>

And I am getting errors like these
pdepend:
     [exec] PHP_Depend 0.10.5 by Manuel Pichler

     [exec] Parsing source files:
     [exec] phpcpd 1.3.2 by Sebastian Bergmann.

     [exec] PHP Fatal error:  Allowed memory size of 262144000 bytes exhausted (tried to allocate 71 bytes) in /usr/share/pear/PHPCPD/Detector.php on line 115
     [exec] PHP Stack trace:
     [exec] PHP   1. {main}() /usr/bin/phpcpd:0
     [exec] PHP   2. PHPCPD_TextUI_Command::main() /usr/bin/phpcpd:51
     [exec] PHP   3. PHPCPD_Detector->copyPasteDetection() /usr/share/pear/PHPCPD/TextUI/Command.php:216
     [exec] PHP   4. token_get_all() /usr/share/pear/PHPCPD/Detector.php:115
     [exec] Result: 255

phploc:
     [exec] phploc 1.6.1 by Sebastian Bergmann.

     [exec] PHP Fatal error:  Allowed memory size of 262144000 bytes exhausted (tried to allocate 71 bytes) in /usr/share/pear/PHPLOC/Analyser.php on line 279
     [exec] PHP Stack trace:
     [exec] PHP   1. {main}() /usr/bin/phploc:0
     [exec] PHP   2. PHPLOC_TextUI_Command::main() /usr/bin/phploc:51
     [exec] PHP   3. PHPLOC_Analyser->countFiles() /usr/share/pear/PHPLOC/TextUI/Command.php:215
     [exec] PHP   4. PHPLOC_Analyser->countFile() /usr/share/pear/PHPLOC/Analyser.php:170
     [exec] PHP   5. token_get_all() /usr/share/pear/PHPLOC/Analyser.php:279
     [exec] Result: 255

What should I do to solve it? If I manually remove the large files from the directory then the build just passes but I want the build to run automatically checking out the code base from svn which will have these large files.
Ques4- Can I configure my checkout in such a way that these files dont get checked out?

A: For every target you can use fileset property or add exclude directories manually
<target name="phploc" description="Measure project size using PHPLOC">
    <exec executable="phploc">
        <arg value="--log-csv"/>
        <arg value="${basedir}/build/logs/phploc.csv"/>
        <arg value="--exclude"/>
        <arg value="${src}/api/"/>
        <arg value="--exclude"/>
        <arg value="${src}/external/"/>
        <arg path="${src}"/>
    </exec>
</target>

<target name="pdepend"
        description="Calculate software metrics using PHP_Depend">
    <exec executable="pdepend">
        <arg value="--jdepend-xml=${basedir}/build/logs/jdepend.xml"/>
        <arg value="--jdepend-chart=${basedir}/build/pdepend/dependencies.svg"/>
        <arg value="--overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg"/>
        <arg value="--ignore=/dir/one/,/dir/two/"/>
        <arg path="${src}"/>
    </exec>
</target>

<target name="phpcpd" description="Find duplicate code using PHPCPD">
    <exec executable="phpcpd">
        <arg value="--log-pmd"/>
        <arg value="${basedir}/build/logs/pmd-cpd.xml"/>
        <arg value="--exclude"/>
        <arg value="${src}/api/"/>
        <arg value="--exclude"/>
        <arg value="${src}/exclude/"/><arg path="${src}"/>
    </exec>
</target>

Hope my answer will be helpful for someone.

A:
In my project there are certain directories and certain php files
  which are very large in size due to which my build is failing and I
  want to exclude them in my build.xml
There are certain files which are not php but .dat so should I mention
  these files in the --ignore too?

What I'm doing in this case is to make a copy of the needed files, and work from there. Either copy the whole directory and delete certain files, or copy over just the needed files. In the former case, the find program would do:
cp /my/large/project /tmp/work
find /tmp/work -name "*.dat" -delete
find /tmp/work -size 500k -delete

In the latter, I'm using ant's <copy> task:
<copy todir="${dir.source.our}" includeEmptyDirs="true">
   <fileset dir="${dir.source}/ext" includes="${glob.source.our}"/>
</copy>

PHP Fatal error:  Allowed memory size of 262144000 bytes exhausted

You'll have to increase PHP memory size in php.ini.
Search for memory_limit and set the value to something like 512 MB, e.g.
memory_limit = 512M


text:
Q: Changing font in cmd or powershell I was looking if there was a way to change the font in command prompt or power shell? To be more exact changing it to Ubuntu Mono? Or what is the default font in Ubuntu?

A: You can access the shell menu by right-clicking in the upper left hand corner of the window:

From there, if you would like to make a permanent change select "Defaults", to change just this session's shell select "Properties".  Both options open a similar window.  Select the "Font" tab and then select the desired font and size.


text:
Q: Google Spreadsheets: how to display the amount of cells that contain specific multiple text and numbers I'm trying to create a spreadsheet in Google Spreadsheets to use for score keeping in a pool league and have run into a problem.
I have two sheets in the spreadsheet.  The first is called "Actual Scoresheet" and contains scores from the game.  The second sheet is called "Player Stats" and contains stats from each player during the game.
In the "Actual Scoresheet", I have a range of cells (for example F37:T37) where the scores from each game are entered.  There are 4 different possibilities for a win that can be entered in any of the cells in this range.  These possibilities are "14", "BR", "TR", "WZ".
In the "Player Stats", I have a cell that I want to show the total amount of wins in the range of cells contained in "Actual Scoresheet".
I tried this formula
=COUNTIFS('Actual Scoresheet'!F37:T37, "14", 'Actual Scoresheet'!F37:T37, "BR", 'Actual Scoresheet'!F37:T37, "WZ", 'Actual Scoresheet'!F37:T37, "TR")

but it is only returning a value of 0 even though cells F37:T37 contain 2 TR's and 2 14's, which should return a value of 4.
Can anyone help me figure out what I'm doing wrong?  Thanks

A: Given tag, Excel version:
=SUM(COUNTIF('Actual Scoresheet'!F37:T37,{14,"BR","TR","WZ"}))

or for a locale with; as the separator:
=SUM(COUNTIF('Actual Scoresheet'!F37:T37;{14;"BR";"TR";"WZ"}))

Again both are to be entered as an array formula, in Excel with Ctrl+Shift+Enter.
CSE entry not necessary, see the maestro's comment below.
14 may be either a number or a string.

A: As per +Tim Williams' comment, you essentially have an OR condition rather than an AND; so you can sum individual COUNTIF()s, or a bit shorter:
=ArrayFormula(SUM(COUNTIF('Actual Scoresheet'!F37:T37,{"14";"BR";"TR";"WZ"})))


text:
Q: How to make the screen go dark when a proximity sensor is detected on Android? I have an application for calls, when the user enters the call page, there is a voice, etc., I want to implement a proximity sensor, so that when the user brings the phone to his ear, the screen is inactive and darkened. Here is my code for the sensor (it works).
    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.Hardware;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Corporate_messenger.DB;
    using Corporate_messenger.Service;
    using Corporate_messenger.Service.Notification;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Xamarin.Forms;

    namespace Corporate_messenger.Droid
    {
        [Activity(Label = "CallActivity",ScreenOrientation = ScreenOrientation.Portrait)]
        public class CallActivity : Activity, ISensorEventListener
        {

            Android.Widget.Button BtnStartCall;
            Android.Widget.Button BtnEndCall;
            Android.Widget.Button BtnEndCallCenter;

            SensorManager sensorManager;
            Sensor proximitySensor;

            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);

                    sensorManager = (SensorManager) GetSystemService(Context.SensorService);
                    sensorManager.RegisterListener(this, sensorManager.GetDefaultSensor(SensorType.Proximity), SensorDelay.Ui);
                    proximitySensor = sensorManager.GetDefaultSensor(SensorType.Proximity);
            }

            public void OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy)
            {
                var s = sensor;
            }

            public void OnSensorChanged(SensorEvent e)
            {

// The sensor is triggered here, at this moment I can't figure out how to Hide the screen (do not
               // active , darken)
            }
        }
    }

Please help me to make the screen not active "Dimed"


text:
Q: Linking .so file on Eclipse I'm still new to Android development, so I'm stuck with NDK.
Background: I am trying to connect my app to the printer. For that purpose the vendor gave a sample application which discovers printer and then prints. Right now I am trying to run that sample application but it has a .so file and every time I try to run it gives me this error:
01-01 17:34:59.618: E/AndroidRuntime(5870): java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.xyz.epos2_printer-2/base.apk"],nativeLibraryDirectories=[/data/app/com.xyz.epos2_printer-2/lib/arm, /vendor/lib, /system/lib]]] couldn't find "libepos2.so"

I am using Eclipse not Android Studio (so build.gradle solution won't work for me I suppose). I have searched on this topic but couldn't figure out how to do it.

A: Check you have added libepos2.so file in your project
check the screen shot.
Step 2

*

*Add the following in gradle under default config.
ndk {
            abiFilters "armeabi-v7a", "x86", "armeabi", "mips"
        }
    sourceSets { main { jniLibs.srcDirs = ['src/main/jniLibs/'] } }

Step 3
Add this in dependency:
implementation files('libs/ePOSEasySelect.jar')
implementation files('libs/ePOS2.jar')
implementation files('libs/armeabi/libeposeasyselect.so')
implementation files('libs/armeabi/libeposprint.so')

Step 4
Add this in gradle.properties:
android.useDeprecatedNdk=true


text:
Q: Imread grayscale is different than imread + convert to grayscale While working with OpenCV, I found a curious behavior and my knoledge couldn't explain it.
Maybe someone will have the answer.
image= cv.imread("image.jpg", 0)
__, thre = cv.threshold(image, 1, 255, cv.THRESH_BINARY)
plt.imshow(thre)

image = cv.imread("image.jpg")
image=  cv.cvtColor(output, cv.COLOR_BGR2GRAY)
__, thre = cv.threshold(image, 1, 255, cv.THRESH_BINARY)
plt.imshow(thre)

As you can see, the two images are a bit different.
Could someone explain me why using imread with flag 0 (grayscale) make a different result than using imread without a flag and convert it to grayscale after.
Is it because of the cvtColor flag ?

A: I am not sure if this is reason for effect you have observed, but I want to note that there exist two distinct ways of RGB to Grayscale Conversion: that is using mean and using weighted average, in later case different weights might be used, cvtColor() is said to use following formula
Y = 0.299*R + 0.587*G + 0.114*B

there is also another formula provided in linked article with weights adjusted for human perception as follows
Z = 0.2126*R + 0.7152*G + 0.0722*B

Note that as above transformations are idempotent you might feed already grayscale image into them without care.


text:
Q: Copying/moving a struct into another one When you don't have to deal with pointers, copying/moving a struct into another one is quite easy.
In my case though, I've to deal with pointers and access rights.
protected:
          addrinfo *hints, *result;
...
hints = new addrinfo;
...
getaddrinfo(0, port.c_str(),  hints, &result); // result is protected - can't do that.

memmove/memcpy can be used, but addrinfo contains a pointer to sockaddr inside itself.
I thought to use a temporary struct to pass getaddrinfo and then move everything to result, but the question is always there.
Tell me if you need some other details.
EDIT: @Mike Woolf you've given me an idea. Since the base class is an abstract one, I can even make those structs public, since the user would have no way to istantiate it. Thanks however for the answer.

A: In a case like this, I would write my own copying function. It could be something like
void structCopy(struct* dest, const struct* src);

Inside of this function, use memcpy() to copy everything over except for the pointers.
I had to do something like this when I was making a multiplayer game - copying pointers like this. In this kind of pattern it's typical to assume that this is a function that understands exactly what it has to do - that is, structCopy() is specifically designed for this particular struct. So it is aware that there is a sockaddr inside of the object.
So really, just hardcode inside of this function how you want to handle it. Do you want it to create a new sockaddr on the other end? Then have the copy function do that. Or whatever works.
TL;DR - Create a special copy function for your struct that knows what is inside the struct and have it handle the sockaddr according to whatever your specifications are. By making it part of the class (or a friend function) you're not breaking any rules by hardcoding the function.


text:
Q: Python - tempfile module creates a file that cannot be opened? I'm using the tempfile module and imagemagick and when i try to run this code:
width = height = 100
temp_file = tempfile.NamedTemporaryFile()
canvas = "convert -size {}x{} canvas:black {}/canvas.png".format(scale_width, scale_height, temp_file.name)
os.system(canvas)

I get the following error:

convert: unable to open image
  /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png':
  Not a directory @ error/blob.c/OpenBlob/2705. convert: WriteBlob
  Failed
  /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png'
  @ error/png.c/MagickPNGErrorHandler/1630.

What could be the problem?
I'm just trying to create a black image (resolution of 100x100) stored in a randomly generated temp file.
Thanks!

A: You have to leave the /canvas.png bit. The temporary file created by tempfile.NamedTemporaryFile() was /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh. So using it as parent directory for the output file raises the error by imagemagick.
To specify the output format PNG by filename extension, the temporary file can be created with the suffix keyword argument:
temp_file = tempfile.NamedTemporaryFile(suffix='.png')

Additionally, you should use the subprocess module to run subprocesses. That way you do not have to use string formatting the whole command in order to pass the subprocesses' arguments, e.g.
subprocess.check_call(['convert',
                       '-size', '{}x{}'.format(scale_width, scale_height),
                       'canvas:black',
                       temp_file.name])

And another remark: NamedTemporaryFile() opens a file descriptor, which you should close right away. The docs also state that you are in charge of deleting the file again.


text:
Q: Running Flash (AS3) code in Haxe I am starting out developing in Haxe in combination with OpenFl, and am in a situation where I need to be able to run Flash/AS3 code in a Haxe program which is being compiled to Flash anyway.
I know I could use the command lime build -as3 as3source/ and then edit that code and manually insert the AS3 code I need to run, but I would prefer not doing that if I can.
Is there any way to do this?

A: You can compile your AS3 code into a separate swf or swc and then use -swf-lib to use it from Haxe.

A: You can always write a build script which enters the code in combination with the command for you, if you just want to avoid doing it manually, but I belive that´s the kind of answer you want.
I just find build script very usefull.

A: You may want to look at this article, some major options are described there (including tools for converting AS3 code to Haxe and technique with -swf-lib).


text:
Q: What are the benefits of having an unique IP address? I just signed up with DreamHost VPS, and their sign-up process offered an unique IP address for an additional ~$4/mo.
I know what IP addresses are. Why would this uniqueness matter? Visitors are accessing my website via URL addresses anyway.

A: Blacklists (SEO, mailings etc.) are often based on IP, so having unique IP will reduce propability that you will suffer for someone's other actions.

A: The big one is that you need a unique IP address for some SSL/TLS implementations. As pointed out in the comments, no version of IE on XP can do this, which is the biggest offender.
Also, if you have an application that needs to reference an IP instead of a DNS name, you'd need it since your shared host is likely configured to ignore requests to an IP.

A: If you don't know that you need a unique IP address, then you probably don't need one.
Some protocols and applications require a specific IP address, but for the ones most frequently used these days, host name alone is often sufficient.
Obviously, in the background, this must resolve to an IP address, but not necessarily a unique or fixed address. As long as the server understands enough to route the query appropriately, all the services could share the same pool of IP addresses without issue.

A: Another benefit is being able to point multiple domain names at your static IP address in order to run multiple stand-alone websites that each resolve to their own folders.

A: I agree with Bill.  If you don't know you need it, don't get it. You can always add it later if you find you need an ssl certificate (like for processing credit cards).
As for the comments you may hear online about security of having your site on a unique IP so that you are not lumped in with spammers, for example, almost everyone in the world is on shared servers.  Most hosting companies now are good at responding to spam issues and making sure they get rid of bad clients.


text:
Q: Prevent leaving form without saving iOS I'm trying to implement with jquery that when a user is leaving certain page without filling some fields, the browser could warn the user.
I have tried this solution but it only works in Chrome, Mozila and android (I have tried with Chrome):
window.addEventListener("beforeunload", function(e) {
var confirmationMessage = "\o/";
        e.returnValue = confirmationMessage;
        return confirmationMessage;

Anyone who have the master key for this? Thanks in advance


text:
Q: What's wrong with my kendo template? I've prepared template for my Kendo Grid's column:
# if(status == 0) { #
    #= "Error" #
# else if(status == 1) { #
    #= "Warning" #
# else if(status == 2) { #
    #= "OK" #
# } #

It's seems OK to me, but I'm getting an error "Error: Invalid template". Grid displays numeric values, but I'd like to replace it with string values.
So where's the problem?

A: You are missing a closing bracket on the first and second if statement.
# if(status == 0) { #
    #= "Error" #
# } else if(status == 1) { #
    #= "Warning" #
# } else if(status == 2) { #
    #= "OK" #
# } #


text:
Q: String's split returning unexpected value System.out.println(Arrays.toString("1.1.1".split(".")));

This prints out an empty array. What gives?
To me, it should print out "[1, 1, 1]". Instead, it prints out "[]". It doesn't make sense to me.

A: . is wildcard character in regex.
use - split("\\.")


text:
Q: Raster merge produces wrong values in R I have run into a problem, somewhat similar to that described R Raster Merge Changes Values, but the suggested solution does not fit my need, as none of them provided help my issue,

https://stackoverflow.com/questions/38631565/r-raster-merge-changes-values

The problem is that where raster's merge produces wrong values, and someone refers to the current thread and suggests the use of mosaic_rasters() from gdalUtils. The problem is that my use of merge is in a function call i.e
for(i in seq_len(nlayers(Countstacks[[1]]))){
   print(i)
Count[[i]] <- do.call(merge, lapply(Countstacks, function(x) x[[i]]))
 }

when I try to directly replace the above with
for(i in seq_len(nlayers(Countstacks[[1]]))){
   print(i)
Count[[i]] <- do.call(mosaic_rasters, lapply(Countstacks, function(x) x[[i]]))
}

or use:
do.call(gdalUtils::mosaic_rasters, ...

It throws this error: "Error in FUN(X[[i]], ...) : invalid 'file' argument Calls: do.call -> -> sapply -> lapply -> FUN Execution halted" and won't go past this stage. Clearly, doesn't look like do.call is able to work with gdalUtils. Any suggestions on how I could replace the merge or re-write the code to be able to use gdalUtils.


text:
Q: Xpages Calendar without time slots Any suggestion on how to create calendar without time slots on the daily, two days and weekly view ?  I looked at INotes calendar control but having found where that possible.  Also looked at jQuery FullCalendar but having difficulties on how to implement it for my requirements.
The requirement is a defined company assets scheduling for that those days, so the actual time period is not important just the day.
Lotus Domino 8.5.3 or 9.01
Thank you in advance.
Bob

A: There are a few on OpenNTF
https://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=ITWU%20adhoc%20groupcalendar
And the Teamroom template
https://www.openntf.org/main.nsf/blog.xsp?permaLink=NHEF-8ERBUJ
You might be able to use those as the starting point and use CSS to hide the time gridlines?
Howard


text:
Q: Pascal Syntax Error I have the following function in my program:
function Getrand(rStart,rEnd:Integer): Integer;
var
diff: Integer;

begin
diff := rEnd - rStart;

Getrand := Random(diff) + rStart;
end;

When I try to compile the program, I get this error:
Failed when compiling
Line 27: [Error] (27:9): Invalid number of parameters in script

What am I doing wrong?

A: Perhaps your flavour of Pascal doesn't support the traditional return value syntax. Try Result := … instead of Getrand := ….

A: you can use
Exit(Random(diff) + rStart)

instead. But keep in mind that if you do that it will exit from function after returning the value.

A: You need to write Getrand(Random(diff),rStart); to send variables to function


text:
Q: Unable to display Toast message when using with WebService I need to display a message to the user "Communicating to the Server...Please wait for few seconds" when a call to a webservice is made. Currently I'm using Toast.makeText to display the message. For some reason, I don't see the message pop-up. But interestingly when I comment the web service method call, I see the Toast message.
Toast.makeText(this, "Communicating to the Server...Please wait for few seconds",
                     Toast.LENGTH_SHORT).show();

//webservice code goes here...

Or any other alternative to satisfy this requirement is also fine.

A: Have you looked at using AysncTask. Using AsyncTask you can show a dialog with your message on onPreExecute().

A: Do NOT mix UI code and network code.  See: http://developer.android.com/resources/articles/painless-threading.html

A: You can use AsyncTask to run your service and show Toast in onPreExecute.
Or you can use normal Thread but, you'll need to use Handler. Here is how:
class MyActivity extends Activity
{
    final Handler mHandler;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(...);
        mHandler = new Handler();

        ...
    }

    void showToast(final String text)
    {
        mHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                Toast.makeText(MyActivity.this, text, Toast.LENGTH_LONG).show();
            }
         });
    }

    class MyThread implements Runnable
    {
        @Override
        public void run()
        {
            showToast("your custom text");
            //your service code
        }
    }
}

And here is how you start the thread:
Thread thread = new Thread(new MyThread());
thread.run();

A: The problem is that the UI thread is blocked as soon as you make the blocking web service call, so it never updates with the toast message. By the time it returns, the time for toast message has expired.
Run your web service call in a thread, using AsyncTask, or just create a thread like,
new Thread(new Runnable() {
  public void run() {
    // WS call here

  }
}).start();

Take care that if you create your own thread, you can only update the UI from the UI thread, so you'll need to use Handler.post() or sendMessage() to run the UI update on the UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/reference/android/os/Handler.html


text:
Q: SQL Server won't print out my variable when I am using EXEC sp_executesql Why is no result being shown? I think everything is fine, it should work, but when I print the output variable it prints nothing
DECLARE @Result NVARCHAR(20)
DECLARE @Qry NVARCHAR(MAX)

SET @Qry = 'select [forid1].[2/17/2017] from [forid1]'

EXECUTE sp_executesql @Qry, N'@Result NVARCHAR(20) OUTPUT', @Result  OUTPUT;

PRINT ' value is : ' + @Result  ;

A: You need to assign the @Result variable in your dynamic SQL:
DECLARE @Result NVARCHAR(20)
DECLARE @Qry NVARCHAR(MAX)

-- assign the @Result inside the dynamic SQL
SET @Qry='select @Result=[forid1].[2/17/2017] from [forid1]'

EXECUTE Sp_executesql @Qry, N'@Result NVARCHAR(20) OUTPUT', @Result  OUTPUT;
print ' value is : ' + @Result  ;


text:
Q: Log_path_is_undefined and log_file_is_undefined I'm updating Spring boot version from 2.5 to 2.6 and I encounter an issue with Logback.
Here's the snippet of my application.properties file:
logging.file=abc.log
logging.path=.

And a part of my logback-spring.xml
 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH:-.}/${LOG_FILE}.log</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${LOG_PATH:-.}/${LOG_FILE}-%i.log</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>3</maxIndex>
        </rollingPolicy>

        <!-- Only allow a file to get to ~10MB -->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>10MB</maxFileSize>
        </triggeringPolicy>

        <encoder>
            <pattern>%date{ISO8601} %-5level [%-35.35logger{30}] %msg%n</pattern>
        </encoder>
    </appender>

I'm getting the error:
2022-10-07 22:51:08,903 INFO  [o.h.v.internal.util.Version        ] HV000001: Hibernate Validator 6.0.22.Final
2022-10-07 22:51:09,241 INFO  [o.s.c.a.ConfigurationClassParser   ] Properties location [classpath:application.properties] not resolvable: class path resource [application.properties] cannot be opened because it does not exist
2022-10-07 22:51:10,158 WARN  [.AnnotationConfigApplicationContext] Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:

I also get a file named: log_file_is_undefined.log
What am I missing?

A: From the documentation:

${LOG_FILE}: Whether logging.file.name was set in Boot's external configuration.
${LOG_PATH}: Whether logging.file.path (representing a directory for log files to live in) was set in Boot's external configuration.

So use:
logging.file.name=abc.log
logging.file.path=.


text:
Q: Occasionally Need to OPTIMIZE TABLE after table creation -- MariaDB 10.6.11 I transfer tables from one server to another by running the CREATE TABLE statement without any indexes. Then I batch insert all of the data into the table. Then I run an ALTER TABLE to add the indexes.
Occasionally when I do this I notice queries will run slowly so I run an EXPLAIN and the query is not using the correct index or not using an index at all. Then I run an OPTIMIZE TABLE, and that seems to resolve the issue.
So I have two questions :

*

*Is there an automated way I can know when I need to run OPTIMIZE TABLE on a table that has become 'unoptimized'?

*More importantly, what am I doing that is causing this issue?

I have only noticed this issue on MariaDB 10.6.11 running on Ubuntu 22.04. I have never had this issue in the past on older versions of Ubuntu/MariaDB.
This has happened previously to tables that are well over 100GB, and I just assumed it had something to do with too many updates, inserts, deletes. However, it happened this morning on a table that is only 250MB immediately after a fresh CREATE, INSERT, ALTER.

A: You can update the index statistics without doing OPTIMIZE TABLE
When you run
OPTIMIZE TABLE mytable;

This is what OPTIMIZE TABLE does under the hood for InnoDB
ALTER TABLE mytable ENGINE=InnoDB;
ANALYZE TABLE mytable;

In details

*

*The first line copies the table to a temp table, switching temp table for the original table.

*The second line reads the index info and compiles the index statistics

You can skip the first line and just run
ANALYZE TABLE mytable;

I discussed this before in my post from Feb 27, 2013: What is the difference between OPTIMIZE TABLE and ANALYZE TABLE table in MySQL


text:
Q: Is there a way to reduce time to load cshtml view? My application is in asp.net-mvc and i return pages this way :
[AuthorizedFunctionalities(Functionalities = "Missions_R")]
public ViewResult Missions()
{
    return View("~/Views/Mission/Missions.cshtml");
}

Although I directly return a cshtml page, there is at least 1 sec before the client receives the actual html (seen with devtools -> network on browser). In this page I then call an ajax which loads data in about 500ms.
How come the loading of the page without any call to my DB can be longer than the call where I do requests on my DB ?
Is there a way to reduce this time ? Or to track if there is additional calls that might slow the request ?


text:
Q: send arguments to django forms I want to pre-populate a textfield on a django form when the form is loaded. Below is my code.
I want this "content" field in forms.py to be pre-populated when my form loads in the browser. This field should be un-editable. But with the code below an empty textfield gets created.
I know I can pre-populate this info by sending it in the url string just like I am sending 'id'. But I don't want to take that approach. Is there any other way to send parameters to forms?
forms.py
class ContentModelForm(ModelForm):
    content = forms.CharField(max_length=256)
    message = forms.CharField(max_length=256)
    created_at = forms.DateTimeField('DateTime created')

    class Meta:
        model = Content

    def __init__(self, *args, **kwargs):
        super(ContentModelForm, self).__init__()
        self.fields['content'].value = kwargs.get('content')

views.py
def post_form_upload(request, id):
    post = get_object_or_404(models.Post, id=id)
    content = post.content

    if request.method == 'GET':
        form = ContentModelForm(content = content)
    else:
        form = ContentModelForm(request.POST)
        if form.is_valid():
            message = form.cleaned_data['message']
            created_at = form.cleaned_data['created_at']
            models.Content.objects.create(post_id = id,
                                        message = message,
                                        created_at = created_at)
            return HttpResponseRedirect(reverse('post_form_upload',
                                          args = (post.next_id,)))
    return render(request, 'survey_forms/post_form_upload.html',{
    'form':form,
     'id' : id,
    })

survey_forms/post_form_upload.html
<form action="{% url 'post_form_upload' id=id %}"  method='post'>
{% csrf_token %}
{{form.as_p}}
<input type='submit' value='Submit'/>
</form>

Thanks.

A: You should be using the initial keyword argument when instantiating your form. This accepts a dictionary where the keys are the field name and the values are the initial values.
form = ContentModelForm(initial={'content': content})

Moreover since you want this field to be readonly. You should change this line
content = forms.CharField(max_length=256)

to
content = forms.CharField(max_length=256, widget=forms.TextInput(attrs={'readonly':'readonly'})

A: if you want an input to be pre-populated then you might as well just give it a "value" attribute, for example.
input<type="text, value="content_you_want_in_there">


text:
Q: How do I apply a regular expression to multiple lines? I have a regular expression that grabs the two words I want, but only from the first line. How can I expand the expression to encompass every line.
Regex I have:      ActivityState\s\s*(\w+).*new ActivityState\s*\(\"(\w+)
Text String:
public ActivityState StartState = new ActivityState("start");
public ActivityState ThisState = new ActivityState("this");
public ActivityState IsState = new ActivityState("is");
public ActivityState AState = new ActivityState("a");
public ActivityState TestState = new ActivityState("test");

Desired output:
StartState state

ThisState state

IsState is

AState a

TestState test

A: For a general case, you can add the /g flag in the end of your regex:
ActivityState\s\s*(\w+).*new ActivityState\s*\(\"(\w+)/g

/g stands for global and it means it wont stop at first match.
See Demo
Depending on your programming language this can be also achieved several different ways, with most languages having this behavior built in on its functions. For instance, in python if you call re.findall(pattern,text) you have the same behavior without needing to specify the /g flag in the pattern.


text:
Q: Fastest SAX-style XML parsers for JRuby I need to port some simple Ruby program to Windows, and I thought I'd use JRuby to avoid most of the hassle, but there's no libxml for JRuby.
What should I use instead? I have gigabytes of XML to process, so I'd prefer if it was fast.

A: There is libxml-jruby. It aims to be an API compatible replacement for libxml-ruby and drops into ruby code seamlessly if you have it installed within JRuby. However, I have found it to be lacking in certain areas (XPath and error handling) and I can't vouch for its SAX coverage.
Another option for JRuby would be Nokogiri - you'll have to search for it as I can only post one hyperlink! It has a JRuby component to it but, although I've heard good things about it, I've not had time to try it yet.
Any pure ruby XML library will work in JRuby of course, but if you have gigabytes of data to process you might want to stay clear of those, speed wise.


text:
Q: IOS: Memory Issue on living objects and I have an image gallery which is developed using UICollectionView. After I select multiple images from the gallery and press 'Done'. Selected images will display in a UIScrollView (paging on) and those are full screen images that can be scrolled up/down to see other images.
1) Is it ok to have this amount of living objects and heap allocation, when starting the app.'

2) When I select and scroll through the images of UIScrollView allocated memory for images will added to the memory and not release. It will crash the app.
Here are the screens when I start scrolling up/down through the images. It will Increasing the memory consumption also other processes.

This is testing on iPhone5, using Activity monitor VM and Real memory going up.

A: Why don't you try to load the images 3 at a time, and not the whole set of images at once.
I mean you can set your Scroll Views array and add as many [NSNull null] objects to it as the number of images to be shown. Then, at a particular instance, have only 3 images in that array and after scrolling remove the unnecessary ones or replace it with [NSNull null] objects.

A: Profiling memory is tricky. The best instrument to actually use is the Activity Monitor, which will tell you how much live memory is really being used, unlike Allocations which will tell you more than you need to know.
Also, the maximum amount of memory is dependent on each device. If you really want to know if you're using a lot of memory, just test it on a device. You generally have a lot of flexibility, and the internal UIImage class does a lot of fancy caching and clearing of said caching for you.


text:
Q: Umbraco Multi-site With Shared Content If I have 1 Umbraco installation with 4 websites, is it possible to share contents between the sites?
Or is it better to create another website ('repository') that will have all the contents and allow the 4 other websites to retrieve/link contents from this 'repository' website?

A: There was a good session at Umbraco CodeGarden by CountryWide this year that might be worth watching as it discussed a group in the housing market that have about "40+ different high traffic sites from a single Umbraco installation" but with shared content between many of the sites in the group. You can watch the video here:
http://stream.umbraco.org/video/9921509/40-different-high-traffic-sites-from-a
I'd recommend watching the entire video but if not you can jump to about 25 minutes in to see this topic of discussion. They have a shared content node (+ children).
Simon

A: I would recommend you stick with your existing websites and not create a repository website. This makes it easier I think to define canonical urls for documents if they are to be displayed on multiple websites. Also makes more sens from a content editor point of view. To reach content from another website, I would use code similar to this (considering Umbraco 7+ here):
// Root nodes
var root = Umbraco.TypedContentAtRoot().First();
var site = Model.Content.AncestorOrSelf("Site");
var lang = Model.Content.AncestorOrSelf("LanguageHome");

var allOtherWebsites = root.Children.Where(x => x.Id != site.Id);
var newsFromAllOtherWebsites = allOtherWebsites.Descendants("News").Where(x => x.Parent.Name.ToLowerInvariant() == lang.Name.ToLowerInvariant());

// Do things with news...

I threw in something for multi-lingual setup also, you can simply remove those if you don't need.
Hope this helps!


text:
Q: is this way of applying data augmentation correct I'm training a CNN and want to apply some data augmentation to my input images. I combined some code from tensorflow tutorials and have the following workflow:
I have a dataset containing all filenames. Then I map a function to that dataset that loads the labels and images and applies some data augmentation:
def decode_image(img):
  img = tf.image.decode_jpeg(img, channels=3)
  img = tf.image.convert_image_dtype(img, tf.float32)
  img = tf.image.random_flip_up_down(img)
  ...

def process_path(file_path):
  label = label_from_file_path(file_path)
  img = tf.io.read_file(file_path)
  img = decode_image(img)
  return img, label

After that I repeat, batch and prefetch the dataset containing images and labels.
My question now is: is this the correct way to do data augmentation? I don't create new artificial data as I only apply this once to each image, right? It should still increase the robustness of the network, but do I give up some potential here?

A: It looks to me as though you are attempting to conduct the data augmentation manually - i.e. make changes to each image and then work from there.
Without seeing results, I cannot say whether your method of doing so will yield high accuracy on your test set.
However, from my own experience - a good way of conducting data augmentation is by using the ImageDataGenerator to create modified images and thus increase the size of the training set.
François Chollet, the creator of Keras, explains how this can be implemented in the Deep Learning with Python text - I would recommend this as a source in understanding data augmentation further.
If it helps, here is an example of how an image classifier was built with Keras to distinguish between images of cars and planes.
Essentially, the analysis used 100 images for each class as training and validation (with 15 images across both classes used as the test set).
Data augmentation is used for the purposes of increasing the sample size for the two classes, which subsequently resulted in strong predictive performance across the test set.
You could check whether implementing data augmentation in this manner vs. your method ultimately yields better results.


text:
Q: Installing fftw-2.1.5 with openMPI Trying to install fftw to use GADGET2, and after running the following command:
./configure --enable-mpi --enable-type-prefix --enable-float

I get the message:
checking for mpicc... mpicc
checking for MPI_Init... no
checking for MPI_Init in -lmpi... no
checking for MPI_Init in -lmpich... no
configure: error: couldn't find mpi library for --enable-mpi

Now I have installed openMPI already, so it seems to be the case that it just can't find it. There was a similar question posted a while ago with different mpi software. I think the problem is that my openMPI and other compilers might be in different folders? This brings me to a more general question (I have tried googling this but can't find anything that explains it well):
If I extract a tar and use ./configure without any prefix, where will the program install to? And is this is an issue that my openMPI has for some reason installed to a different place?
Thanks!
edit: found a solution for this from this question, where just running
sudo ldconfig

seemed to fix it and now it compiles fine.


text:
Q: Generators of pure braid groups of arbitrary Coxeter groups Let $W$ be an arbitrary Coxeter group, and let $A$ be the associated Artin-Tits braid group, with standard Coxeter generators $\sigma_i\in A$.  Let $P$ be the "pure braid group", the kernel of the natural homomorphism from $A$ to $W$.  Obvious elements in $P$ include the squares $\sigma_i^2$ of the standard Coxeter generators, as well as conjugates of the $\sigma_i^2$.  Do conjugates of the $\sigma_i^2$ generate the pure braid group $P$?  If so, is there a nice presentation for $P$ in carefully chosen such conjugates?

A: This note
http://arxiv.org/pdf/1511.08731v3.pdf
(unfortunately written in French), Corollaire 3.7, answers your question.
Writing $\bf{W}$ for the canonical positive lift of $W$ in the Artin-Tits group $B_W$, the pure braid group is generated by the elements of the form $\bf{w}\bf{s}^2 \bf{w}^{-1}$ where $\bf{w}\in\bf{W}$, $\bf{s}$ is the lift in $\bf{W}$ of a simple reflection $s\in S$ and $\bf{w}\bf{s}$ also lies in $\bf{W}$. A presentation in terms of these generators is given in Corollaire 3.7 of the above given link.
It works for arbitrary (finitely generated) Coxeter groups.


text:
Q: ordered list; working with javascript and json I'm a junior web developer and I want to understand what json file does, as I have no idea. So I am following a tutorial from lynda.com
It seems very simple, I want to display the array elements within the variable info, but for some reason, it's adding another count after each item of the array!!! I have checked and compared the code with the tutorial, and it's still appearing wrong.
I have added the code on JSFiddle:
https://jsfiddle.net/meyvz462/
Those are my loops:
for (var i = 0; i <= info.links.length; i++) {
    for (key in info.links[i]) {
        if (info.links[i].hasOwnProperty(key)) {
            output += '
' +
                '' + key + '' +
                '
';
        } // hasOwnProperty ckeck
    } //for each object
} //for each array element

I guess it is what it must be wrong....
Thank you!!!!

A: The closing tag is wrong.
output += '
' +
                    '' + key + '' +
                    '
';

has to be
output += '
' +
                '' + key + '' +
                '
';

A: You have missed a closing
 at the end (https://jsbin.com/yasenivege/1/edit?js,console,output):
var info = {
        "full_name" : "Someone Else",
        "title" : "Web Developer",
        "links" : [
        { "blog"     : "http://iviewsource.com" },
                { "facebook" : "http://facebook.com/iviewsource" },
                            { "podcast"  : "http://feeds.feedburner.com/authoredcontent" },
                { "twitter"  : "http://twitter.com/planetoftheweb" },
                { "youtube"  : "http://www.youtube.com/planetoftheweb" }
            ]
        };

            var output = '';

            for (var i = 0; i <= info.links.length; i++) {
              var element = info.links[i];
              for (var key in element) {
                console.log(element[key]);
                if (element.hasOwnProperty(key)) {
                  output += '
' +
                          '' + key +''+
                          '
';
                }// hasOwnProperty ckeck
              } //for each object
           } //for each array element

           var update = document.getElementById('linksGroup');
    console.log(output)
           update.innerHTML = output;


text:
Q: Create gridview in one line I need to create a gridview and set image from asset this gridview will be in one line and one column. After that I select one photo and transfer it to another activity.
This is code of my second activity
package com.testcamera.hassanechafai.testcamera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

public class CallActivity extends ActionBarActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call);
        ImageView image = (ImageView)findViewById(R.id.ImageView);

    }

This is code of the first activity (where I want to set gridview)
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

public class FirstActivity extends ActionBarActivity {

    private String selectedImagePath = "";
    final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;
    ImageView imgView;
    private String imgPath;
    Intent myIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        imgView = (ImageView) findViewById(R.id.ImageView);
        Button butCamera = (Button) findViewById(R.id.Button1);
        butCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            }
        });

        Button butGallery = (Button) findViewById(R.id.Button2);
        butGallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(
                        Intent.createChooser(intent, ""),
                        PICK_IMAGE);
            }
        });

        final EditText save = (EditText) findViewById(R.id.EditText1);
        Button myBtn = (Button) findViewById(R.id.Save);

        myBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int time = Integer.parseInt(save.getText().toString());
                if (time > 0) {

                     myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    calendar.add(Calendar.SECOND, time);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                    Toast.makeText(getApplicationContext(), "Starting Activity in: " + time + " seconds", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });
    }

This is code of alarm receiver
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Alarm time reached", Toast.LENGTH_SHORT).show();
        Intent i = new Intent();
        i.setClassName("com.testcamera.hassanechafai.testcamera", "com.testcamera.hassanechafai.testcamera.CallActivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

I need to choose one picture from gridview and transfer it by passing in alarmreceiver


text:
Q: How do I have a p-value of 1 in the left tail from a two-sample t-test? I have a sample with a mean of 383.45, a standard deviation of 48.878, and a sample size of 30, and a second sample with a mean of 167.78, a standard deviation of 72.368, and a sample size of 30. When I perform a one-tailed two-sample t-test using a TI-84 Plus CE I get a t statistic of 13.52684957 and a p-value of 8.742353334e-19 for the right tail (μ1 > μ2) and 1 for the left (μ1 < μ2). As you might expect, My null hypothesis is that the populations for both samples have the same mean. My alternative hypothesis is that the first sample's population has a greater mean (μ1 > μ2). So, I plan on using the right tail but I'm confused as to why the left tail has a probability of 1 even though when I do a two-tailed test (μ1 ≠ μ2) I get a p-value of 1.748470667e-18 which is around double the p-value for the right tail.

A: The answer by @Dave2e is fine (+1), but I wanted to
give an Answer based mainly on a specific example and showing computations of P-values.
Consider the following fictitious data:
set.seed(2022)
x1 = rnorm(30, 350, 50)
x2 = rnorm(30, 300, 70)

summary(x1);  length(x1);  sd(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  205.0   309.6   346.7   344.2   379.2   410.6
[1] 30         # sample size
[1] 46.29298   # sample SD

summary(x2);  length(x2);  sd(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  190.9   281.3   310.5   307.6   353.5   418.5
[1] 30
[1] 58.53848

Now, do a two sample Welch t test of $H_0: \mu_1=\mu_2$
against $H_a: \mu_1 > \mu_2,$ using t.test in R:
t.test(x1,x2, alt="gr")

        Welch Two Sample t-test

data:  x1 and x2
t = 2.6864, df = 55.074, p-value = 0.004764
alternative hypothesis:
 true difference in means is greater than 0
95 percent confidence interval:
 13.8086     Inf
sample estimates:
mean of x mean of y
 344.2034  307.5991

The P-value of the test is computed by looking in the
upper tail of Student's t distribution with 55.074 degrees
of freedom. [DF is adjusted downward from $n_1+n_2-2=58$ to compensate for the difference
in sample variances.]
1 - pt(2.6864, 55.074)
[1] 0.004764504

[In R, pt is a CDF of Student's t distribution.]
The P-value is the area under the density curve to the right of the vertical dotted red line.

R code for figure:
curve(dt(x, 55.074), -4, 4,
         ylab="Denssity", xlab="t", main=hdr)
 abline(h=0, col="green2")
 abline(v=0, col="green2")
 abline(h= 2.6864, col="red", lwd=2, lty="dotted")
 abline(v= 2.6864, col="red", lwd=2, lty="dotted")

If you do a 2-sided t test, then the P-value is calculated
by looking both in the lower tail below $-2.6864$ and in the upper tail above $2.6864.$  [By using $-notation, we show only the P-value.]
t.test(x1, x2)$p.val
[1] 0.009528523

This P-value for a 2-sided test is computed as follows:
pt(-2.6864, 55.074) + 1 - pt(2.6864, 55.074)
   # left tail + right tail
[1] 0.009529008

Alternatively, using the symmetry of the t distribution:
2*pt(-2.6864, 55.074)   $ Double left tail probability
[1] 0.009529008

Note: Quantities in the output of the test are rounded slightly
to save space, so there is a tiny discrepancy with the P-values shown just above.
However, if you get confused (easy to do), and ask for the
wrong side, using parameter alt="less" in t.test, then
you get a nonsense P-value near $1.$
 t.test(x1, x2, alt="less")$p.val
 [1] 0.9952357

A: Let us define $\mu_1= 383$ and $\mu_2= 168$ with reasonable small standard deviations. The differences between the means are over 4 standard deviations apart. By eye one can judge, with a large difference, that it is very very unlikely to occur by chance alone.
With regard to a discussion of the formal analysis:
The right tail t-test is comparing if $\mu_1(383) > \mu_2(168)$ is clearly TRUE: thus a p-value of nearly 0.
The left tail t-test is testing whether $\mu_1(383) < \mu_2(168)$ which we can see is clearly FALSE: thus a very high p-value of nearly 1.
The null hypothesis $\mu_1(383) = \mu_2(168)$  we can also clearly see is thus FALSE given the relatively small standard deviations. Since we are allowing $\mu_1$ to be greater than or less than $\mu_2$ the probability is split on both sides of the normal distribution; thus the p-value is greater than for the right tail test.
Now if the means were closer or if the standard deviations were sufficiently large, the results would not be so clear cut and thus the recommendation to sketch out the distributions to verify the calculations makes sense.
Hope this answered your question.


text:
Q: How to show Cantor function is uniformly continuous?
Cantor function $f$ is defined by
$f: \Delta \to [0,1]$ by $$f(\sum_{n=1}^{\infty} \frac{2b_n}{3^n}) = \sum_{n=1}^{\infty} \frac{b_n}{2^n}, b_n \in \{0,1\}$$, where $\Delta$ is a Cantor set and each $x\in\Delta$ can be written as $x=\sum_{n=1}^{\infty} \frac{2b_n}{3^n}$, where $b_n = 0$ or $1$.

I read "Cantor function is uniformly continuous" on wikipedia https://en.wikipedia.org/wiki/Cantor_function and wiki also claims that it is Holder continuous of exponent $\alpha = \frac {\log2}{\log3}$. So how to prove it is uniformly continuous and even how to get $\alpha = \frac {\log2}{\log3}$?

A: It is enough to show that it is Holder continuous.
Suppose $0 < \alpha < \frac{\ln 2}{\ln 3} < 1$.
Take any two points $x, y \in [0,1]$. There exists some $n$ such that $|x - y| > 3^{-n}$ (the Archimedian property).
Then $|f(x) - f(y)| \leq \left|f(\frac{k}{3^{n}}) - f(\frac{k +1}{3^{n}})\right|\leq \left|\frac{m}{2^{n}} - \frac{m +1}{2^{n}}\right| \leq \frac{1}{2^{n}}\leq \left(\frac{1}{3^{n}} \right)^{\alpha} < M|x-y|^{\alpha}$, for an appropriate choice of M.


text:
Q: JSP values printing in server console My working environment is like, Struts 1.2 framework with jsp pages, ejb2, db2 database and application server is IBM websphere 9 version. I want to see formbean  value in server console. I have written the code for that in jsp file. Example:
<%= "Welcome "+ sampleformbean.getType() %>

<% System.out.println("Welcome "+ sampleformbean.getType()) %>

<% out.println("Welcome "+ sampleformbean.getType()) %>

But nothing is working. Nothing can be seen in server console. I didn't understand why?. Experts help me. I have to complete work.
NOTE: These codes are inside  html tag.

A: You should look at this IBM KnowledgeCenter topic for details on application logging and trace.


text:
Q: jQuery: Can't update text in a div using $.post I'm trying to get some text to display in a div. This div will appear many times on the page so targeting an ID is out.
This works: it displays the message in the div.
$('.join-div .content a').click(function() {
    $(this).parent().siblings('.message').html('THIS IS A TEST');
});

This does not
$('.join-div .content a').click(function() {

    var data = 'foo=bar';

    $.post('/assets/ajax/join.php',data, function(response) {
        $(this).parent().siblings('.message').html('THIS IS A TEST');
    });
});

I'm not receiving any errors in the console and the php script works; it returns a response and I can alert() it. It looks like $.post is interfering somehow but I can't figure it out.


text:
Q: HTML Parser for C#
Possible Duplicate:
Looking for C# HTML parser

I did some Google search and got a few hits but I wonder whether there is any particular existing code library that stands out from the crowd. Thanks a lot.

A: A tool commonly recommended for this is the Html Agility Pack. It will take HTML and massage it into well-formed XHTML and then a traversable DOM, so is very useful for the code you find in the wild.
There are some examples and the API documentation here:
http://html-agility-pack.net/api
Some useful links:

*

*How to use HTML Agility pack

*Parsing HTML Documents with the Html Agility Pack

*Crawling a web sites with HtmlAgilityPack

*Getting Started With HTML Agility Pack


text:
Q: I'm trying to create a simple user input via Scanner so people can choose a shape as well as parameters for the shape for it to then be calculated I'm currently in the process of learning Java and I have been given a task to re-write my program. My program at the moment consists of a method called: calculateArea() which is used to calculate 3 different shapes area (a Rectangle, Circle and a Square).
I now need it to accept user input to choose one of the three shapes, for it to accept user input for the parameters (length and width) and for it to then calculate it and after printing the correct result, to close the program.
I already created setters and getters for the different shapes and tested that everything works, what I struggle with is how to implement the Scanner to accept the different Shape inputs.
I tried a simple Scanner input for now like this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter shape to calculate: ");

String shape = keyboard.nextLine();
shape = String.valueOf(rectangle.calculateArea());
System.out.println("Your chosen shapes area is: " + shape);

Though this way, it always calculates Rectangles values as I'm directly calling the method on Rectangle. How would I need to re-write it, for it to take the shape + parameters and then print out the value of said input?
I'm still very new and I don't know how to tackle issues/research like this to find out the right answer, so I would appreciate pointers.

A: Assuming you have a class per shape like
class Rectangle {
        private double height;
        private double width;

        public Rectangle(double height, double width) {
            this.height = height;
            this.width = width;
        }

        public double calculateArea() {
            return height * width;
        }
    }

and
class Circle {
        private double radius;

        public Circle(double radius) {
            this.radius = radius;
        }

        public double calculateArea() {
            return radius * radius * 3.1415;
        }
    }

what you could do is depending on a value of shape String that you get from keyboard Scanner to instantiate a class corresponding to the shape and call its calculateArea() method, e.g.,
        String shape = keyboard.next();
        if ("rectangle".equals(shape)) {
            System.out.println(new Rectangle(keyboard.nextDouble(), keyboard.nextDouble()).calculateArea());
        } else if ("circle".equals(shape)) {
            System.out.println(new Circle(keyboard.nextDouble()).calculateArea());
        } else {
            System.out.println("unknown shape, known shapes are rectangle and circle");
        }


text:
Q: Is Dataset.rdd an action or transformation? one of the way to evaluate if a dataframe is empty or not is to do df.rdd.isEmpty(), however, I see rdd at mycode.scala:123 in sparkUI executions. which makes me wonder if this rdd() function is actually an action is instead of a transformation.
I know that isEmpty() is an action, but I do see a separate stage where isEmpty() at mycode.scala:234, so I think they are different actions?

A: rdd is generated to represent a structured query in "RDD terms" so Spark can execute it. It is an RDD of JVM objects of your type T. If used incorrectly can cause memory problems since:

*

*Transfers internally-managed optimized rows that live outside JVM to the memory space in JVM

*Transforms the binary rows to your business objects (the JVM "true" representation)
The first will increase the JVM memory required for the computation while the latter is an extra transformation step.
For such a simple calculation where you count the number of rows, you'd rather stick to count as the optimized and fairly cheap computation (that can avoid copying objects and applying schema).
Internally, Dataset keeps rows in their InternalRow. That decreases JVM memory requirement for your Spark application. The RDD (from rdd) is computed to represent the Spark transformations that are going to be executed once a Spark action is executed.
Please note that executing rdd creates a RDD and does require some calculations too.
So, yes, rdd might be considered an action as it "executes" the query (i.e. the physical plan of the Dataset that sits behind), but in the end it just gives an RDD (so it can't be an action by definition since Spark actions return a non-RDD value).
As you can see in the code:
  lazy val rdd: RDD[T] = {
    val objectType = exprEnc.deserializer.dataType
    val deserialized = CatalystSerde.deserialize[T](logicalPlan) // <-- HERE see explanation below
    sparkSession.sessionState.executePlan(deserialized).toRdd.mapPartitions { rows =>
      rows.map(_.get(0, objectType).asInstanceOf[T])
    }
  }

rdd is computed lazily and only once.

one of the way to evaluate if a dataframe is empty or not is to do df.rdd.isEmpty()

I wonder where did you find it. I'd just count:

count(): Long Returns the number of rows in the Dataset.

toRdd Lazy Value
If you insist on going fairly low-level to check whether your Dataset is empty or not, I'd rather use Dataset.queryExecution.toRdd instead. That's almost like rdd without this extra copying and applying schema.
df.queryExecution.toRdd.isEmpty

Compare the following RDD lineages and think which may seem better.
val dataset = spark.range(5).withColumn("group", 'id % 2)
scala> dataset.rdd.toDebugString
res1: String =
(8) MapPartitionsRDD[8] at rdd at <console>:26 [] // <-- extra deserialization step
 |  MapPartitionsRDD[7] at rdd at <console>:26 []
 |  MapPartitionsRDD[6] at rdd at <console>:26 []
 |  MapPartitionsRDD[5] at rdd at <console>:26 []
 |  ParallelCollectionRDD[4] at rdd at <console>:26 []

// Compare with a more memory-optimized alternative
// Avoids copies and has no schema
scala> dataset.queryExecution.toRdd.toDebugString
res2: String =
(8) MapPartitionsRDD[11] at toRdd at <console>:26 []
|  MapPartitionsRDD[10] at toRdd at <console>:26 []
|  ParallelCollectionRDD[9] at toRdd at <console>:26 []

From Spark perspective, the transformations are fairly cheap since they don't cause any shuffles, but given the memory requirements change between the computation I'd use the latter (with toRdd).
rdd Lazy Value
rdd represents the content of the Dataset as a (lazily-created) RDD with rows of the JVM type T.
rdd: RDD[T]

As you can see in the source code (pasted above), requesting rdd in the end will trigger one extra computation just to get the RDD.

*

*Creates a new logical plan to deserialize the Dataset's logical plan, i.e. you get extra deserialization from internal binary row format that is managed outside JVM to its corresponding representation as JVM objects living inside JVM (think of GC that you should avoid at all cost)